支持 mac

This commit is contained in:
onvia 2023-07-24 11:13:08 +08:00
parent 413e79966a
commit 516a7f20c1
1940 changed files with 693119 additions and 1178 deletions

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,12 @@
#!/bin/bash
# 安装必要的包
brew install pkg-config cairo pango libpng jpeg giflib librsvg pixman
if [ $? -eq 0 ]; then
ln -s /opt/homebrew/Cellar/jpeg/9e/lib/libjpeg.9.dylib /opt/homebrew/opt/jpeg-turbo/lib/libjpeg.8.dylib
else
echo "Failed to install some packages, exiting."
exit 1
fi

View File

@ -0,0 +1 @@
../color-support/bin.js

View File

@ -0,0 +1 @@
../mkdirp/bin/cmd.js

View File

@ -0,0 +1 @@
../@mapbox/node-pre-gyp/bin/node-pre-gyp

View File

@ -0,0 +1 @@
../nopt/bin/nopt.js

View File

@ -0,0 +1 @@
../rimraf/bin.js

View File

@ -0,0 +1 @@
../semver/bin/semver.js

668
npm-packages/mac-v2.4.x/.package-lock.json generated Normal file
View File

@ -0,0 +1,668 @@
{
"name": "ccc-tnt-psd2ui",
"version": "0.0.1",
"lockfileVersion": 2,
"requires": true,
"packages": {
"node_modules/@mapbox/node-pre-gyp": {
"version": "1.0.11",
"resolved": "https://registry.npmmirror.com/@mapbox/node-pre-gyp/-/node-pre-gyp-1.0.11.tgz",
"integrity": "sha512-Yhlar6v9WQgUp/He7BdgzOz8lqMQ8sU+jkCq7Wx8Myc5YFJLbEe7lgui/V7G1qB1DJykHSGwreceSaD60Y0PUQ==",
"dependencies": {
"detect-libc": "^2.0.0",
"https-proxy-agent": "^5.0.0",
"make-dir": "^3.1.0",
"node-fetch": "^2.6.7",
"nopt": "^5.0.0",
"npmlog": "^5.0.1",
"rimraf": "^3.0.2",
"semver": "^7.3.5",
"tar": "^6.1.11"
},
"bin": {
"node-pre-gyp": "bin/node-pre-gyp"
}
},
"node_modules/@types/base64-js": {
"version": "1.3.0",
"resolved": "https://registry.npmmirror.com/@types/base64-js/-/base64-js-1.3.0.tgz",
"integrity": "sha512-ZmI0sZGAUNXUfMWboWwi4LcfpoVUYldyN6Oe0oJ5cCsHDU/LlRq8nQKPXhYLOx36QYSW9bNIb1vvRrD6K7Llgw=="
},
"node_modules/@types/pako": {
"version": "2.0.0",
"resolved": "https://registry.npmmirror.com/@types/pako/-/pako-2.0.0.tgz",
"integrity": "sha512-10+iaz93qR5WYxTo+PMifD5TSxiOtdRaxBf7INGGXMQgTCu8Z/7GYWYFUOS3q/G0nE5boj1r4FEB+WSy7s5gbA=="
},
"node_modules/abbrev": {
"version": "1.1.1",
"resolved": "https://registry.npmmirror.com/abbrev/-/abbrev-1.1.1.tgz",
"integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q=="
},
"node_modules/ag-psd": {
"version": "15.3.1",
"resolved": "https://registry.npmmirror.com/ag-psd/-/ag-psd-15.3.1.tgz",
"integrity": "sha512-woH/Yb5OduYCvwH2OPLeqSPaWTmgT3n8WYU1/csuUX/BAUSphqH0B/QdRnBvlW7C+53VIH8c3Mm4GErjQx+L3A==",
"dependencies": {
"@types/base64-js": "^1.3.0",
"@types/pako": "^2.0.0",
"base64-js": "^1.5.1",
"pako": "^2.1.0"
}
},
"node_modules/agent-base": {
"version": "6.0.2",
"resolved": "https://registry.npmmirror.com/agent-base/-/agent-base-6.0.2.tgz",
"integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==",
"dependencies": {
"debug": "4"
},
"engines": {
"node": ">= 6.0.0"
}
},
"node_modules/ansi-regex": {
"version": "5.0.1",
"resolved": "https://registry.npmmirror.com/ansi-regex/-/ansi-regex-5.0.1.tgz",
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
"engines": {
"node": ">=8"
}
},
"node_modules/aproba": {
"version": "2.0.0",
"resolved": "https://registry.npmmirror.com/aproba/-/aproba-2.0.0.tgz",
"integrity": "sha512-lYe4Gx7QT+MKGbDsA+Z+he/Wtef0BiwDOlK/XkBrdfsh9J/jPPXbX0tE9x9cl27Tmu5gg3QUbUrQYa/y+KOHPQ=="
},
"node_modules/are-we-there-yet": {
"version": "2.0.0",
"resolved": "https://registry.npmmirror.com/are-we-there-yet/-/are-we-there-yet-2.0.0.tgz",
"integrity": "sha512-Ci/qENmwHnsYo9xKIcUJN5LeDKdJ6R1Z1j9V/J5wyq8nh/mYPEpIKJbBZXtZjG04HiK7zV/p6Vs9952MrMeUIw==",
"dependencies": {
"delegates": "^1.0.0",
"readable-stream": "^3.6.0"
},
"engines": {
"node": ">=10"
}
},
"node_modules/balanced-match": {
"version": "1.0.2",
"resolved": "https://registry.npmmirror.com/balanced-match/-/balanced-match-1.0.2.tgz",
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="
},
"node_modules/base64-js": {
"version": "1.5.1",
"resolved": "https://registry.npmmirror.com/base64-js/-/base64-js-1.5.1.tgz",
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="
},
"node_modules/brace-expansion": {
"version": "1.1.11",
"resolved": "https://registry.npmmirror.com/brace-expansion/-/brace-expansion-1.1.11.tgz",
"integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
"dependencies": {
"balanced-match": "^1.0.0",
"concat-map": "0.0.1"
}
},
"node_modules/canvas": {
"version": "2.11.2",
"resolved": "https://registry.npmmirror.com/canvas/-/canvas-2.11.2.tgz",
"integrity": "sha512-ItanGBMrmRV7Py2Z+Xhs7cT+FNt5K0vPL4p9EZ/UX/Mu7hFbkxSjKF2KVtPwX7UYWp7dRKnrTvReflgrItJbdw==",
"hasInstallScript": true,
"dependencies": {
"@mapbox/node-pre-gyp": "^1.0.0",
"nan": "^2.17.0",
"simple-get": "^3.0.3"
},
"engines": {
"node": ">=6"
}
},
"node_modules/chownr": {
"version": "2.0.0",
"resolved": "https://registry.npmmirror.com/chownr/-/chownr-2.0.0.tgz",
"integrity": "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==",
"engines": {
"node": ">=10"
}
},
"node_modules/color-support": {
"version": "1.1.3",
"resolved": "https://registry.npmmirror.com/color-support/-/color-support-1.1.3.tgz",
"integrity": "sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==",
"bin": {
"color-support": "bin.js"
}
},
"node_modules/concat-map": {
"version": "0.0.1",
"resolved": "https://registry.npmmirror.com/concat-map/-/concat-map-0.0.1.tgz",
"integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg=="
},
"node_modules/console-control-strings": {
"version": "1.1.0",
"resolved": "https://registry.npmmirror.com/console-control-strings/-/console-control-strings-1.1.0.tgz",
"integrity": "sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ=="
},
"node_modules/debug": {
"version": "4.3.4",
"resolved": "https://registry.npmmirror.com/debug/-/debug-4.3.4.tgz",
"integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==",
"dependencies": {
"ms": "2.1.2"
},
"engines": {
"node": ">=6.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
}
},
"node_modules/decompress-response": {
"version": "4.2.1",
"resolved": "https://registry.npmmirror.com/decompress-response/-/decompress-response-4.2.1.tgz",
"integrity": "sha512-jOSne2qbyE+/r8G1VU+G/82LBs2Fs4LAsTiLSHOCOMZQl2OKZ6i8i4IyHemTe+/yIXOtTcRQMzPcgyhoFlqPkw==",
"dependencies": {
"mimic-response": "^2.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/delegates": {
"version": "1.0.0",
"resolved": "https://registry.npmmirror.com/delegates/-/delegates-1.0.0.tgz",
"integrity": "sha512-bd2L678uiWATM6m5Z1VzNCErI3jiGzt6HGY8OVICs40JQq/HALfbyNJmp0UDakEY4pMMaN0Ly5om/B1VI/+xfQ=="
},
"node_modules/detect-libc": {
"version": "2.0.2",
"resolved": "https://registry.npmmirror.com/detect-libc/-/detect-libc-2.0.2.tgz",
"integrity": "sha512-UX6sGumvvqSaXgdKGUsgZWqcUyIXZ/vZTrlRT/iobiKhGL0zL4d3osHj3uqllWJK+i+sixDS/3COVEOFbupFyw==",
"engines": {
"node": ">=8"
}
},
"node_modules/emoji-regex": {
"version": "8.0.0",
"resolved": "https://registry.npmmirror.com/emoji-regex/-/emoji-regex-8.0.0.tgz",
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="
},
"node_modules/fs-extra": {
"version": "10.1.0",
"resolved": "https://registry.npmmirror.com/fs-extra/-/fs-extra-10.1.0.tgz",
"integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==",
"dependencies": {
"graceful-fs": "^4.2.0",
"jsonfile": "^6.0.1",
"universalify": "^2.0.0"
},
"engines": {
"node": ">=12"
}
},
"node_modules/fs-minipass": {
"version": "2.1.0",
"resolved": "https://registry.npmmirror.com/fs-minipass/-/fs-minipass-2.1.0.tgz",
"integrity": "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==",
"dependencies": {
"minipass": "^3.0.0"
},
"engines": {
"node": ">= 8"
}
},
"node_modules/fs-minipass/node_modules/minipass": {
"version": "3.3.6",
"resolved": "https://registry.npmmirror.com/minipass/-/minipass-3.3.6.tgz",
"integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==",
"dependencies": {
"yallist": "^4.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/fs.realpath": {
"version": "1.0.0",
"resolved": "https://registry.npmmirror.com/fs.realpath/-/fs.realpath-1.0.0.tgz",
"integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw=="
},
"node_modules/gauge": {
"version": "3.0.2",
"resolved": "https://registry.npmmirror.com/gauge/-/gauge-3.0.2.tgz",
"integrity": "sha512-+5J6MS/5XksCuXq++uFRsnUd7Ovu1XenbeuIuNRJxYWjgQbPuFhT14lAvsWfqfAmnwluf1OwMjz39HjfLPci0Q==",
"dependencies": {
"aproba": "^1.0.3 || ^2.0.0",
"color-support": "^1.1.2",
"console-control-strings": "^1.0.0",
"has-unicode": "^2.0.1",
"object-assign": "^4.1.1",
"signal-exit": "^3.0.0",
"string-width": "^4.2.3",
"strip-ansi": "^6.0.1",
"wide-align": "^1.1.2"
},
"engines": {
"node": ">=10"
}
},
"node_modules/glob": {
"version": "7.2.3",
"resolved": "https://registry.npmmirror.com/glob/-/glob-7.2.3.tgz",
"integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==",
"dependencies": {
"fs.realpath": "^1.0.0",
"inflight": "^1.0.4",
"inherits": "2",
"minimatch": "^3.1.1",
"once": "^1.3.0",
"path-is-absolute": "^1.0.0"
},
"engines": {
"node": "*"
}
},
"node_modules/graceful-fs": {
"version": "4.2.11",
"resolved": "https://registry.npmmirror.com/graceful-fs/-/graceful-fs-4.2.11.tgz",
"integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="
},
"node_modules/has-unicode": {
"version": "2.0.1",
"resolved": "https://registry.npmmirror.com/has-unicode/-/has-unicode-2.0.1.tgz",
"integrity": "sha512-8Rf9Y83NBReMnx0gFzA8JImQACstCYWUplepDa9xprwwtmgEZUF0h/i5xSA625zB/I37EtrswSST6OXxwaaIJQ=="
},
"node_modules/https-proxy-agent": {
"version": "5.0.1",
"resolved": "https://registry.npmmirror.com/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz",
"integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==",
"dependencies": {
"agent-base": "6",
"debug": "4"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/inflight": {
"version": "1.0.6",
"resolved": "https://registry.npmmirror.com/inflight/-/inflight-1.0.6.tgz",
"integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==",
"dependencies": {
"once": "^1.3.0",
"wrappy": "1"
}
},
"node_modules/inherits": {
"version": "2.0.4",
"resolved": "https://registry.npmmirror.com/inherits/-/inherits-2.0.4.tgz",
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="
},
"node_modules/is-fullwidth-code-point": {
"version": "3.0.0",
"resolved": "https://registry.npmmirror.com/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
"integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
"engines": {
"node": ">=8"
}
},
"node_modules/jsonfile": {
"version": "6.1.0",
"resolved": "https://registry.npmmirror.com/jsonfile/-/jsonfile-6.1.0.tgz",
"integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==",
"dependencies": {
"universalify": "^2.0.0"
},
"optionalDependencies": {
"graceful-fs": "^4.1.6"
}
},
"node_modules/lru-cache": {
"version": "6.0.0",
"resolved": "https://registry.npmmirror.com/lru-cache/-/lru-cache-6.0.0.tgz",
"integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==",
"dependencies": {
"yallist": "^4.0.0"
},
"engines": {
"node": ">=10"
}
},
"node_modules/make-dir": {
"version": "3.1.0",
"resolved": "https://registry.npmmirror.com/make-dir/-/make-dir-3.1.0.tgz",
"integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==",
"dependencies": {
"semver": "^6.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/make-dir/node_modules/semver": {
"version": "6.3.1",
"resolved": "https://registry.npmmirror.com/semver/-/semver-6.3.1.tgz",
"integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
"bin": {
"semver": "bin/semver.js"
}
},
"node_modules/mimic-response": {
"version": "2.1.0",
"resolved": "https://registry.npmmirror.com/mimic-response/-/mimic-response-2.1.0.tgz",
"integrity": "sha512-wXqjST+SLt7R009ySCglWBCFpjUygmCIfD790/kVbiGmUgfYGuB14PiTd5DwVxSV4NcYHjzMkoj5LjQZwTQLEA==",
"engines": {
"node": ">=8"
}
},
"node_modules/minimatch": {
"version": "3.1.2",
"resolved": "https://registry.npmmirror.com/minimatch/-/minimatch-3.1.2.tgz",
"integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
"dependencies": {
"brace-expansion": "^1.1.7"
},
"engines": {
"node": "*"
}
},
"node_modules/minimist": {
"version": "1.2.8",
"resolved": "https://registry.npmmirror.com/minimist/-/minimist-1.2.8.tgz",
"integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA=="
},
"node_modules/minipass": {
"version": "5.0.0",
"resolved": "https://registry.npmmirror.com/minipass/-/minipass-5.0.0.tgz",
"integrity": "sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ==",
"engines": {
"node": ">=8"
}
},
"node_modules/minizlib": {
"version": "2.1.2",
"resolved": "https://registry.npmmirror.com/minizlib/-/minizlib-2.1.2.tgz",
"integrity": "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==",
"dependencies": {
"minipass": "^3.0.0",
"yallist": "^4.0.0"
},
"engines": {
"node": ">= 8"
}
},
"node_modules/minizlib/node_modules/minipass": {
"version": "3.3.6",
"resolved": "https://registry.npmmirror.com/minipass/-/minipass-3.3.6.tgz",
"integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==",
"dependencies": {
"yallist": "^4.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/mkdirp": {
"version": "1.0.4",
"resolved": "https://registry.npmmirror.com/mkdirp/-/mkdirp-1.0.4.tgz",
"integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==",
"bin": {
"mkdirp": "bin/cmd.js"
},
"engines": {
"node": ">=10"
}
},
"node_modules/ms": {
"version": "2.1.2",
"resolved": "https://registry.npmmirror.com/ms/-/ms-2.1.2.tgz",
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
},
"node_modules/nan": {
"version": "2.17.0",
"resolved": "https://registry.npmmirror.com/nan/-/nan-2.17.0.tgz",
"integrity": "sha512-2ZTgtl0nJsO0KQCjEpxcIr5D+Yv90plTitZt9JBfQvVJDS5seMl3FOvsh3+9CoYWXf/1l5OaZzzF6nDm4cagaQ=="
},
"node_modules/node-fetch": {
"version": "2.6.12",
"resolved": "https://registry.npmmirror.com/node-fetch/-/node-fetch-2.6.12.tgz",
"integrity": "sha512-C/fGU2E8ToujUivIO0H+tpQ6HWo4eEmchoPIoXtxCrVghxdKq+QOHqEZW7tuP3KlV3bC8FRMO5nMCC7Zm1VP6g==",
"dependencies": {
"whatwg-url": "^5.0.0"
},
"engines": {
"node": "4.x || >=6.0.0"
},
"peerDependencies": {
"encoding": "^0.1.0"
},
"peerDependenciesMeta": {
"encoding": {
"optional": true
}
}
},
"node_modules/nopt": {
"version": "5.0.0",
"resolved": "https://registry.npmmirror.com/nopt/-/nopt-5.0.0.tgz",
"integrity": "sha512-Tbj67rffqceeLpcRXrT7vKAN8CwfPeIBgM7E6iBkmKLV7bEMwpGgYLGv0jACUsECaa/vuxP0IjEont6umdMgtQ==",
"dependencies": {
"abbrev": "1"
},
"bin": {
"nopt": "bin/nopt.js"
},
"engines": {
"node": ">=6"
}
},
"node_modules/npmlog": {
"version": "5.0.1",
"resolved": "https://registry.npmmirror.com/npmlog/-/npmlog-5.0.1.tgz",
"integrity": "sha512-AqZtDUWOMKs1G/8lwylVjrdYgqA4d9nu8hc+0gzRxlDb1I10+FHBGMXs6aiQHFdCUUlqH99MUMuLfzWDNDtfxw==",
"dependencies": {
"are-we-there-yet": "^2.0.0",
"console-control-strings": "^1.1.0",
"gauge": "^3.0.0",
"set-blocking": "^2.0.0"
}
},
"node_modules/object-assign": {
"version": "4.1.1",
"resolved": "https://registry.npmmirror.com/object-assign/-/object-assign-4.1.1.tgz",
"integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/once": {
"version": "1.4.0",
"resolved": "https://registry.npmmirror.com/once/-/once-1.4.0.tgz",
"integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
"dependencies": {
"wrappy": "1"
}
},
"node_modules/pako": {
"version": "2.1.0",
"resolved": "https://registry.npmmirror.com/pako/-/pako-2.1.0.tgz",
"integrity": "sha512-w+eufiZ1WuJYgPXbV/PO3NCMEc3xqylkKHzp8bxp1uW4qaSNQUkwmLLEc3kKsfz8lpV1F8Ht3U1Cm+9Srog2ug=="
},
"node_modules/path-is-absolute": {
"version": "1.0.1",
"resolved": "https://registry.npmmirror.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz",
"integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/readable-stream": {
"version": "3.6.2",
"resolved": "https://registry.npmmirror.com/readable-stream/-/readable-stream-3.6.2.tgz",
"integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
"dependencies": {
"inherits": "^2.0.3",
"string_decoder": "^1.1.1",
"util-deprecate": "^1.0.1"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/rimraf": {
"version": "3.0.2",
"resolved": "https://registry.npmmirror.com/rimraf/-/rimraf-3.0.2.tgz",
"integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==",
"dependencies": {
"glob": "^7.1.3"
},
"bin": {
"rimraf": "bin.js"
}
},
"node_modules/safe-buffer": {
"version": "5.2.1",
"resolved": "https://registry.npmmirror.com/safe-buffer/-/safe-buffer-5.2.1.tgz",
"integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="
},
"node_modules/semver": {
"version": "7.5.4",
"resolved": "https://registry.npmmirror.com/semver/-/semver-7.5.4.tgz",
"integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==",
"dependencies": {
"lru-cache": "^6.0.0"
},
"bin": {
"semver": "bin/semver.js"
},
"engines": {
"node": ">=10"
}
},
"node_modules/set-blocking": {
"version": "2.0.0",
"resolved": "https://registry.npmmirror.com/set-blocking/-/set-blocking-2.0.0.tgz",
"integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw=="
},
"node_modules/signal-exit": {
"version": "3.0.7",
"resolved": "https://registry.npmmirror.com/signal-exit/-/signal-exit-3.0.7.tgz",
"integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="
},
"node_modules/simple-concat": {
"version": "1.0.1",
"resolved": "https://registry.npmmirror.com/simple-concat/-/simple-concat-1.0.1.tgz",
"integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q=="
},
"node_modules/simple-get": {
"version": "3.1.1",
"resolved": "https://registry.npmmirror.com/simple-get/-/simple-get-3.1.1.tgz",
"integrity": "sha512-CQ5LTKGfCpvE1K0n2us+kuMPbk/q0EKl82s4aheV9oXjFEz6W/Y7oQFVJuU6QG77hRT4Ghb5RURteF5vnWjupA==",
"dependencies": {
"decompress-response": "^4.2.0",
"once": "^1.3.1",
"simple-concat": "^1.0.0"
}
},
"node_modules/string_decoder": {
"version": "1.3.0",
"resolved": "https://registry.npmmirror.com/string_decoder/-/string_decoder-1.3.0.tgz",
"integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
"dependencies": {
"safe-buffer": "~5.2.0"
}
},
"node_modules/string-width": {
"version": "4.2.3",
"resolved": "https://registry.npmmirror.com/string-width/-/string-width-4.2.3.tgz",
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
"dependencies": {
"emoji-regex": "^8.0.0",
"is-fullwidth-code-point": "^3.0.0",
"strip-ansi": "^6.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/strip-ansi": {
"version": "6.0.1",
"resolved": "https://registry.npmmirror.com/strip-ansi/-/strip-ansi-6.0.1.tgz",
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
"dependencies": {
"ansi-regex": "^5.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/tar": {
"version": "6.1.15",
"resolved": "https://registry.npmmirror.com/tar/-/tar-6.1.15.tgz",
"integrity": "sha512-/zKt9UyngnxIT/EAGYuxaMYgOIJiP81ab9ZfkILq4oNLPFX50qyYmu7jRj9qeXoxmJHjGlbH0+cm2uy1WCs10A==",
"dependencies": {
"chownr": "^2.0.0",
"fs-minipass": "^2.0.0",
"minipass": "^5.0.0",
"minizlib": "^2.1.1",
"mkdirp": "^1.0.3",
"yallist": "^4.0.0"
},
"engines": {
"node": ">=10"
}
},
"node_modules/tr46": {
"version": "0.0.3",
"resolved": "https://registry.npmmirror.com/tr46/-/tr46-0.0.3.tgz",
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="
},
"node_modules/universalify": {
"version": "2.0.0",
"resolved": "https://registry.npmmirror.com/universalify/-/universalify-2.0.0.tgz",
"integrity": "sha512-hAZsKq7Yy11Zu1DE0OzWjw7nnLZmJZYTDZZyEFHZdUhV8FkH5MCfoU1XMaxXovpyW5nq5scPqq0ZDP9Zyl04oQ==",
"engines": {
"node": ">= 10.0.0"
}
},
"node_modules/util-deprecate": {
"version": "1.0.2",
"resolved": "https://registry.npmmirror.com/util-deprecate/-/util-deprecate-1.0.2.tgz",
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="
},
"node_modules/webidl-conversions": {
"version": "3.0.1",
"resolved": "https://registry.npmmirror.com/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="
},
"node_modules/whatwg-url": {
"version": "5.0.0",
"resolved": "https://registry.npmmirror.com/whatwg-url/-/whatwg-url-5.0.0.tgz",
"integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",
"dependencies": {
"tr46": "~0.0.3",
"webidl-conversions": "^3.0.0"
}
},
"node_modules/wide-align": {
"version": "1.1.5",
"resolved": "https://registry.npmmirror.com/wide-align/-/wide-align-1.1.5.tgz",
"integrity": "sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg==",
"dependencies": {
"string-width": "^1.0.2 || 2 || 3 || 4"
}
},
"node_modules/wrappy": {
"version": "1.0.2",
"resolved": "https://registry.npmmirror.com/wrappy/-/wrappy-1.0.2.tgz",
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="
},
"node_modules/yallist": {
"version": "4.0.0",
"resolved": "https://registry.npmmirror.com/yallist/-/yallist-4.0.0.tgz",
"integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="
}
}
}

View File

@ -0,0 +1,74 @@
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
#
# ******** NOTE ********
# We have attempted to detect the languages in your repository. Please check
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: "CodeQL"
on:
push:
branches: [ "master" ]
pull_request:
# The branches below must be a subset of the branches above
branches: [ "master" ]
schedule:
- cron: '24 5 * * 4'
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: [ 'javascript' ]
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
# Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support
steps:
- name: Checkout repository
uses: actions/checkout@v3
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v2
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
# queries: security-extended,security-and-quality
# Autobuild attempts to build any compiled languages (C/C++, C#, Go, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v2
# Command-line programs to run using the OS shell.
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
# If the Autobuild fails above, remove it and uncomment the following three lines.
# modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance.
# - run: |
# echo "Run, Build Application using script"
# ./location_of_script_within_repo/buildscript.sh
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2
with:
category: "/language:${{matrix.language}}"

View File

@ -0,0 +1,510 @@
# node-pre-gyp changelog
## 1.0.11
- Fixes dependabot alert [CVE-2021-44906](https://nvd.nist.gov/vuln/detail/CVE-2021-44906)
## 1.0.10
- Upgraded minimist to 1.2.6 to address dependabot alert [CVE-2021-44906](https://nvd.nist.gov/vuln/detail/CVE-2021-44906)
## 1.0.9
- Upgraded node-fetch to 2.6.7 to address [CVE-2022-0235](https://www.cve.org/CVERecord?id=CVE-2022-0235)
- Upgraded detect-libc to 2.0.0 to use non-blocking NodeJS(>=12) Report API
## 1.0.8
- Downgraded npmlog to maintain node v10 and v8 support (https://github.com/mapbox/node-pre-gyp/pull/624)
## 1.0.7
- Upgraded nyc and npmlog to address https://github.com/advisories/GHSA-93q8-gq69-wqmw
## 1.0.6
- Added node v17 to the internal node releases listing
- Upgraded various dependencies declared in package.json to latest major versions (node-fetch from 2.6.1 to 2.6.5, npmlog from 4.1.2 to 5.01, semver from 7.3.4 to 7.3.5, and tar from 6.1.0 to 6.1.11)
- Fixed bug in `staging_host` parameter (https://github.com/mapbox/node-pre-gyp/pull/590)
## 1.0.5
- Fix circular reference warning with node >= v14
## 1.0.4
- Added node v16 to the internal node releases listing
## 1.0.3
- Improved support configuring s3 uploads (solves https://github.com/mapbox/node-pre-gyp/issues/571)
- New options added in https://github.com/mapbox/node-pre-gyp/pull/576: 'bucket', 'region', and `s3ForcePathStyle`
## 1.0.2
- Fixed regression in proxy support (https://github.com/mapbox/node-pre-gyp/issues/572)
## 1.0.1
- Switched from mkdirp@1.0.4 to make-dir@3.1.0 to avoid this bug: https://github.com/isaacs/node-mkdirp/issues/31
## 1.0.0
- Module is now name-spaced at `@mapbox/node-pre-gyp` and the original `node-pre-gyp` is deprecated.
- New: support for staging and production s3 targets (see README.md)
- BREAKING: no longer supporting `node_pre_gyp_accessKeyId` & `node_pre_gyp_secretAccessKey`, use `AWS_ACCESS_KEY_ID` & `AWS_SECRET_ACCESS_KEY` instead to authenticate against s3 for `info`, `publish`, and `unpublish` commands.
- Dropped node v6 support, added node v14 support
- Switched tests to use mapbox-owned bucket for testing
- Added coverage tracking and linting with eslint
- Added back support for symlinks inside the tarball
- Upgraded all test apps to N-API/node-addon-api
- New: support for staging and production s3 targets (see README.md)
- Added `node_pre_gyp_s3_host` env var which has priority over the `--s3_host` option or default.
- Replaced needle with node-fetch
- Added proxy support for node-fetch
- Upgraded to mkdirp@1.x
## 0.17.0
- Got travis + appveyor green again
- Added support for more node versions
## 0.16.0
- Added Node 15 support in the local database (https://github.com/mapbox/node-pre-gyp/pull/520)
## 0.15.0
- Bump dependency on `mkdirp` from `^0.5.1` to `^0.5.3` (https://github.com/mapbox/node-pre-gyp/pull/492)
- Bump dependency on `needle` from `^2.2.1` to `^2.5.0` (https://github.com/mapbox/node-pre-gyp/pull/502)
- Added Node 14 support in the local database (https://github.com/mapbox/node-pre-gyp/pull/501)
## 0.14.0
- Defer modules requires in napi.js (https://github.com/mapbox/node-pre-gyp/pull/434)
- Bump dependency on `tar` from `^4` to `^4.4.2` (https://github.com/mapbox/node-pre-gyp/pull/454)
- Support extracting compiled binary from local offline mirror (https://github.com/mapbox/node-pre-gyp/pull/459)
- Added Node 13 support in the local database (https://github.com/mapbox/node-pre-gyp/pull/483)
## 0.13.0
- Added Node 12 support in the local database (https://github.com/mapbox/node-pre-gyp/pull/449)
## 0.12.0
- Fixed double-build problem with node v10 (https://github.com/mapbox/node-pre-gyp/pull/428)
- Added node 11 support in the local database (https://github.com/mapbox/node-pre-gyp/pull/422)
## 0.11.0
- Fixed double-install problem with node v10
- Significant N-API improvements (https://github.com/mapbox/node-pre-gyp/pull/405)
## 0.10.3
- Now will use `request` over `needle` if request is installed. By default `needle` is used for `https`. This should unbreak proxy support that regressed in v0.9.0
## 0.10.2
- Fixed rc/deep-extent security vulnerability
- Fixed broken reinstall script do to incorrectly named get_best_napi_version
## 0.10.1
- Fix needle error event (@medns)
## 0.10.0
- Allow for a single-level module path when packing @allenluce (https://github.com/mapbox/node-pre-gyp/pull/371)
- Log warnings instead of errors when falling back @xzyfer (https://github.com/mapbox/node-pre-gyp/pull/366)
- Add Node.js v10 support to tests (https://github.com/mapbox/node-pre-gyp/pull/372)
- Remove retire.js from CI (https://github.com/mapbox/node-pre-gyp/pull/372)
- Remove support for Node.js v4 due to [EOL on April 30th, 2018](https://github.com/nodejs/Release/blob/7dd52354049cae99eed0e9fe01345b0722a86fde/schedule.json#L14)
- Update appveyor tests to install default NPM version instead of NPM v2.x for all Windows builds (https://github.com/mapbox/node-pre-gyp/pull/375)
## 0.9.1
- Fixed regression (in v0.9.0) with support for http redirects @allenluce (https://github.com/mapbox/node-pre-gyp/pull/361)
## 0.9.0
- Switched from using `request` to `needle` to reduce size of module deps (https://github.com/mapbox/node-pre-gyp/pull/350)
## 0.8.0
- N-API support (@inspiredware)
## 0.7.1
- Upgraded to tar v4.x
## 0.7.0
- Updated request and hawk (#347)
- Dropped node v0.10.x support
## 0.6.40
- Improved error reporting if an install fails
## 0.6.39
- Support for node v9
- Support for versioning on `{libc}` to allow binaries to work on non-glic linux systems like alpine linux
## 0.6.38
- Maintaining compatibility (for v0.6.x series) with node v0.10.x
## 0.6.37
- Solved one part of #276: now now deduce the node ABI from the major version for node >= 2 even when not stored in the abi_crosswalk.json
- Fixed docs to avoid mentioning the deprecated and dangerous `prepublish` in package.json (#291)
- Add new node versions to crosswalk
- Ported tests to use tape instead of mocha
- Got appveyor tests passing by downgrading npm and node-gyp
## 0.6.36
- Removed the running of `testbinary` during install. Because this was regressed for so long, it is too dangerous to re-enable by default. Developers needing validation can call `node-pre-gyp testbinary` directory.
- Fixed regression in v0.6.35 for electron installs (now skipping binary validation which is not yet supported for electron)
## 0.6.35
- No longer recommending `npm ls` in `prepublish` (#291)
- Fixed testbinary command (#283) @szdavid92
## 0.6.34
- Added new node versions to crosswalk, including v8
- Upgraded deps to latest versions, started using `^` instead of `~` for all deps.
## 0.6.33
- Improved support for yarn
## 0.6.32
- Honor npm configuration for CA bundles (@heikkipora)
- Add node-pre-gyp and npm versions to user agent (@addaleax)
- Updated various deps
- Add known node version for v7.x
## 0.6.31
- Updated various deps
## 0.6.30
- Update to npmlog@4.x and semver@5.3.x
- Add known node version for v6.5.0
## 0.6.29
- Add known node versions for v0.10.45, v0.12.14, v4.4.4, v5.11.1, and v6.1.0
## 0.6.28
- Now more verbose when remote binaries are not available. This is needed since npm is increasingly more quiet by default
and users need to know why builds are falling back to source compiles that might then error out.
## 0.6.27
- Add known node version for node v6
- Stopped bundling dependencies
- Documented method for module authors to avoid bundling node-pre-gyp
- See https://github.com/mapbox/node-pre-gyp/tree/master#configuring for details
## 0.6.26
- Skip validation for nw runtime (https://github.com/mapbox/node-pre-gyp/pull/181) via @fleg
## 0.6.25
- Improved support for auto-detection of electron runtime in `node-pre-gyp.find()`
- Pull request from @enlight - https://github.com/mapbox/node-pre-gyp/pull/187
- Add known node version for 4.4.1 and 5.9.1
## 0.6.24
- Add known node version for 5.8.0, 5.9.0, and 4.4.0.
## 0.6.23
- Add known node version for 0.10.43, 0.12.11, 4.3.2, and 5.7.1.
## 0.6.22
- Add known node version for 4.3.1, and 5.7.0.
## 0.6.21
- Add known node version for 0.10.42, 0.12.10, 4.3.0, and 5.6.0.
## 0.6.20
- Add known node version for 4.2.5, 4.2.6, 5.4.0, 5.4.1,and 5.5.0.
## 0.6.19
- Add known node version for 4.2.4
## 0.6.18
- Add new known node versions for 0.10.x, 0.12.x, 4.x, and 5.x
## 0.6.17
- Re-tagged to fix packaging problem of `Error: Cannot find module 'isarray'`
## 0.6.16
- Added known version in crosswalk for 5.1.0.
## 0.6.15
- Upgraded tar-pack (https://github.com/mapbox/node-pre-gyp/issues/182)
- Support custom binary hosting mirror (https://github.com/mapbox/node-pre-gyp/pull/170)
- Added known version in crosswalk for 4.2.2.
## 0.6.14
- Added node 5.x version
## 0.6.13
- Added more known node 4.x versions
## 0.6.12
- Added support for [Electron](http://electron.atom.io/). Just pass the `--runtime=electron` flag when building/installing. Thanks @zcbenz
## 0.6.11
- Added known node and io.js versions including more 3.x and 4.x versions
## 0.6.10
- Added known node and io.js versions including 3.x and 4.x versions
- Upgraded `tar` dep
## 0.6.9
- Upgraded `rc` dep
- Updated known io.js version: v2.4.0
## 0.6.8
- Upgraded `semver` and `rimraf` deps
- Updated known node and io.js versions
## 0.6.7
- Fixed `node_abi` versions for io.js 1.1.x -> 1.8.x (should be 43, but was stored as 42) (refs https://github.com/iojs/build/issues/94)
## 0.6.6
- Updated with known io.js 2.0.0 version
## 0.6.5
- Now respecting `npm_config_node_gyp` (https://github.com/npm/npm/pull/4887)
- Updated to semver@4.3.2
- Updated known node v0.12.x versions and io.js 1.x versions.
## 0.6.4
- Improved support for `io.js` (@fengmk2)
- Test coverage improvements (@mikemorris)
- Fixed support for `--dist-url` that regressed in 0.6.3
## 0.6.3
- Added support for passing raw options to node-gyp using `--` separator. Flags passed after
the `--` to `node-pre-gyp configure` will be passed directly to gyp while flags passed
after the `--` will be passed directly to make/visual studio.
- Added `node-pre-gyp configure` command to be able to call `node-gyp configure` directly
- Fix issue with require validation not working on windows 7 (@edgarsilva)
## 0.6.2
- Support for io.js >= v1.0.2
- Deferred require of `request` and `tar` to help speed up command line usage of `node-pre-gyp`.
## 0.6.1
- Fixed bundled `tar` version
## 0.6.0
- BREAKING: node odd releases like v0.11.x now use `major.minor.patch` for `{node_abi}` instead of `NODE_MODULE_VERSION` (#124)
- Added support for `toolset` option in versioning. By default is an empty string but `--toolset` can be passed to publish or install to select alternative binaries that target a custom toolset like C++11. For example to target Visual Studio 2014 modules like node-sqlite3 use `--toolset=v140`.
- Added support for `--no-rollback` option to request that a failed binary test does not remove the binary module leaves it in place.
- Added support for `--update-binary` option to request an existing binary be re-installed and the check for a valid local module be skipped.
- Added support for passing build options from `npm` through `node-pre-gyp` to `node-gyp`: `--nodedir`, `--disturl`, `--python`, and `--msvs_version`
## 0.5.31
- Added support for deducing node_abi for node.js runtime from previous release if the series is even
- Added support for --target=0.10.33
## 0.5.30
- Repackaged with latest bundled deps
## 0.5.29
- Added support for semver `build`.
- Fixed support for downloading from urls that include `+`.
## 0.5.28
- Now reporting unix style paths only in reveal command
## 0.5.27
- Fixed support for auto-detecting s3 bucket name when it contains `.` - @taavo
- Fixed support for installing when path contains a `'` - @halfdan
- Ported tests to mocha
## 0.5.26
- Fix node-webkit support when `--target` option is not provided
## 0.5.25
- Fix bundling of deps
## 0.5.24
- Updated ABI crosswalk to incldue node v0.10.30 and v0.10.31
## 0.5.23
- Added `reveal` command. Pass no options to get all versioning data as json. Pass a second arg to grab a single versioned property value
- Added support for `--silent` (shortcut for `--loglevel=silent`)
## 0.5.22
- Fixed node-webkit versioning name (NOTE: node-webkit support still experimental)
## 0.5.21
- New package to fix `shasum check failed` error with v0.5.20
## 0.5.20
- Now versioning node-webkit binaries based on major.minor.patch - assuming no compatible ABI across versions (#90)
## 0.5.19
- Updated to know about more node-webkit releases
## 0.5.18
- Updated to know about more node-webkit releases
## 0.5.17
- Updated to know about node v0.10.29 release
## 0.5.16
- Now supporting all aws-sdk configuration parameters (http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/node-configuring.html) (#86)
## 0.5.15
- Fixed installation of windows packages sub directories on unix systems (#84)
## 0.5.14
- Finished support for cross building using `--target_platform` option (#82)
- Now skipping binary validation on install if target arch/platform do not match the host.
- Removed multi-arch validing for OS X since it required a FAT node.js binary
## 0.5.13
- Fix problem in 0.5.12 whereby the wrong versions of mkdirp and semver where bundled.
## 0.5.12
- Improved support for node-webkit (@Mithgol)
## 0.5.11
- Updated target versions listing
## 0.5.10
- Fixed handling of `-debug` flag passed directory to node-pre-gyp (#72)
- Added optional second arg to `node_pre_gyp.find` to customize the default versioning options used to locate the runtime binary
- Failed install due to `testbinary` check failure no longer leaves behind binary (#70)
## 0.5.9
- Fixed regression in `testbinary` command causing installs to fail on windows with 0.5.7 (#60)
## 0.5.8
- Started bundling deps
## 0.5.7
- Fixed the `testbinary` check, which is used to determine whether to re-download or source compile, to work even in complex dependency situations (#63)
- Exposed the internal `testbinary` command in node-pre-gyp command line tool
- Fixed minor bug so that `fallback_to_build` option is always respected
## 0.5.6
- Added support for versioning on the `name` value in `package.json` (#57).
- Moved to using streams for reading tarball when publishing (#52)
## 0.5.5
- Improved binary validation that also now works with node-webkit (@Mithgol)
- Upgraded test apps to work with node v0.11.x
- Improved test coverage
## 0.5.4
- No longer depends on external install of node-gyp for compiling builds.
## 0.5.3
- Reverted fix for debian/nodejs since it broke windows (#45)
## 0.5.2
- Support for debian systems where the node binary is named `nodejs` (#45)
- Added `bin/node-pre-gyp.cmd` to be able to run command on windows locally (npm creates an .npm automatically when globally installed)
- Updated abi-crosswalk with node v0.10.26 entry.
## 0.5.1
- Various minor bug fixes, several improving windows support for publishing.
## 0.5.0
- Changed property names in `binary` object: now required are `module_name`, `module_path`, and `host`.
- Now `module_path` supports versioning, which allows developers to opt-in to using a versioned install path (#18).
- Added `remote_path` which also supports versioning.
- Changed `remote_uri` to `host`.
## 0.4.2
- Added support for `--target` flag to request cross-compile against a specific node/node-webkit version.
- Added preliminary support for node-webkit
- Fixed support for `--target_arch` option being respected in all cases.
## 0.4.1
- Fixed exception when only stderr is available in binary test (@bendi / #31)
## 0.4.0
- Enforce only `https:` based remote publishing access.
- Added `node-pre-gyp info` command to display listing of published binaries
- Added support for changing the directory node-pre-gyp should build in with the `-C/--directory` option.
- Added support for S3 prefixes.
## 0.3.1
- Added `unpublish` command.
- Fixed module path construction in tests.
- Added ability to disable falling back to build behavior via `npm install --fallback-to-build=false` which overrides setting in a depedencies package.json `install` target.
## 0.3.0
- Support for packaging all files in `module_path` directory - see `app4` for example
- Added `testpackage` command.
- Changed `clean` command to only delete `.node` not entire `build` directory since node-gyp will handle that.
- `.node` modules must be in a folder of there own since tar-pack will remove everything when it unpacks.

View File

@ -0,0 +1,27 @@
Copyright (c), Mapbox
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of node-pre-gyp nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@ -0,0 +1,742 @@
# @mapbox/node-pre-gyp
#### @mapbox/node-pre-gyp makes it easy to publish and install Node.js C++ addons from binaries
[![Build Status](https://travis-ci.com/mapbox/node-pre-gyp.svg?branch=master)](https://travis-ci.com/mapbox/node-pre-gyp)
[![Build status](https://ci.appveyor.com/api/projects/status/3nxewb425y83c0gv)](https://ci.appveyor.com/project/Mapbox/node-pre-gyp)
`@mapbox/node-pre-gyp` stands between [npm](https://github.com/npm/npm) and [node-gyp](https://github.com/Tootallnate/node-gyp) and offers a cross-platform method of binary deployment.
### Special note on previous package
On Feb 9th, 2021 `@mapbox/node-pre-gyp@1.0.0` was [released](./CHANGELOG.md). Older, unscoped versions that are not part of the `@mapbox` org are deprecated and only `@mapbox/node-pre-gyp` will see updates going forward. To upgrade to the new package do:
```
npm uninstall node-pre-gyp --save
npm install @mapbox/node-pre-gyp --save
```
### Features
- A command line tool called `node-pre-gyp` that can install your package's C++ module from a binary.
- A variety of developer targeted commands for packaging, testing, and publishing binaries.
- A JavaScript module that can dynamically require your installed binary: `require('@mapbox/node-pre-gyp').find`
For a hello world example of a module packaged with `node-pre-gyp` see <https://github.com/springmeyer/node-addon-example> and [the wiki ](https://github.com/mapbox/node-pre-gyp/wiki/Modules-using-node-pre-gyp) for real world examples.
## Credits
- The module is modeled after [node-gyp](https://github.com/Tootallnate/node-gyp) by [@Tootallnate](https://github.com/Tootallnate)
- Motivation for initial development came from [@ErisDS](https://github.com/ErisDS) and the [Ghost Project](https://github.com/TryGhost/Ghost).
- Development is sponsored by [Mapbox](https://www.mapbox.com/)
## FAQ
See the [Frequently Ask Questions](https://github.com/mapbox/node-pre-gyp/wiki/FAQ).
## Depends
- Node.js >= node v8.x
## Install
`node-pre-gyp` is designed to be installed as a local dependency of your Node.js C++ addon and accessed like:
./node_modules/.bin/node-pre-gyp --help
But you can also install it globally:
npm install @mapbox/node-pre-gyp -g
## Usage
### Commands
View all possible commands:
node-pre-gyp --help
- clean - Remove the entire folder containing the compiled .node module
- install - Install pre-built binary for module
- reinstall - Run "clean" and "install" at once
- build - Compile the module by dispatching to node-gyp or nw-gyp
- rebuild - Run "clean" and "build" at once
- package - Pack binary into tarball
- testpackage - Test that the staged package is valid
- publish - Publish pre-built binary
- unpublish - Unpublish pre-built binary
- info - Fetch info on published binaries
You can also chain commands:
node-pre-gyp clean build unpublish publish info
### Options
Options include:
- `-C/--directory`: run the command in this directory
- `--build-from-source`: build from source instead of using pre-built binary
- `--update-binary`: reinstall by replacing previously installed local binary with remote binary
- `--runtime=node-webkit`: customize the runtime: `node`, `electron` and `node-webkit` are the valid options
- `--fallback-to-build`: fallback to building from source if pre-built binary is not available
- `--target=0.4.0`: Pass the target node or node-webkit version to compile against
- `--target_arch=ia32`: Pass the target arch and override the host `arch`. Any value that is [supported by Node.js](https://nodejs.org/api/os.html#osarch) is valid.
- `--target_platform=win32`: Pass the target platform and override the host `platform`. Valid values are `linux`, `darwin`, `win32`, `sunos`, `freebsd`, `openbsd`, and `aix`.
Both `--build-from-source` and `--fallback-to-build` can be passed alone or they can provide values. You can pass `--fallback-to-build=false` to override the option as declared in package.json. In addition to being able to pass `--build-from-source` you can also pass `--build-from-source=myapp` where `myapp` is the name of your module.
For example: `npm install --build-from-source=myapp`. This is useful if:
- `myapp` is referenced in the package.json of a larger app and therefore `myapp` is being installed as a dependency with `npm install`.
- The larger app also depends on other modules installed with `node-pre-gyp`
- You only want to trigger a source compile for `myapp` and the other modules.
### Configuring
This is a guide to configuring your module to use node-pre-gyp.
#### 1) Add new entries to your `package.json`
- Add `@mapbox/node-pre-gyp` to `dependencies`
- Add `aws-sdk` as a `devDependency`
- Add a custom `install` script
- Declare a `binary` object
This looks like:
```js
"dependencies" : {
"@mapbox/node-pre-gyp": "1.x"
},
"devDependencies": {
"aws-sdk": "2.x"
}
"scripts": {
"install": "node-pre-gyp install --fallback-to-build"
},
"binary": {
"module_name": "your_module",
"module_path": "./lib/binding/",
"host": "https://your_module.s3-us-west-1.amazonaws.com"
}
```
For a full example see [node-addon-examples's package.json](https://github.com/springmeyer/node-addon-example/blob/master/package.json).
Let's break this down:
- Dependencies need to list `node-pre-gyp`
- Your devDependencies should list `aws-sdk` so that you can run `node-pre-gyp publish` locally or a CI system. We recommend using `devDependencies` only since `aws-sdk` is large and not needed for `node-pre-gyp install` since it only uses http to fetch binaries
- Your `scripts` section should override the `install` target with `"install": "node-pre-gyp install --fallback-to-build"`. This allows node-pre-gyp to be used instead of the default npm behavior of always source compiling with `node-gyp` directly.
- Your package.json should contain a `binary` section describing key properties you provide to allow node-pre-gyp to package optimally. They are detailed below.
Note: in the past we recommended putting `@mapbox/node-pre-gyp` in the `bundledDependencies`, but we no longer recommend this. In the past there were npm bugs (with node versions 0.10.x) that could lead to node-pre-gyp not being available at the right time during install (unless we bundled). This should no longer be the case. Also, for a time we recommended using `"preinstall": "npm install @mapbox/node-pre-gyp"` as an alternative method to avoid needing to bundle. But this did not behave predictably across all npm versions - see https://github.com/mapbox/node-pre-gyp/issues/260 for the details. So we do not recommend using `preinstall` to install `@mapbox/node-pre-gyp`. More history on this at https://github.com/strongloop/fsevents/issues/157#issuecomment-265545908.
##### The `binary` object has three required properties
###### module_name
The name of your native node module. This value must:
- Match the name passed to [the NODE_MODULE macro](http://nodejs.org/api/addons.html#addons_hello_world)
- Must be a valid C variable name (e.g. it cannot contain `-`)
- Should not include the `.node` extension.
###### module_path
The location your native module is placed after a build. This should be an empty directory without other Javascript files. This entire directory will be packaged in the binary tarball. When installing from a remote package this directory will be overwritten with the contents of the tarball.
Note: This property supports variables based on [Versioning](#versioning).
###### host
A url to the remote location where you've published tarball binaries (must be `https` not `http`).
It is highly recommended that you use Amazon S3. The reasons are:
- Various node-pre-gyp commands like `publish` and `info` only work with an S3 host.
- S3 is a very solid hosting platform for distributing large files.
- We provide detail documentation for using [S3 hosting](#s3-hosting) with node-pre-gyp.
Why then not require S3? Because while some applications using node-pre-gyp need to distribute binaries as large as 20-30 MB, others might have very small binaries and might wish to store them in a GitHub repo. This is not recommended, but if an author really wants to host in a non-S3 location then it should be possible.
It should also be mentioned that there is an optional and entirely separate npm module called [node-pre-gyp-github](https://github.com/bchr02/node-pre-gyp-github) which is intended to complement node-pre-gyp and be installed along with it. It provides the ability to store and publish your binaries within your repositories GitHub Releases if you would rather not use S3 directly. Installation and usage instructions can be found [here](https://github.com/bchr02/node-pre-gyp-github), but the basic premise is that instead of using the ```node-pre-gyp publish``` command you would use ```node-pre-gyp-github publish```.
##### The `binary` object other optional S3 properties
If you are not using a standard s3 path like `bucket_name.s3(.-)region.amazonaws.com`, you might get an error on `publish` because node-pre-gyp extracts the region and bucket from the `host` url. For example, you may have an on-premises s3-compatible storage server, or may have configured a specific dns redirecting to an s3 endpoint. In these cases, you can explicitly set the `region` and `bucket` properties to tell node-pre-gyp to use these values instead of guessing from the `host` property. The following values can be used in the `binary` section:
###### host
The url to the remote server root location (must be `https` not `http`).
###### bucket
The bucket name where your tarball binaries should be located.
###### region
Your S3 server region.
###### s3ForcePathStyle
Set `s3ForcePathStyle` to true if the endpoint url should not be prefixed with the bucket name. If false (default), the server endpoint would be constructed as `bucket_name.your_server.com`.
##### The `binary` object has optional properties
###### remote_path
It **is recommended** that you customize this property. This is an extra path to use for publishing and finding remote tarballs. The default value for `remote_path` is `""` meaning that if you do not provide it then all packages will be published at the base of the `host`. It is recommended to provide a value like `./{name}/v{version}` to help organize remote packages in the case that you choose to publish multiple node addons to the same `host`.
Note: This property supports variables based on [Versioning](#versioning).
###### package_name
It is **not recommended** to override this property unless you are also overriding the `remote_path`. This is the versioned name of the remote tarball containing the binary `.node` module and any supporting files you've placed inside the `module_path` directory. Unless you specify `package_name` in your `package.json` then it defaults to `{module_name}-v{version}-{node_abi}-{platform}-{arch}.tar.gz` which allows your binary to work across node versions, platforms, and architectures. If you are using `remote_path` that is also versioned by `./{module_name}/v{version}` then you could remove these variables from the `package_name` and just use: `{node_abi}-{platform}-{arch}.tar.gz`. Then your remote tarball will be looked up at, for example, `https://example.com/your-module/v0.1.0/node-v11-linux-x64.tar.gz`.
Avoiding the version of your module in the `package_name` and instead only embedding in a directory name can be useful when you want to make a quick tag of your module that does not change any C++ code. In this case you can just copy binaries to the new version behind the scenes like:
```sh
aws s3 sync --acl public-read s3://mapbox-node-binary/sqlite3/v3.0.3/ s3://mapbox-node-binary/sqlite3/v3.0.4/
```
Note: This property supports variables based on [Versioning](#versioning).
#### 2) Add a new target to binding.gyp
`node-pre-gyp` calls out to `node-gyp` to compile the module and passes variables along like [module_name](#module_name) and [module_path](#module_path).
A new target must be added to `binding.gyp` that moves the compiled `.node` module from `./build/Release/module_name.node` into the directory specified by `module_path`.
Add a target like this at the end of your `targets` list:
```js
{
"target_name": "action_after_build",
"type": "none",
"dependencies": [ "<(module_name)" ],
"copies": [
{
"files": [ "<(PRODUCT_DIR)/<(module_name).node" ],
"destination": "<(module_path)"
}
]
}
```
For a full example see [node-addon-example's binding.gyp](https://github.com/springmeyer/node-addon-example/blob/2ff60a8ded7f042864ad21db00c3a5a06cf47075/binding.gyp).
#### 3) Dynamically require your `.node`
Inside the main js file that requires your addon module you are likely currently doing:
```js
var binding = require('../build/Release/binding.node');
```
or:
```js
var bindings = require('./bindings')
```
Change those lines to:
```js
var binary = require('@mapbox/node-pre-gyp');
var path = require('path');
var binding_path = binary.find(path.resolve(path.join(__dirname,'./package.json')));
var binding = require(binding_path);
```
For a full example see [node-addon-example's index.js](https://github.com/springmeyer/node-addon-example/blob/2ff60a8ded7f042864ad21db00c3a5a06cf47075/index.js#L1-L4)
#### 4) Build and package your app
Now build your module from source:
npm install --build-from-source
The `--build-from-source` tells `node-pre-gyp` to not look for a remote package and instead dispatch to node-gyp to build.
Now `node-pre-gyp` should now also be installed as a local dependency so the command line tool it offers can be found at `./node_modules/.bin/node-pre-gyp`.
#### 5) Test
Now `npm test` should work just as it did before.
#### 6) Publish the tarball
Then package your app:
./node_modules/.bin/node-pre-gyp package
Once packaged, now you can publish:
./node_modules/.bin/node-pre-gyp publish
Currently the `publish` command pushes your binary to S3. This requires:
- You have installed `aws-sdk` with `npm install aws-sdk`
- You have created a bucket already.
- The `host` points to an S3 http or https endpoint.
- You have configured node-pre-gyp to read your S3 credentials (see [S3 hosting](#s3-hosting) for details).
You can also host your binaries elsewhere. To do this requires:
- You manually publish the binary created by the `package` command to an `https` endpoint
- Ensure that the `host` value points to your custom `https` endpoint.
#### 7) Automate builds
Now you need to publish builds for all the platforms and node versions you wish to support. This is best automated.
- See [Appveyor Automation](#appveyor-automation) for how to auto-publish builds on Windows.
- See [Travis Automation](#travis-automation) for how to auto-publish builds on OS X and Linux.
#### 8) You're done!
Now publish your module to the npm registry. Users will now be able to install your module from a binary.
What will happen is this:
1. `npm install <your package>` will pull from the npm registry
2. npm will run the `install` script which will call out to `node-pre-gyp`
3. `node-pre-gyp` will fetch the binary `.node` module and unpack in the right place
4. Assuming that all worked, you are done
If a a binary was not available for a given platform and `--fallback-to-build` was used then `node-gyp rebuild` will be called to try to source compile the module.
#### 9) One more option
It may be that you want to work with two s3 buckets, one for staging and one for production; this
arrangement makes it less likely to accidentally overwrite a production binary. It also allows the production
environment to have more restrictive permissions than staging while still enabling publishing when
developing and testing.
The binary.host property can be set at execution time. In order to do so all of the following conditions
must be true.
- binary.host is falsey or not present
- binary.staging_host is not empty
- binary.production_host is not empty
If any of these checks fail then the operation will not perform execution time determination of the s3 target.
If the command being executed is either "publish" or "unpublish" then the default is set to `binary.staging_host`. In all other cases
the default is `binary.production_host`.
The command-line options `--s3_host=staging` or `--s3_host=production` override the default. If `s3_host`
is present and not `staging` or `production` an exception is thrown.
This allows installing from staging by specifying `--s3_host=staging`. And it requires specifying
`--s3_option=production` in order to publish to, or unpublish from, production, making accidental errors less likely.
## Node-API Considerations
[Node-API](https://nodejs.org/api/n-api.html#n_api_node_api), which was previously known as N-API, is an ABI-stable alternative to previous technologies such as [nan](https://github.com/nodejs/nan) which are tied to a specific Node runtime engine. Node-API is Node runtime engine agnostic and guarantees modules created today will continue to run, without changes, into the future.
Using `node-pre-gyp` with Node-API projects requires a handful of additional configuration values and imposes some additional requirements.
The most significant difference is that an Node-API module can be coded to target multiple Node-API versions. Therefore, an Node-API module must declare in its `package.json` file which Node-API versions the module is designed to run against. In addition, since multiple builds may be required for a single module, path and file names must be specified in way that avoids naming conflicts.
### The `napi_versions` array property
A Node-API module must declare in its `package.json` file, the Node-API versions the module is intended to support. This is accomplished by including an `napi-versions` array property in the `binary` object. For example:
```js
"binary": {
"module_name": "your_module",
"module_path": "your_module_path",
"host": "https://your_bucket.s3-us-west-1.amazonaws.com",
"napi_versions": [1,3]
}
```
If the `napi_versions` array property is *not* present, `node-pre-gyp` operates as it always has. Including the `napi_versions` array property instructs `node-pre-gyp` that this is a Node-API module build.
When the `napi_versions` array property is present, `node-pre-gyp` fires off multiple operations, one for each of the Node-API versions in the array. In the example above, two operations are initiated, one for Node-API version 1 and second for Node-API version 3. How this version number is communicated is described next.
### The `napi_build_version` value
For each of the Node-API module operations `node-pre-gyp` initiates, it ensures that the `napi_build_version` is set appropriately.
This value is of importance in two areas:
1. The C/C++ code which needs to know against which Node-API version it should compile.
2. `node-pre-gyp` itself which must assign appropriate path and file names to avoid collisions.
### Defining `NAPI_VERSION` for the C/C++ code
The `napi_build_version` value is communicated to the C/C++ code by adding this code to the `binding.gyp` file:
```
"defines": [
"NAPI_VERSION=<(napi_build_version)",
]
```
This ensures that `NAPI_VERSION`, an integer value, is declared appropriately to the C/C++ code for each build.
> Note that earlier versions of this document recommended defining the symbol `NAPI_BUILD_VERSION`. `NAPI_VERSION` is preferred because it used by the Node-API C/C++ headers to configure the specific Node-API versions being requested.
### Path and file naming requirements in `package.json`
Since `node-pre-gyp` fires off multiple operations for each request, it is essential that path and file names be created in such a way as to avoid collisions. This is accomplished by imposing additional path and file naming requirements.
Specifically, when performing Node-API builds, the `{napi_build_version}` text configuration value *must* be present in the `module_path` property. In addition, the `{napi_build_version}` text configuration value *must* be present in either the `remote_path` or `package_name` property. (No problem if it's in both.)
Here's an example:
```js
"binary": {
"module_name": "your_module",
"module_path": "./lib/binding/napi-v{napi_build_version}",
"remote_path": "./{module_name}/v{version}/{configuration}/",
"package_name": "{platform}-{arch}-napi-v{napi_build_version}.tar.gz",
"host": "https://your_bucket.s3-us-west-1.amazonaws.com",
"napi_versions": [1,3]
}
```
## Supporting both Node-API and NAN builds
You may have a legacy native add-on that you wish to continue supporting for those versions of Node that do not support Node-API, as you add Node-API support for later Node versions. This can be accomplished by specifying the `node_napi_label` configuration value in the package.json `binary.package_name` property.
Placing the configuration value `node_napi_label` in the package.json `binary.package_name` property instructs `node-pre-gyp` to build all viable Node-API binaries supported by the current Node instance. If the current Node instance does not support Node-API, `node-pre-gyp` will request a traditional, non-Node-API build.
The configuration value `node_napi_label` is set by `node-pre-gyp` to the type of build created, `napi` or `node`, and the version number. For Node-API builds, the string contains the Node-API version nad has values like `napi-v3`. For traditional, non-Node-API builds, the string contains the ABI version with values like `node-v46`.
Here's how the `binary` configuration above might be changed to support both Node-API and NAN builds:
```js
"binary": {
"module_name": "your_module",
"module_path": "./lib/binding/{node_napi_label}",
"remote_path": "./{module_name}/v{version}/{configuration}/",
"package_name": "{platform}-{arch}-{node_napi_label}.tar.gz",
"host": "https://your_bucket.s3-us-west-1.amazonaws.com",
"napi_versions": [1,3]
}
```
The C/C++ symbol `NAPI_VERSION` can be used to distinguish Node-API and non-Node-API builds. The value of `NAPI_VERSION` is set to the integer Node-API version for Node-API builds and is set to `0` for non-Node-API builds.
For example:
```C
#if NAPI_VERSION
// Node-API code goes here
#else
// NAN code goes here
#endif
```
### Two additional configuration values
The following two configuration values, which were implemented in previous versions of `node-pre-gyp`, continue to exist, but have been replaced by the `node_napi_label` configuration value described above.
1. `napi_version` If Node-API is supported by the currently executing Node instance, this value is the Node-API version number supported by Node. If Node-API is not supported, this value is an empty string.
2. `node_abi_napi` If the value returned for `napi_version` is non empty, this value is `'napi'`. If the value returned for `napi_version` is empty, this value is the value returned for `node_abi`.
These values are present for use in the `binding.gyp` file and may be used as `{napi_version}` and `{node_abi_napi}` for text substituion in the `binary` properties of the `package.json` file.
## S3 Hosting
You can host wherever you choose but S3 is cheap, `node-pre-gyp publish` expects it, and S3 can be integrated well with [Travis.ci](http://travis-ci.org) to automate builds for OS X and Ubuntu, and with [Appveyor](http://appveyor.com) to automate builds for Windows. Here is an approach to do this:
First, get setup locally and test the workflow:
#### 1) Create an S3 bucket
And have your **key** and **secret key** ready for writing to the bucket.
It is recommended to create a IAM user with a policy that only gives permissions to the specific bucket you plan to publish to. This can be done in the [IAM console](https://console.aws.amazon.com/iam/) by: 1) adding a new user, 2) choosing `Attach User Policy`, 3) Using the `Policy Generator`, 4) selecting `Amazon S3` for the service, 5) adding the actions: `DeleteObject`, `GetObject`, `GetObjectAcl`, `ListBucket`, `HeadBucket`, `PutObject`, `PutObjectAcl`, 6) adding an ARN of `arn:aws:s3:::bucket/*` (replacing `bucket` with your bucket name), and finally 7) clicking `Add Statement` and saving the policy. It should generate a policy like:
```js
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "objects",
"Effect": "Allow",
"Action": [
"s3:PutObject",
"s3:GetObjectAcl",
"s3:GetObject",
"s3:DeleteObject",
"s3:PutObjectAcl"
],
"Resource": "arn:aws:s3:::your-bucket-name/*"
},
{
"Sid": "bucket",
"Effect": "Allow",
"Action": "s3:ListBucket",
"Resource": "arn:aws:s3:::your-bucket-name"
},
{
"Sid": "buckets",
"Effect": "Allow",
"Action": "s3:HeadBucket",
"Resource": "*"
}
]
}
```
#### 2) Install node-pre-gyp
Either install it globally:
npm install node-pre-gyp -g
Or put the local version on your PATH
export PATH=`pwd`/node_modules/.bin/:$PATH
#### 3) Configure AWS credentials
It is recommended to configure the AWS JS SDK v2 used internally by `node-pre-gyp` by setting these environment variables:
- AWS_ACCESS_KEY_ID
- AWS_SECRET_ACCESS_KEY
But also you can also use the `Shared Config File` mentioned [in the AWS JS SDK v2 docs](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/configuring-the-jssdk.html)
#### 4) Package and publish your build
Install the `aws-sdk`:
npm install aws-sdk
Then publish:
node-pre-gyp package publish
Note: if you hit an error like `Hostname/IP doesn't match certificate's altnames` it may mean that you need to provide the `region` option in your config.
## Appveyor Automation
[Appveyor](http://www.appveyor.com/) can build binaries and publish the results per commit and supports:
- Windows Visual Studio 2013 and related compilers
- Both 64 bit (x64) and 32 bit (x86) build configurations
- Multiple Node.js versions
For an example of doing this see [node-sqlite3's appveyor.yml](https://github.com/mapbox/node-sqlite3/blob/master/appveyor.yml).
Below is a guide to getting set up:
#### 1) Create a free Appveyor account
Go to https://ci.appveyor.com/signup/free and sign in with your GitHub account.
#### 2) Create a new project
Go to https://ci.appveyor.com/projects/new and select the GitHub repo for your module
#### 3) Add appveyor.yml and push it
Once you have committed an `appveyor.yml` ([appveyor.yml reference](http://www.appveyor.com/docs/appveyor-yml)) to your GitHub repo and pushed it AppVeyor should automatically start building your project.
#### 4) Create secure variables
Encrypt your S3 AWS keys by going to <https://ci.appveyor.com/tools/encrypt> and hitting the `encrypt` button.
Then paste the result into your `appveyor.yml`
```yml
environment:
AWS_ACCESS_KEY_ID:
secure: Dn9HKdLNYvDgPdQOzRq/DqZ/MPhjknRHB1o+/lVU8MA=
AWS_SECRET_ACCESS_KEY:
secure: W1rwNoSnOku1r+28gnoufO8UA8iWADmL1LiiwH9IOkIVhDTNGdGPJqAlLjNqwLnL
```
NOTE: keys are per account but not per repo (this is difference than Travis where keys are per repo but not related to the account used to encrypt them).
#### 5) Hook up publishing
Just put `node-pre-gyp package publish` in your `appveyor.yml` after `npm install`.
#### 6) Publish when you want
You might wish to publish binaries only on a specific commit. To do this you could borrow from the [Travis CI idea of commit keywords](http://about.travis-ci.org/docs/user/how-to-skip-a-build/) and add special handling for commit messages with `[publish binary]`:
SET CM=%APPVEYOR_REPO_COMMIT_MESSAGE%
if not "%CM%" == "%CM:[publish binary]=%" node-pre-gyp --msvs_version=2013 publish
If your commit message contains special characters (e.g. `&`) this method might fail. An alternative is to use PowerShell, which gives you additional possibilities, like ignoring case by using `ToLower()`:
ps: if($env:APPVEYOR_REPO_COMMIT_MESSAGE.ToLower().Contains('[publish binary]')) { node-pre-gyp --msvs_version=2013 publish }
Remember this publishing is not the same as `npm publish`. We're just talking about the binary module here and not your entire npm package.
## Travis Automation
[Travis](https://travis-ci.org/) can push to S3 after a successful build and supports both:
- Ubuntu Precise and OS X (64 bit)
- Multiple Node.js versions
For an example of doing this see [node-add-example's .travis.yml](https://github.com/springmeyer/node-addon-example/blob/2ff60a8ded7f042864ad21db00c3a5a06cf47075/.travis.yml).
Note: if you need 32 bit binaries, this can be done from a 64 bit Travis machine. See [the node-sqlite3 scripts for an example of doing this](https://github.com/mapbox/node-sqlite3/blob/bae122aa6a2b8a45f6b717fab24e207740e32b5d/scripts/build_against_node.sh#L54-L74).
Below is a guide to getting set up:
#### 1) Install the Travis gem
gem install travis
#### 2) Create secure variables
Make sure you run this command from within the directory of your module.
Use `travis-encrypt` like:
travis encrypt AWS_ACCESS_KEY_ID=${node_pre_gyp_accessKeyId}
travis encrypt AWS_SECRET_ACCESS_KEY=${node_pre_gyp_secretAccessKey}
Then put those values in your `.travis.yml` like:
```yaml
env:
global:
- secure: F+sEL/v56CzHqmCSSES4pEyC9NeQlkoR0Gs/ZuZxX1ytrj8SKtp3MKqBj7zhIclSdXBz4Ev966Da5ctmcTd410p0b240MV6BVOkLUtkjZJyErMBOkeb8n8yVfSoeMx8RiIhBmIvEn+rlQq+bSFis61/JkE9rxsjkGRZi14hHr4M=
- secure: o2nkUQIiABD139XS6L8pxq3XO5gch27hvm/gOdV+dzNKc/s2KomVPWcOyXNxtJGhtecAkABzaW8KHDDi5QL1kNEFx6BxFVMLO8rjFPsMVaBG9Ks6JiDQkkmrGNcnVdxI/6EKTLHTH5WLsz8+J7caDBzvKbEfTux5EamEhxIWgrI=
```
More details on Travis encryption at http://about.travis-ci.org/docs/user/encryption-keys/.
#### 3) Hook up publishing
Just put `node-pre-gyp package publish` in your `.travis.yml` after `npm install`.
##### OS X publishing
If you want binaries for OS X in addition to linux you can enable [multi-os for Travis](http://docs.travis-ci.com/user/multi-os/#Setting-.travis.yml)
Use a configuration like:
```yml
language: cpp
os:
- linux
- osx
env:
matrix:
- NODE_VERSION="4"
- NODE_VERSION="6"
before_install:
- rm -rf ~/.nvm/ && git clone --depth 1 https://github.com/creationix/nvm.git ~/.nvm
- source ~/.nvm/nvm.sh
- nvm install $NODE_VERSION
- nvm use $NODE_VERSION
```
See [Travis OS X Gotchas](#travis-os-x-gotchas) for why we replace `language: node_js` and `node_js:` sections with `language: cpp` and a custom matrix.
Also create platform specific sections for any deps that need install. For example if you need libpng:
```yml
- if [ $(uname -s) == 'Linux' ]; then apt-get install libpng-dev; fi;
- if [ $(uname -s) == 'Darwin' ]; then brew install libpng; fi;
```
For detailed multi-OS examples see [node-mapnik](https://github.com/mapnik/node-mapnik/blob/master/.travis.yml) and [node-sqlite3](https://github.com/mapbox/node-sqlite3/blob/master/.travis.yml).
##### Travis OS X Gotchas
First, unlike the Travis Linux machines, the OS X machines do not put `node-pre-gyp` on PATH by default. To do so you will need to:
```sh
export PATH=$(pwd)/node_modules/.bin:${PATH}
```
Second, the OS X machines do not support using a matrix for installing different Node.js versions. So you need to bootstrap the installation of Node.js in a cross platform way.
By doing:
```yml
env:
matrix:
- NODE_VERSION="4"
- NODE_VERSION="6"
before_install:
- rm -rf ~/.nvm/ && git clone --depth 1 https://github.com/creationix/nvm.git ~/.nvm
- source ~/.nvm/nvm.sh
- nvm install $NODE_VERSION
- nvm use $NODE_VERSION
```
You can easily recreate the previous behavior of this matrix:
```yml
node_js:
- "4"
- "6"
```
#### 4) Publish when you want
You might wish to publish binaries only on a specific commit. To do this you could borrow from the [Travis CI idea of commit keywords](http://about.travis-ci.org/docs/user/how-to-skip-a-build/) and add special handling for commit messages with `[publish binary]`:
COMMIT_MESSAGE=$(git log --format=%B --no-merges -n 1 | tr -d '\n')
if [[ ${COMMIT_MESSAGE} =~ "[publish binary]" ]]; then node-pre-gyp publish; fi;
Then you can trigger new binaries to be built like:
git commit -a -m "[publish binary]"
Or, if you don't have any changes to make simply run:
git commit --allow-empty -m "[publish binary]"
WARNING: if you are working in a pull request and publishing binaries from there then you will want to avoid double publishing when Travis CI builds both the `push` and `pr`. You only want to run the publish on the `push` commit. See https://github.com/Project-OSRM/node-osrm/blob/8eb837abe2e2e30e595093d16e5354bc5c573575/scripts/is_pr_merge.sh which is called from https://github.com/Project-OSRM/node-osrm/blob/8eb837abe2e2e30e595093d16e5354bc5c573575/scripts/publish.sh for an example of how to do this.
Remember this publishing is not the same as `npm publish`. We're just talking about the binary module here and not your entire npm package. To automate the publishing of your entire package to npm on Travis see http://about.travis-ci.org/docs/user/deployment/npm/
# Versioning
The `binary` properties of `module_path`, `remote_path`, and `package_name` support variable substitution. The strings are evaluated by `node-pre-gyp` depending on your system and any custom build flags you passed.
- `node_abi`: The node C++ `ABI` number. This value is available in Javascript as `process.versions.modules` as of [`>= v0.10.4 >= v0.11.7`](https://github.com/joyent/node/commit/ccabd4a6fa8a6eb79d29bc3bbe9fe2b6531c2d8e) and in C++ as the `NODE_MODULE_VERSION` define much earlier. For versions of Node before this was available we fallback to the V8 major and minor version.
- `platform` matches node's `process.platform` like `linux`, `darwin`, and `win32` unless the user passed the `--target_platform` option to override.
- `arch` matches node's `process.arch` like `x64` or `ia32` unless the user passes the `--target_arch` option to override.
- `libc` matches `require('detect-libc').family` like `glibc` or `musl` unless the user passes the `--target_libc` option to override.
- `configuration` - Either 'Release' or 'Debug' depending on if `--debug` is passed during the build.
- `module_name` - the `binary.module_name` attribute from `package.json`.
- `version` - the semver `version` value for your module from `package.json` (NOTE: ignores the `semver.build` property).
- `major`, `minor`, `patch`, and `prelease` match the individual semver values for your module's `version`
- `build` - the sevmer `build` value. For example it would be `this.that` if your package.json `version` was `v1.0.0+this.that`
- `prerelease` - the semver `prerelease` value. For example it would be `alpha.beta` if your package.json `version` was `v1.0.0-alpha.beta`
The options are visible in the code at <https://github.com/mapbox/node-pre-gyp/blob/612b7bca2604508d881e1187614870ba19a7f0c5/lib/util/versioning.js#L114-L127>
# Download binary files from a mirror
S3 is broken in China for the well known reason.
Using the `npm` config argument: `--{module_name}_binary_host_mirror` can download binary files through a mirror, `-` in `module_name` will be replaced with `_`.
e.g.: Install [v8-profiler](https://www.npmjs.com/package/v8-profiler) from `npm`.
```bash
$ npm install v8-profiler --profiler_binary_host_mirror=https://npm.taobao.org/mirrors/node-inspector/
```
e.g.: Install [canvas-prebuilt](https://www.npmjs.com/package/canvas-prebuilt) from `npm`.
```bash
$ npm install canvas-prebuilt --canvas_prebuilt_binary_host_mirror=https://npm.taobao.org/mirrors/canvas-prebuilt/
```

View File

@ -0,0 +1,4 @@
#!/usr/bin/env node
'use strict';
require('../lib/main');

View File

@ -0,0 +1,2 @@
@echo off
node "%~dp0\node-pre-gyp" %*

View File

@ -0,0 +1,10 @@
# Contributing
### Releasing a new version:
- Ensure tests are passing on travis and appveyor
- Run `node scripts/abi_crosswalk.js` and commit any changes
- Update the changelog
- Tag a new release like: `git tag -a v0.6.34 -m "tagging v0.6.34" && git push --tags`
- Run `npm publish`

View File

@ -0,0 +1,51 @@
'use strict';
module.exports = exports = build;
exports.usage = 'Attempts to compile the module by dispatching to node-gyp or nw-gyp';
const napi = require('./util/napi.js');
const compile = require('./util/compile.js');
const handle_gyp_opts = require('./util/handle_gyp_opts.js');
const configure = require('./configure.js');
function do_build(gyp, argv, callback) {
handle_gyp_opts(gyp, argv, (err, result) => {
let final_args = ['build'].concat(result.gyp).concat(result.pre);
if (result.unparsed.length > 0) {
final_args = final_args.
concat(['--']).
concat(result.unparsed);
}
if (!err && result.opts.napi_build_version) {
napi.swap_build_dir_in(result.opts.napi_build_version);
}
compile.run_gyp(final_args, result.opts, (err2) => {
if (result.opts.napi_build_version) {
napi.swap_build_dir_out(result.opts.napi_build_version);
}
return callback(err2);
});
});
}
function build(gyp, argv, callback) {
// Form up commands to pass to node-gyp:
// We map `node-pre-gyp build` to `node-gyp configure build` so that we do not
// trigger a clean and therefore do not pay the penalty of a full recompile
if (argv.length && (argv.indexOf('rebuild') > -1)) {
argv.shift(); // remove `rebuild`
// here we map `node-pre-gyp rebuild` to `node-gyp rebuild` which internally means
// "clean + configure + build" and triggers a full recompile
compile.run_gyp(['clean'], {}, (err3) => {
if (err3) return callback(err3);
configure(gyp, argv, (err4) => {
if (err4) return callback(err4);
return do_build(gyp, argv, callback);
});
});
} else {
return do_build(gyp, argv, callback);
}
}

View File

@ -0,0 +1,31 @@
'use strict';
module.exports = exports = clean;
exports.usage = 'Removes the entire folder containing the compiled .node module';
const rm = require('rimraf');
const exists = require('fs').exists || require('path').exists;
const versioning = require('./util/versioning.js');
const napi = require('./util/napi.js');
const path = require('path');
function clean(gyp, argv, callback) {
const package_json = gyp.package_json;
const napi_build_version = napi.get_napi_build_version_from_command_args(argv);
const opts = versioning.evaluate(package_json, gyp.opts, napi_build_version);
const to_delete = opts.module_path;
if (!to_delete) {
return callback(new Error('module_path is empty, refusing to delete'));
} else if (path.normalize(to_delete) === path.normalize(process.cwd())) {
return callback(new Error('module_path is not set, refusing to delete'));
} else {
exists(to_delete, (found) => {
if (found) {
if (!gyp.opts.silent_clean) console.log('[' + package_json.name + '] Removing "%s"', to_delete);
return rm(to_delete, callback);
}
return callback();
});
}
}

View File

@ -0,0 +1,52 @@
'use strict';
module.exports = exports = configure;
exports.usage = 'Attempts to configure node-gyp or nw-gyp build';
const napi = require('./util/napi.js');
const compile = require('./util/compile.js');
const handle_gyp_opts = require('./util/handle_gyp_opts.js');
function configure(gyp, argv, callback) {
handle_gyp_opts(gyp, argv, (err, result) => {
let final_args = result.gyp.concat(result.pre);
// pull select node-gyp configure options out of the npm environ
const known_gyp_args = ['dist-url', 'python', 'nodedir', 'msvs_version'];
known_gyp_args.forEach((key) => {
const val = gyp.opts[key] || gyp.opts[key.replace('-', '_')];
if (val) {
final_args.push('--' + key + '=' + val);
}
});
// --ensure=false tell node-gyp to re-install node development headers
// but it is only respected by node-gyp install, so we have to call install
// as a separate step if the user passes it
if (gyp.opts.ensure === false) {
const install_args = final_args.concat(['install', '--ensure=false']);
compile.run_gyp(install_args, result.opts, (err2) => {
if (err2) return callback(err2);
if (result.unparsed.length > 0) {
final_args = final_args.
concat(['--']).
concat(result.unparsed);
}
compile.run_gyp(['configure'].concat(final_args), result.opts, (err3) => {
return callback(err3);
});
});
} else {
if (result.unparsed.length > 0) {
final_args = final_args.
concat(['--']).
concat(result.unparsed);
}
compile.run_gyp(['configure'].concat(final_args), result.opts, (err4) => {
if (!err4 && result.opts.napi_build_version) {
napi.swap_build_dir_out(result.opts.napi_build_version);
}
return callback(err4);
});
}
});
}

View File

@ -0,0 +1,38 @@
'use strict';
module.exports = exports = info;
exports.usage = 'Lists all published binaries (requires aws-sdk)';
const log = require('npmlog');
const versioning = require('./util/versioning.js');
const s3_setup = require('./util/s3_setup.js');
function info(gyp, argv, callback) {
const package_json = gyp.package_json;
const opts = versioning.evaluate(package_json, gyp.opts);
const config = {};
s3_setup.detect(opts, config);
const s3 = s3_setup.get_s3(config);
const s3_opts = {
Bucket: config.bucket,
Prefix: config.prefix
};
s3.listObjects(s3_opts, (err, meta) => {
if (err && err.code === 'NotFound') {
return callback(new Error('[' + package_json.name + '] Not found: https://' + s3_opts.Bucket + '.s3.amazonaws.com/' + config.prefix));
} else if (err) {
return callback(err);
} else {
log.verbose(JSON.stringify(meta, null, 1));
if (meta && meta.Contents) {
meta.Contents.forEach((obj) => {
console.log(obj.Key);
});
} else {
console.error('[' + package_json.name + '] No objects found at https://' + s3_opts.Bucket + '.s3.amazonaws.com/' + config.prefix);
}
return callback();
}
});
}

View File

@ -0,0 +1,235 @@
'use strict';
module.exports = exports = install;
exports.usage = 'Attempts to install pre-built binary for module';
const fs = require('fs');
const path = require('path');
const log = require('npmlog');
const existsAsync = fs.exists || path.exists;
const versioning = require('./util/versioning.js');
const napi = require('./util/napi.js');
const makeDir = require('make-dir');
// for fetching binaries
const fetch = require('node-fetch');
const tar = require('tar');
let npgVersion = 'unknown';
try {
// Read own package.json to get the current node-pre-pyp version.
const ownPackageJSON = fs.readFileSync(path.join(__dirname, '..', 'package.json'), 'utf8');
npgVersion = JSON.parse(ownPackageJSON).version;
} catch (e) {
// do nothing
}
function place_binary(uri, targetDir, opts, callback) {
log.http('GET', uri);
// Try getting version info from the currently running npm.
const envVersionInfo = process.env.npm_config_user_agent ||
'node ' + process.version;
const sanitized = uri.replace('+', '%2B');
const requestOpts = {
uri: sanitized,
headers: {
'User-Agent': 'node-pre-gyp (v' + npgVersion + ', ' + envVersionInfo + ')'
},
follow_max: 10
};
if (opts.cafile) {
try {
requestOpts.ca = fs.readFileSync(opts.cafile);
} catch (e) {
return callback(e);
}
} else if (opts.ca) {
requestOpts.ca = opts.ca;
}
const proxyUrl = opts.proxy ||
process.env.http_proxy ||
process.env.HTTP_PROXY ||
process.env.npm_config_proxy;
let agent;
if (proxyUrl) {
const ProxyAgent = require('https-proxy-agent');
agent = new ProxyAgent(proxyUrl);
log.http('download', 'proxy agent configured using: "%s"', proxyUrl);
}
fetch(sanitized, { agent })
.then((res) => {
if (!res.ok) {
throw new Error(`response status ${res.status} ${res.statusText} on ${sanitized}`);
}
const dataStream = res.body;
return new Promise((resolve, reject) => {
let extractions = 0;
const countExtractions = (entry) => {
extractions += 1;
log.info('install', 'unpacking %s', entry.path);
};
dataStream.pipe(extract(targetDir, countExtractions))
.on('error', (e) => {
reject(e);
});
dataStream.on('end', () => {
resolve(`extracted file count: ${extractions}`);
});
dataStream.on('error', (e) => {
reject(e);
});
});
})
.then((text) => {
log.info(text);
callback();
})
.catch((e) => {
log.error(`install ${e.message}`);
callback(e);
});
}
function extract(to, onentry) {
return tar.extract({
cwd: to,
strip: 1,
onentry
});
}
function extract_from_local(from, targetDir, callback) {
if (!fs.existsSync(from)) {
return callback(new Error('Cannot find file ' + from));
}
log.info('Found local file to extract from ' + from);
// extract helpers
let extractCount = 0;
function countExtractions(entry) {
extractCount += 1;
log.info('install', 'unpacking ' + entry.path);
}
function afterExtract(err) {
if (err) return callback(err);
if (extractCount === 0) {
return callback(new Error('There was a fatal problem while extracting the tarball'));
}
log.info('tarball', 'done parsing tarball');
callback();
}
fs.createReadStream(from).pipe(extract(targetDir, countExtractions))
.on('close', afterExtract)
.on('error', afterExtract);
}
function do_build(gyp, argv, callback) {
const args = ['rebuild'].concat(argv);
gyp.todo.push({ name: 'build', args: args });
process.nextTick(callback);
}
function print_fallback_error(err, opts, package_json) {
const fallback_message = ' (falling back to source compile with node-gyp)';
let full_message = '';
if (err.statusCode !== undefined) {
// If we got a network response it but failed to download
// it means remote binaries are not available, so let's try to help
// the user/developer with the info to debug why
full_message = 'Pre-built binaries not found for ' + package_json.name + '@' + package_json.version;
full_message += ' and ' + opts.runtime + '@' + (opts.target || process.versions.node) + ' (' + opts.node_abi + ' ABI, ' + opts.libc + ')';
full_message += fallback_message;
log.warn('Tried to download(' + err.statusCode + '): ' + opts.hosted_tarball);
log.warn(full_message);
log.http(err.message);
} else {
// If we do not have a statusCode that means an unexpected error
// happened and prevented an http response, so we output the exact error
full_message = 'Pre-built binaries not installable for ' + package_json.name + '@' + package_json.version;
full_message += ' and ' + opts.runtime + '@' + (opts.target || process.versions.node) + ' (' + opts.node_abi + ' ABI, ' + opts.libc + ')';
full_message += fallback_message;
log.warn(full_message);
log.warn('Hit error ' + err.message);
}
}
//
// install
//
function install(gyp, argv, callback) {
const package_json = gyp.package_json;
const napi_build_version = napi.get_napi_build_version_from_command_args(argv);
const source_build = gyp.opts['build-from-source'] || gyp.opts.build_from_source;
const update_binary = gyp.opts['update-binary'] || gyp.opts.update_binary;
const should_do_source_build = source_build === package_json.name || (source_build === true || source_build === 'true');
if (should_do_source_build) {
log.info('build', 'requesting source compile');
return do_build(gyp, argv, callback);
} else {
const fallback_to_build = gyp.opts['fallback-to-build'] || gyp.opts.fallback_to_build;
let should_do_fallback_build = fallback_to_build === package_json.name || (fallback_to_build === true || fallback_to_build === 'true');
// but allow override from npm
if (process.env.npm_config_argv) {
const cooked = JSON.parse(process.env.npm_config_argv).cooked;
const match = cooked.indexOf('--fallback-to-build');
if (match > -1 && cooked.length > match && cooked[match + 1] === 'false') {
should_do_fallback_build = false;
log.info('install', 'Build fallback disabled via npm flag: --fallback-to-build=false');
}
}
let opts;
try {
opts = versioning.evaluate(package_json, gyp.opts, napi_build_version);
} catch (err) {
return callback(err);
}
opts.ca = gyp.opts.ca;
opts.cafile = gyp.opts.cafile;
const from = opts.hosted_tarball;
const to = opts.module_path;
const binary_module = path.join(to, opts.module_name + '.node');
existsAsync(binary_module, (found) => {
if (!update_binary) {
if (found) {
console.log('[' + package_json.name + '] Success: "' + binary_module + '" already installed');
console.log('Pass --update-binary to reinstall or --build-from-source to recompile');
return callback();
}
log.info('check', 'checked for "' + binary_module + '" (not found)');
}
makeDir(to).then(() => {
const fileName = from.startsWith('file://') && from.slice('file://'.length);
if (fileName) {
extract_from_local(fileName, to, after_place);
} else {
place_binary(from, to, opts, after_place);
}
}).catch((err) => {
after_place(err);
});
function after_place(err) {
if (err && should_do_fallback_build) {
print_fallback_error(err, opts, package_json);
return do_build(gyp, argv, callback);
} else if (err) {
return callback(err);
} else {
console.log('[' + package_json.name + '] Success: "' + binary_module + '" is installed via remote');
return callback();
}
}
});
}
}

View File

@ -0,0 +1,125 @@
'use strict';
/**
* Set the title.
*/
process.title = 'node-pre-gyp';
const node_pre_gyp = require('../');
const log = require('npmlog');
/**
* Process and execute the selected commands.
*/
const prog = new node_pre_gyp.Run({ argv: process.argv });
let completed = false;
if (prog.todo.length === 0) {
if (~process.argv.indexOf('-v') || ~process.argv.indexOf('--version')) {
console.log('v%s', prog.version);
process.exit(0);
} else if (~process.argv.indexOf('-h') || ~process.argv.indexOf('--help')) {
console.log('%s', prog.usage());
process.exit(0);
}
console.log('%s', prog.usage());
process.exit(1);
}
// if --no-color is passed
if (prog.opts && Object.hasOwnProperty.call(prog, 'color') && !prog.opts.color) {
log.disableColor();
}
log.info('it worked if it ends with', 'ok');
log.verbose('cli', process.argv);
log.info('using', process.title + '@%s', prog.version);
log.info('using', 'node@%s | %s | %s', process.versions.node, process.platform, process.arch);
/**
* Change dir if -C/--directory was passed.
*/
const dir = prog.opts.directory;
if (dir) {
const fs = require('fs');
try {
const stat = fs.statSync(dir);
if (stat.isDirectory()) {
log.info('chdir', dir);
process.chdir(dir);
} else {
log.warn('chdir', dir + ' is not a directory');
}
} catch (e) {
if (e.code === 'ENOENT') {
log.warn('chdir', dir + ' is not a directory');
} else {
log.warn('chdir', 'error during chdir() "%s"', e.message);
}
}
}
function run() {
const command = prog.todo.shift();
if (!command) {
// done!
completed = true;
log.info('ok');
return;
}
// set binary.host when appropriate. host determines the s3 target bucket.
const target = prog.setBinaryHostProperty(command.name);
if (target && ['install', 'publish', 'unpublish', 'info'].indexOf(command.name) >= 0) {
log.info('using binary.host: ' + prog.package_json.binary.host);
}
prog.commands[command.name](command.args, function(err) {
if (err) {
log.error(command.name + ' error');
log.error('stack', err.stack);
errorMessage();
log.error('not ok');
console.log(err.message);
return process.exit(1);
}
const args_array = [].slice.call(arguments, 1);
if (args_array.length) {
console.log.apply(console, args_array);
}
// now run the next command in the queue
process.nextTick(run);
});
}
process.on('exit', (code) => {
if (!completed && !code) {
log.error('Completion callback never invoked!');
errorMessage();
process.exit(6);
}
});
process.on('uncaughtException', (err) => {
log.error('UNCAUGHT EXCEPTION');
log.error('stack', err.stack);
errorMessage();
process.exit(7);
});
function errorMessage() {
// copied from npm's lib/util/error-handler.js
const os = require('os');
log.error('System', os.type() + ' ' + os.release());
log.error('command', process.argv.map(JSON.stringify).join(' '));
log.error('cwd', process.cwd());
log.error('node -v', process.version);
log.error(process.title + ' -v', 'v' + prog.package.version);
}
// start running the given commands!
run();

View File

@ -0,0 +1,309 @@
'use strict';
/**
* Module exports.
*/
module.exports = exports;
/**
* Module dependencies.
*/
// load mocking control function for accessing s3 via https. the function is a noop always returning
// false if not mocking.
exports.mockS3Http = require('./util/s3_setup').get_mockS3Http();
exports.mockS3Http('on');
const mocking = exports.mockS3Http('get');
const fs = require('fs');
const path = require('path');
const nopt = require('nopt');
const log = require('npmlog');
log.disableProgress();
const napi = require('./util/napi.js');
const EE = require('events').EventEmitter;
const inherits = require('util').inherits;
const cli_commands = [
'clean',
'install',
'reinstall',
'build',
'rebuild',
'package',
'testpackage',
'publish',
'unpublish',
'info',
'testbinary',
'reveal',
'configure'
];
const aliases = {};
// differentiate node-pre-gyp's logs from npm's
log.heading = 'node-pre-gyp';
if (mocking) {
log.warn(`mocking s3 to ${process.env.node_pre_gyp_mock_s3}`);
}
// this is a getter to avoid circular reference warnings with node v14.
Object.defineProperty(exports, 'find', {
get: function() {
return require('./pre-binding').find;
},
enumerable: true
});
// in the following, "my_module" is using node-pre-gyp to
// prebuild and install pre-built binaries. "main_module"
// is using "my_module".
//
// "bin/node-pre-gyp" invokes Run() without a path. the
// expectation is that the working directory is the package
// root "my_module". this is true because in all cases npm is
// executing a script in the context of "my_module".
//
// "pre-binding.find()" is executed by "my_module" but in the
// context of "main_module". this is because "main_module" is
// executing and requires "my_module" which is then executing
// "pre-binding.find()" via "node-pre-gyp.find()", so the working
// directory is that of "main_module".
//
// that's why "find()" must pass the path to package.json.
//
function Run({ package_json_path = './package.json', argv }) {
this.package_json_path = package_json_path;
this.commands = {};
const self = this;
cli_commands.forEach((command) => {
self.commands[command] = function(argvx, callback) {
log.verbose('command', command, argvx);
return require('./' + command)(self, argvx, callback);
};
});
this.parseArgv(argv);
// this is set to true after the binary.host property was set to
// either staging_host or production_host.
this.binaryHostSet = false;
}
inherits(Run, EE);
exports.Run = Run;
const proto = Run.prototype;
/**
* Export the contents of the package.json.
*/
proto.package = require('../package.json');
/**
* nopt configuration definitions
*/
proto.configDefs = {
help: Boolean, // everywhere
arch: String, // 'configure'
debug: Boolean, // 'build'
directory: String, // bin
proxy: String, // 'install'
loglevel: String // everywhere
};
/**
* nopt shorthands
*/
proto.shorthands = {
release: '--no-debug',
C: '--directory',
debug: '--debug',
j: '--jobs',
silent: '--loglevel=silent',
silly: '--loglevel=silly',
verbose: '--loglevel=verbose'
};
/**
* expose the command aliases for the bin file to use.
*/
proto.aliases = aliases;
/**
* Parses the given argv array and sets the 'opts', 'argv',
* 'command', and 'package_json' properties.
*/
proto.parseArgv = function parseOpts(argv) {
this.opts = nopt(this.configDefs, this.shorthands, argv);
this.argv = this.opts.argv.remain.slice();
const commands = this.todo = [];
// create a copy of the argv array with aliases mapped
argv = this.argv.map((arg) => {
// is this an alias?
if (arg in this.aliases) {
arg = this.aliases[arg];
}
return arg;
});
// process the mapped args into "command" objects ("name" and "args" props)
argv.slice().forEach((arg) => {
if (arg in this.commands) {
const args = argv.splice(0, argv.indexOf(arg));
argv.shift();
if (commands.length > 0) {
commands[commands.length - 1].args = args;
}
commands.push({ name: arg, args: [] });
}
});
if (commands.length > 0) {
commands[commands.length - 1].args = argv.splice(0);
}
// if a directory was specified package.json is assumed to be relative
// to it.
let package_json_path = this.package_json_path;
if (this.opts.directory) {
package_json_path = path.join(this.opts.directory, package_json_path);
}
this.package_json = JSON.parse(fs.readFileSync(package_json_path));
// expand commands entries for multiple napi builds
this.todo = napi.expand_commands(this.package_json, this.opts, commands);
// support for inheriting config env variables from npm
const npm_config_prefix = 'npm_config_';
Object.keys(process.env).forEach((name) => {
if (name.indexOf(npm_config_prefix) !== 0) return;
const val = process.env[name];
if (name === npm_config_prefix + 'loglevel') {
log.level = val;
} else {
// add the user-defined options to the config
name = name.substring(npm_config_prefix.length);
// avoid npm argv clobber already present args
// which avoids problem of 'npm test' calling
// script that runs unique npm install commands
if (name === 'argv') {
if (this.opts.argv &&
this.opts.argv.remain &&
this.opts.argv.remain.length) {
// do nothing
} else {
this.opts[name] = val;
}
} else {
this.opts[name] = val;
}
}
});
if (this.opts.loglevel) {
log.level = this.opts.loglevel;
}
log.resume();
};
/**
* allow the binary.host property to be set at execution time.
*
* for this to take effect requires all the following to be true.
* - binary is a property in package.json
* - binary.host is falsey
* - binary.staging_host is not empty
* - binary.production_host is not empty
*
* if any of the previous checks fail then the function returns an empty string
* and makes no changes to package.json's binary property.
*
*
* if command is "publish" then the default is set to "binary.staging_host"
* if command is not "publish" the the default is set to "binary.production_host"
*
* if the command-line option '--s3_host' is set to "staging" or "production" then
* "binary.host" is set to the specified "staging_host" or "production_host". if
* '--s3_host' is any other value an exception is thrown.
*
* if '--s3_host' is not present then "binary.host" is set to the default as above.
*
* this strategy was chosen so that any command other than "publish" or "unpublish" uses "production"
* as the default without requiring any command-line options but that "publish" and "unpublish" require
* '--s3_host production_host' to be specified in order to *really* publish (or unpublish). publishing
* to staging can be done freely without worrying about disturbing any production releases.
*/
proto.setBinaryHostProperty = function(command) {
if (this.binaryHostSet) {
return this.package_json.binary.host;
}
const p = this.package_json;
// don't set anything if host is present. it must be left blank to trigger this.
if (!p || !p.binary || p.binary.host) {
return '';
}
// and both staging and production must be present. errors will be reported later.
if (!p.binary.staging_host || !p.binary.production_host) {
return '';
}
let target = 'production_host';
if (command === 'publish' || command === 'unpublish') {
target = 'staging_host';
}
// the environment variable has priority over the default or the command line. if
// either the env var or the command line option are invalid throw an error.
const npg_s3_host = process.env.node_pre_gyp_s3_host;
if (npg_s3_host === 'staging' || npg_s3_host === 'production') {
target = `${npg_s3_host}_host`;
} else if (this.opts['s3_host'] === 'staging' || this.opts['s3_host'] === 'production') {
target = `${this.opts['s3_host']}_host`;
} else if (this.opts['s3_host'] || npg_s3_host) {
throw new Error(`invalid s3_host ${this.opts['s3_host'] || npg_s3_host}`);
}
p.binary.host = p.binary[target];
this.binaryHostSet = true;
return p.binary.host;
};
/**
* Returns the usage instructions for node-pre-gyp.
*/
proto.usage = function usage() {
const str = [
'',
' Usage: node-pre-gyp <command> [options]',
'',
' where <command> is one of:',
cli_commands.map((c) => {
return ' - ' + c + ' - ' + require('./' + c).usage;
}).join('\n'),
'',
'node-pre-gyp@' + this.version + ' ' + path.resolve(__dirname, '..'),
'node@' + process.versions.node
].join('\n');
return str;
};
/**
* Version number getter.
*/
Object.defineProperty(proto, 'version', {
get: function() {
return this.package.version;
},
enumerable: true
});

View File

@ -0,0 +1,73 @@
'use strict';
module.exports = exports = _package;
exports.usage = 'Packs binary (and enclosing directory) into locally staged tarball';
const fs = require('fs');
const path = require('path');
const log = require('npmlog');
const versioning = require('./util/versioning.js');
const napi = require('./util/napi.js');
const existsAsync = fs.exists || path.exists;
const makeDir = require('make-dir');
const tar = require('tar');
function readdirSync(dir) {
let list = [];
const files = fs.readdirSync(dir);
files.forEach((file) => {
const stats = fs.lstatSync(path.join(dir, file));
if (stats.isDirectory()) {
list = list.concat(readdirSync(path.join(dir, file)));
} else {
list.push(path.join(dir, file));
}
});
return list;
}
function _package(gyp, argv, callback) {
const package_json = gyp.package_json;
const napi_build_version = napi.get_napi_build_version_from_command_args(argv);
const opts = versioning.evaluate(package_json, gyp.opts, napi_build_version);
const from = opts.module_path;
const binary_module = path.join(from, opts.module_name + '.node');
existsAsync(binary_module, (found) => {
if (!found) {
return callback(new Error('Cannot package because ' + binary_module + ' missing: run `node-pre-gyp rebuild` first'));
}
const tarball = opts.staged_tarball;
const filter_func = function(entry) {
const basename = path.basename(entry);
if (basename.length && basename[0] !== '.') {
console.log('packing ' + entry);
return true;
} else {
console.log('skipping ' + entry);
}
return false;
};
makeDir(path.dirname(tarball)).then(() => {
let files = readdirSync(from);
const base = path.basename(from);
files = files.map((file) => {
return path.join(base, path.relative(from, file));
});
tar.create({
portable: false,
gzip: true,
filter: filter_func,
file: tarball,
cwd: path.dirname(from)
}, files, (err2) => {
if (err2) console.error('[' + package_json.name + '] ' + err2.message);
else log.info('package', 'Binary staged at "' + tarball + '"');
return callback(err2);
});
}).catch((err) => {
return callback(err);
});
});
}

View File

@ -0,0 +1,34 @@
'use strict';
const npg = require('..');
const versioning = require('../lib/util/versioning.js');
const napi = require('../lib/util/napi.js');
const existsSync = require('fs').existsSync || require('path').existsSync;
const path = require('path');
module.exports = exports;
exports.usage = 'Finds the require path for the node-pre-gyp installed module';
exports.validate = function(package_json, opts) {
versioning.validate_config(package_json, opts);
};
exports.find = function(package_json_path, opts) {
if (!existsSync(package_json_path)) {
throw new Error(package_json_path + 'does not exist');
}
const prog = new npg.Run({ package_json_path, argv: process.argv });
prog.setBinaryHostProperty();
const package_json = prog.package_json;
versioning.validate_config(package_json, opts);
let napi_build_version;
if (napi.get_napi_build_versions(package_json, opts)) {
napi_build_version = napi.get_best_napi_build_version(package_json, opts);
}
opts = opts || {};
if (!opts.module_root) opts.module_root = path.dirname(package_json_path);
const meta = versioning.evaluate(package_json, opts, napi_build_version);
return meta.module;
};

View File

@ -0,0 +1,81 @@
'use strict';
module.exports = exports = publish;
exports.usage = 'Publishes pre-built binary (requires aws-sdk)';
const fs = require('fs');
const path = require('path');
const log = require('npmlog');
const versioning = require('./util/versioning.js');
const napi = require('./util/napi.js');
const s3_setup = require('./util/s3_setup.js');
const existsAsync = fs.exists || path.exists;
const url = require('url');
function publish(gyp, argv, callback) {
const package_json = gyp.package_json;
const napi_build_version = napi.get_napi_build_version_from_command_args(argv);
const opts = versioning.evaluate(package_json, gyp.opts, napi_build_version);
const tarball = opts.staged_tarball;
existsAsync(tarball, (found) => {
if (!found) {
return callback(new Error('Cannot publish because ' + tarball + ' missing: run `node-pre-gyp package` first'));
}
log.info('publish', 'Detecting s3 credentials');
const config = {};
s3_setup.detect(opts, config);
const s3 = s3_setup.get_s3(config);
const key_name = url.resolve(config.prefix, opts.package_name);
const s3_opts = {
Bucket: config.bucket,
Key: key_name
};
log.info('publish', 'Authenticating with s3');
log.info('publish', config);
log.info('publish', 'Checking for existing binary at ' + opts.hosted_path);
s3.headObject(s3_opts, (err, meta) => {
if (meta) log.info('publish', JSON.stringify(meta));
if (err && err.code === 'NotFound') {
// we are safe to publish because
// the object does not already exist
log.info('publish', 'Preparing to put object');
const s3_put_opts = {
ACL: 'public-read',
Body: fs.createReadStream(tarball),
Key: key_name,
Bucket: config.bucket
};
log.info('publish', 'Putting object', s3_put_opts.ACL, s3_put_opts.Bucket, s3_put_opts.Key);
try {
s3.putObject(s3_put_opts, (err2, resp) => {
log.info('publish', 'returned from putting object');
if (err2) {
log.info('publish', 's3 putObject error: "' + err2 + '"');
return callback(err2);
}
if (resp) log.info('publish', 's3 putObject response: "' + JSON.stringify(resp) + '"');
log.info('publish', 'successfully put object');
console.log('[' + package_json.name + '] published to ' + opts.hosted_path);
return callback();
});
} catch (err3) {
log.info('publish', 's3 putObject error: "' + err3 + '"');
return callback(err3);
}
} else if (err) {
log.info('publish', 's3 headObject error: "' + err + '"');
return callback(err);
} else {
log.error('publish', 'Cannot publish over existing version');
log.error('publish', "Update the 'version' field in package.json and try again");
log.error('publish', 'If the previous version was published in error see:');
log.error('publish', '\t node-pre-gyp unpublish');
return callback(new Error('Failed publishing to ' + opts.hosted_path));
}
});
});
}

View File

@ -0,0 +1,20 @@
'use strict';
module.exports = exports = rebuild;
exports.usage = 'Runs "clean" and "build" at once';
const napi = require('./util/napi.js');
function rebuild(gyp, argv, callback) {
const package_json = gyp.package_json;
let commands = [
{ name: 'clean', args: [] },
{ name: 'build', args: ['rebuild'] }
];
commands = napi.expand_commands(package_json, gyp.opts, commands);
for (let i = commands.length; i !== 0; i--) {
gyp.todo.unshift(commands[i - 1]);
}
process.nextTick(callback);
}

View File

@ -0,0 +1,19 @@
'use strict';
module.exports = exports = rebuild;
exports.usage = 'Runs "clean" and "install" at once';
const napi = require('./util/napi.js');
function rebuild(gyp, argv, callback) {
const package_json = gyp.package_json;
let installArgs = [];
const napi_build_version = napi.get_best_napi_build_version(package_json, gyp.opts);
if (napi_build_version != null) installArgs = [napi.get_command_arg(napi_build_version)];
gyp.todo.unshift(
{ name: 'clean', args: [] },
{ name: 'install', args: installArgs }
);
process.nextTick(callback);
}

View File

@ -0,0 +1,32 @@
'use strict';
module.exports = exports = reveal;
exports.usage = 'Reveals data on the versioned binary';
const versioning = require('./util/versioning.js');
const napi = require('./util/napi.js');
function unix_paths(key, val) {
return val && val.replace ? val.replace(/\\/g, '/') : val;
}
function reveal(gyp, argv, callback) {
const package_json = gyp.package_json;
const napi_build_version = napi.get_napi_build_version_from_command_args(argv);
const opts = versioning.evaluate(package_json, gyp.opts, napi_build_version);
let hit = false;
// if a second arg is passed look to see
// if it is a known option
// console.log(JSON.stringify(gyp.opts,null,1))
const remain = gyp.opts.argv.remain[gyp.opts.argv.remain.length - 1];
if (remain && Object.hasOwnProperty.call(opts, remain)) {
console.log(opts[remain].replace(/\\/g, '/'));
hit = true;
}
// otherwise return all options as json
if (!hit) {
console.log(JSON.stringify(opts, unix_paths, 2));
}
return callback();
}

View File

@ -0,0 +1,79 @@
'use strict';
module.exports = exports = testbinary;
exports.usage = 'Tests that the binary.node can be required';
const path = require('path');
const log = require('npmlog');
const cp = require('child_process');
const versioning = require('./util/versioning.js');
const napi = require('./util/napi.js');
function testbinary(gyp, argv, callback) {
const args = [];
const options = {};
let shell_cmd = process.execPath;
const package_json = gyp.package_json;
const napi_build_version = napi.get_napi_build_version_from_command_args(argv);
const opts = versioning.evaluate(package_json, gyp.opts, napi_build_version);
// skip validation for runtimes we don't explicitly support (like electron)
if (opts.runtime &&
opts.runtime !== 'node-webkit' &&
opts.runtime !== 'node') {
return callback();
}
const nw = (opts.runtime && opts.runtime === 'node-webkit');
// ensure on windows that / are used for require path
const binary_module = opts.module.replace(/\\/g, '/');
if ((process.arch !== opts.target_arch) ||
(process.platform !== opts.target_platform)) {
let msg = 'skipping validation since host platform/arch (';
msg += process.platform + '/' + process.arch + ')';
msg += ' does not match target (';
msg += opts.target_platform + '/' + opts.target_arch + ')';
log.info('validate', msg);
return callback();
}
if (nw) {
options.timeout = 5000;
if (process.platform === 'darwin') {
shell_cmd = 'node-webkit';
} else if (process.platform === 'win32') {
shell_cmd = 'nw.exe';
} else {
shell_cmd = 'nw';
}
const modulePath = path.resolve(binary_module);
const appDir = path.join(__dirname, 'util', 'nw-pre-gyp');
args.push(appDir);
args.push(modulePath);
log.info('validate', "Running test command: '" + shell_cmd + ' ' + args.join(' ') + "'");
cp.execFile(shell_cmd, args, options, (err, stdout, stderr) => {
// check for normal timeout for node-webkit
if (err) {
if (err.killed === true && err.signal && err.signal.indexOf('SIG') > -1) {
return callback();
}
const stderrLog = stderr.toString();
log.info('stderr', stderrLog);
if (/^\s*Xlib:\s*extension\s*"RANDR"\s*missing\s*on\s*display\s*":\d+\.\d+"\.\s*$/.test(stderrLog)) {
log.info('RANDR', 'stderr contains only RANDR error, ignored');
return callback();
}
return callback(err);
}
return callback();
});
return;
}
args.push('--eval');
args.push("require('" + binary_module.replace(/'/g, '\'') + "')");
log.info('validate', "Running test command: '" + shell_cmd + ' ' + args.join(' ') + "'");
cp.execFile(shell_cmd, args, options, (err, stdout, stderr) => {
if (err) {
return callback(err, { stdout: stdout, stderr: stderr });
}
return callback();
});
}

View File

@ -0,0 +1,53 @@
'use strict';
module.exports = exports = testpackage;
exports.usage = 'Tests that the staged package is valid';
const fs = require('fs');
const path = require('path');
const log = require('npmlog');
const existsAsync = fs.exists || path.exists;
const versioning = require('./util/versioning.js');
const napi = require('./util/napi.js');
const testbinary = require('./testbinary.js');
const tar = require('tar');
const makeDir = require('make-dir');
function testpackage(gyp, argv, callback) {
const package_json = gyp.package_json;
const napi_build_version = napi.get_napi_build_version_from_command_args(argv);
const opts = versioning.evaluate(package_json, gyp.opts, napi_build_version);
const tarball = opts.staged_tarball;
existsAsync(tarball, (found) => {
if (!found) {
return callback(new Error('Cannot test package because ' + tarball + ' missing: run `node-pre-gyp package` first'));
}
const to = opts.module_path;
function filter_func(entry) {
log.info('install', 'unpacking [' + entry.path + ']');
}
makeDir(to).then(() => {
tar.extract({
file: tarball,
cwd: to,
strip: 1,
onentry: filter_func
}).then(after_extract, callback);
}).catch((err) => {
return callback(err);
});
function after_extract() {
testbinary(gyp, argv, (err) => {
if (err) {
return callback(err);
} else {
console.log('[' + package_json.name + '] Package appears valid');
return callback();
}
});
}
});
}

View File

@ -0,0 +1,41 @@
'use strict';
module.exports = exports = unpublish;
exports.usage = 'Unpublishes pre-built binary (requires aws-sdk)';
const log = require('npmlog');
const versioning = require('./util/versioning.js');
const napi = require('./util/napi.js');
const s3_setup = require('./util/s3_setup.js');
const url = require('url');
function unpublish(gyp, argv, callback) {
const package_json = gyp.package_json;
const napi_build_version = napi.get_napi_build_version_from_command_args(argv);
const opts = versioning.evaluate(package_json, gyp.opts, napi_build_version);
const config = {};
s3_setup.detect(opts, config);
const s3 = s3_setup.get_s3(config);
const key_name = url.resolve(config.prefix, opts.package_name);
const s3_opts = {
Bucket: config.bucket,
Key: key_name
};
s3.headObject(s3_opts, (err, meta) => {
if (err && err.code === 'NotFound') {
console.log('[' + package_json.name + '] Not found: https://' + s3_opts.Bucket + '.s3.amazonaws.com/' + s3_opts.Key);
return callback();
} else if (err) {
return callback(err);
} else {
log.info('unpublish', JSON.stringify(meta));
s3.deleteObject(s3_opts, (err2, resp) => {
if (err2) return callback(err2);
log.info(JSON.stringify(resp));
console.log('[' + package_json.name + '] Success: removed https://' + s3_opts.Bucket + '.s3.amazonaws.com/' + s3_opts.Key);
return callback();
});
}
});
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,93 @@
'use strict';
module.exports = exports;
const fs = require('fs');
const path = require('path');
const win = process.platform === 'win32';
const existsSync = fs.existsSync || path.existsSync;
const cp = require('child_process');
// try to build up the complete path to node-gyp
/* priority:
- node-gyp on ENV:npm_config_node_gyp (https://github.com/npm/npm/pull/4887)
- node-gyp on NODE_PATH
- node-gyp inside npm on NODE_PATH (ignore on iojs)
- node-gyp inside npm beside node exe
*/
function which_node_gyp() {
let node_gyp_bin;
if (process.env.npm_config_node_gyp) {
try {
node_gyp_bin = process.env.npm_config_node_gyp;
if (existsSync(node_gyp_bin)) {
return node_gyp_bin;
}
} catch (err) {
// do nothing
}
}
try {
const node_gyp_main = require.resolve('node-gyp'); // eslint-disable-line node/no-missing-require
node_gyp_bin = path.join(path.dirname(
path.dirname(node_gyp_main)),
'bin/node-gyp.js');
if (existsSync(node_gyp_bin)) {
return node_gyp_bin;
}
} catch (err) {
// do nothing
}
if (process.execPath.indexOf('iojs') === -1) {
try {
const npm_main = require.resolve('npm'); // eslint-disable-line node/no-missing-require
node_gyp_bin = path.join(path.dirname(
path.dirname(npm_main)),
'node_modules/node-gyp/bin/node-gyp.js');
if (existsSync(node_gyp_bin)) {
return node_gyp_bin;
}
} catch (err) {
// do nothing
}
}
const npm_base = path.join(path.dirname(
path.dirname(process.execPath)),
'lib/node_modules/npm/');
node_gyp_bin = path.join(npm_base, 'node_modules/node-gyp/bin/node-gyp.js');
if (existsSync(node_gyp_bin)) {
return node_gyp_bin;
}
}
module.exports.run_gyp = function(args, opts, callback) {
let shell_cmd = '';
const cmd_args = [];
if (opts.runtime && opts.runtime === 'node-webkit') {
shell_cmd = 'nw-gyp';
if (win) shell_cmd += '.cmd';
} else {
const node_gyp_path = which_node_gyp();
if (node_gyp_path) {
shell_cmd = process.execPath;
cmd_args.push(node_gyp_path);
} else {
shell_cmd = 'node-gyp';
if (win) shell_cmd += '.cmd';
}
}
const final_args = cmd_args.concat(args);
const cmd = cp.spawn(shell_cmd, final_args, { cwd: undefined, env: process.env, stdio: [0, 1, 2] });
cmd.on('error', (err) => {
if (err) {
return callback(new Error("Failed to execute '" + shell_cmd + ' ' + final_args.join(' ') + "' (" + err + ')'));
}
callback(null, opts);
});
cmd.on('close', (code) => {
if (code && code !== 0) {
return callback(new Error("Failed to execute '" + shell_cmd + ' ' + final_args.join(' ') + "' (" + code + ')'));
}
callback(null, opts);
});
};

View File

@ -0,0 +1,102 @@
'use strict';
module.exports = exports = handle_gyp_opts;
const versioning = require('./versioning.js');
const napi = require('./napi.js');
/*
Here we gather node-pre-gyp generated options (from versioning) and pass them along to node-gyp.
We massage the args and options slightly to account for differences in what commands mean between
node-pre-gyp and node-gyp (e.g. see the difference between "build" and "rebuild" below)
Keep in mind: the values inside `argv` and `gyp.opts` below are different depending on whether
node-pre-gyp is called directory, or if it is called in a `run-script` phase of npm.
We also try to preserve any command line options that might have been passed to npm or node-pre-gyp.
But this is fairly difficult without passing way to much through. For example `gyp.opts` contains all
the process.env and npm pushes a lot of variables into process.env which node-pre-gyp inherits. So we have
to be very selective about what we pass through.
For example:
`npm install --build-from-source` will give:
argv == [ 'rebuild' ]
gyp.opts.argv == { remain: [ 'install' ],
cooked: [ 'install', '--fallback-to-build' ],
original: [ 'install', '--fallback-to-build' ] }
`./bin/node-pre-gyp build` will give:
argv == []
gyp.opts.argv == { remain: [ 'build' ],
cooked: [ 'build' ],
original: [ '-C', 'test/app1', 'build' ] }
*/
// select set of node-pre-gyp versioning info
// to share with node-gyp
const share_with_node_gyp = [
'module',
'module_name',
'module_path',
'napi_version',
'node_abi_napi',
'napi_build_version',
'node_napi_label'
];
function handle_gyp_opts(gyp, argv, callback) {
// Collect node-pre-gyp specific variables to pass to node-gyp
const node_pre_gyp_options = [];
// generate custom node-pre-gyp versioning info
const napi_build_version = napi.get_napi_build_version_from_command_args(argv);
const opts = versioning.evaluate(gyp.package_json, gyp.opts, napi_build_version);
share_with_node_gyp.forEach((key) => {
const val = opts[key];
if (val) {
node_pre_gyp_options.push('--' + key + '=' + val);
} else if (key === 'napi_build_version') {
node_pre_gyp_options.push('--' + key + '=0');
} else {
if (key !== 'napi_version' && key !== 'node_abi_napi')
return callback(new Error('Option ' + key + ' required but not found by node-pre-gyp'));
}
});
// Collect options that follow the special -- which disables nopt parsing
const unparsed_options = [];
let double_hyphen_found = false;
gyp.opts.argv.original.forEach((opt) => {
if (double_hyphen_found) {
unparsed_options.push(opt);
}
if (opt === '--') {
double_hyphen_found = true;
}
});
// We try respect and pass through remaining command
// line options (like --foo=bar) to node-gyp
const cooked = gyp.opts.argv.cooked;
const node_gyp_options = [];
cooked.forEach((value) => {
if (value.length > 2 && value.slice(0, 2) === '--') {
const key = value.slice(2);
const val = cooked[cooked.indexOf(value) + 1];
if (val && val.indexOf('--') === -1) { // handle '--foo=bar' or ['--foo','bar']
node_gyp_options.push('--' + key + '=' + val);
} else { // pass through --foo
node_gyp_options.push(value);
}
}
});
const result = { 'opts': opts, 'gyp': node_gyp_options, 'pre': node_pre_gyp_options, 'unparsed': unparsed_options };
return callback(null, result);
}

View File

@ -0,0 +1,205 @@
'use strict';
const fs = require('fs');
module.exports = exports;
const versionArray = process.version
.substr(1)
.replace(/-.*$/, '')
.split('.')
.map((item) => {
return +item;
});
const napi_multiple_commands = [
'build',
'clean',
'configure',
'package',
'publish',
'reveal',
'testbinary',
'testpackage',
'unpublish'
];
const napi_build_version_tag = 'napi_build_version=';
module.exports.get_napi_version = function() {
// returns the non-zero numeric napi version or undefined if napi is not supported.
// correctly supporting target requires an updated cross-walk
let version = process.versions.napi; // can be undefined
if (!version) { // this code should never need to be updated
if (versionArray[0] === 9 && versionArray[1] >= 3) version = 2; // 9.3.0+
else if (versionArray[0] === 8) version = 1; // 8.0.0+
}
return version;
};
module.exports.get_napi_version_as_string = function(target) {
// returns the napi version as a string or an empty string if napi is not supported.
const version = module.exports.get_napi_version(target);
return version ? '' + version : '';
};
module.exports.validate_package_json = function(package_json, opts) { // throws Error
const binary = package_json.binary;
const module_path_ok = pathOK(binary.module_path);
const remote_path_ok = pathOK(binary.remote_path);
const package_name_ok = pathOK(binary.package_name);
const napi_build_versions = module.exports.get_napi_build_versions(package_json, opts, true);
const napi_build_versions_raw = module.exports.get_napi_build_versions_raw(package_json);
if (napi_build_versions) {
napi_build_versions.forEach((napi_build_version)=> {
if (!(parseInt(napi_build_version, 10) === napi_build_version && napi_build_version > 0)) {
throw new Error('All values specified in napi_versions must be positive integers.');
}
});
}
if (napi_build_versions && (!module_path_ok || (!remote_path_ok && !package_name_ok))) {
throw new Error('When napi_versions is specified; module_path and either remote_path or ' +
"package_name must contain the substitution string '{napi_build_version}`.");
}
if ((module_path_ok || remote_path_ok || package_name_ok) && !napi_build_versions_raw) {
throw new Error("When the substitution string '{napi_build_version}` is specified in " +
'module_path, remote_path, or package_name; napi_versions must also be specified.');
}
if (napi_build_versions && !module.exports.get_best_napi_build_version(package_json, opts) &&
module.exports.build_napi_only(package_json)) {
throw new Error(
'The Node-API version of this Node instance is ' + module.exports.get_napi_version(opts ? opts.target : undefined) + '. ' +
'This module supports Node-API version(s) ' + module.exports.get_napi_build_versions_raw(package_json) + '. ' +
'This Node instance cannot run this module.');
}
if (napi_build_versions_raw && !napi_build_versions && module.exports.build_napi_only(package_json)) {
throw new Error(
'The Node-API version of this Node instance is ' + module.exports.get_napi_version(opts ? opts.target : undefined) + '. ' +
'This module supports Node-API version(s) ' + module.exports.get_napi_build_versions_raw(package_json) + '. ' +
'This Node instance cannot run this module.');
}
};
function pathOK(path) {
return path && (path.indexOf('{napi_build_version}') !== -1 || path.indexOf('{node_napi_label}') !== -1);
}
module.exports.expand_commands = function(package_json, opts, commands) {
const expanded_commands = [];
const napi_build_versions = module.exports.get_napi_build_versions(package_json, opts);
commands.forEach((command)=> {
if (napi_build_versions && command.name === 'install') {
const napi_build_version = module.exports.get_best_napi_build_version(package_json, opts);
const args = napi_build_version ? [napi_build_version_tag + napi_build_version] : [];
expanded_commands.push({ name: command.name, args: args });
} else if (napi_build_versions && napi_multiple_commands.indexOf(command.name) !== -1) {
napi_build_versions.forEach((napi_build_version)=> {
const args = command.args.slice();
args.push(napi_build_version_tag + napi_build_version);
expanded_commands.push({ name: command.name, args: args });
});
} else {
expanded_commands.push(command);
}
});
return expanded_commands;
};
module.exports.get_napi_build_versions = function(package_json, opts, warnings) { // opts may be undefined
const log = require('npmlog');
let napi_build_versions = [];
const supported_napi_version = module.exports.get_napi_version(opts ? opts.target : undefined);
// remove duplicates, verify each napi version can actaully be built
if (package_json.binary && package_json.binary.napi_versions) {
package_json.binary.napi_versions.forEach((napi_version) => {
const duplicated = napi_build_versions.indexOf(napi_version) !== -1;
if (!duplicated && supported_napi_version && napi_version <= supported_napi_version) {
napi_build_versions.push(napi_version);
} else if (warnings && !duplicated && supported_napi_version) {
log.info('This Node instance does not support builds for Node-API version', napi_version);
}
});
}
if (opts && opts['build-latest-napi-version-only']) {
let latest_version = 0;
napi_build_versions.forEach((napi_version) => {
if (napi_version > latest_version) latest_version = napi_version;
});
napi_build_versions = latest_version ? [latest_version] : [];
}
return napi_build_versions.length ? napi_build_versions : undefined;
};
module.exports.get_napi_build_versions_raw = function(package_json) {
const napi_build_versions = [];
// remove duplicates
if (package_json.binary && package_json.binary.napi_versions) {
package_json.binary.napi_versions.forEach((napi_version) => {
if (napi_build_versions.indexOf(napi_version) === -1) {
napi_build_versions.push(napi_version);
}
});
}
return napi_build_versions.length ? napi_build_versions : undefined;
};
module.exports.get_command_arg = function(napi_build_version) {
return napi_build_version_tag + napi_build_version;
};
module.exports.get_napi_build_version_from_command_args = function(command_args) {
for (let i = 0; i < command_args.length; i++) {
const arg = command_args[i];
if (arg.indexOf(napi_build_version_tag) === 0) {
return parseInt(arg.substr(napi_build_version_tag.length), 10);
}
}
return undefined;
};
module.exports.swap_build_dir_out = function(napi_build_version) {
if (napi_build_version) {
const rm = require('rimraf');
rm.sync(module.exports.get_build_dir(napi_build_version));
fs.renameSync('build', module.exports.get_build_dir(napi_build_version));
}
};
module.exports.swap_build_dir_in = function(napi_build_version) {
if (napi_build_version) {
const rm = require('rimraf');
rm.sync('build');
fs.renameSync(module.exports.get_build_dir(napi_build_version), 'build');
}
};
module.exports.get_build_dir = function(napi_build_version) {
return 'build-tmp-napi-v' + napi_build_version;
};
module.exports.get_best_napi_build_version = function(package_json, opts) {
let best_napi_build_version = 0;
const napi_build_versions = module.exports.get_napi_build_versions(package_json, opts);
if (napi_build_versions) {
const our_napi_version = module.exports.get_napi_version(opts ? opts.target : undefined);
napi_build_versions.forEach((napi_build_version)=> {
if (napi_build_version > best_napi_build_version &&
napi_build_version <= our_napi_version) {
best_napi_build_version = napi_build_version;
}
});
}
return best_napi_build_version === 0 ? undefined : best_napi_build_version;
};
module.exports.build_napi_only = function(package_json) {
return package_json.binary && package_json.binary.package_name &&
package_json.binary.package_name.indexOf('{node_napi_label}') === -1;
};

View File

@ -0,0 +1,26 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Node-webkit-based module test</title>
<script>
function nwModuleTest(){
var util = require('util');
var moduleFolder = require('nw.gui').App.argv[0];
try {
require(moduleFolder);
} catch(e) {
if( process.platform !== 'win32' ){
util.log('nw-pre-gyp error:');
util.log(e.stack);
}
process.exit(1);
}
process.exit(0);
}
</script>
</head>
<body onload="nwModuleTest()">
<h1>Node-webkit-based module test</h1>
</body>
</html>

View File

@ -0,0 +1,9 @@
{
"main": "index.html",
"name": "nw-pre-gyp-module-test",
"description": "Node-webkit-based module test.",
"version": "0.0.1",
"window": {
"show": false
}
}

View File

@ -0,0 +1,163 @@
'use strict';
module.exports = exports;
const url = require('url');
const fs = require('fs');
const path = require('path');
module.exports.detect = function(opts, config) {
const to = opts.hosted_path;
const uri = url.parse(to);
config.prefix = (!uri.pathname || uri.pathname === '/') ? '' : uri.pathname.replace('/', '');
if (opts.bucket && opts.region) {
config.bucket = opts.bucket;
config.region = opts.region;
config.endpoint = opts.host;
config.s3ForcePathStyle = opts.s3ForcePathStyle;
} else {
const parts = uri.hostname.split('.s3');
const bucket = parts[0];
if (!bucket) {
return;
}
if (!config.bucket) {
config.bucket = bucket;
}
if (!config.region) {
const region = parts[1].slice(1).split('.')[0];
if (region === 'amazonaws') {
config.region = 'us-east-1';
} else {
config.region = region;
}
}
}
};
module.exports.get_s3 = function(config) {
if (process.env.node_pre_gyp_mock_s3) {
// here we're mocking. node_pre_gyp_mock_s3 is the scratch directory
// for the mock code.
const AWSMock = require('mock-aws-s3');
const os = require('os');
AWSMock.config.basePath = `${os.tmpdir()}/mock`;
const s3 = AWSMock.S3();
// wrapped callback maker. fs calls return code of ENOENT but AWS.S3 returns
// NotFound.
const wcb = (fn) => (err, ...args) => {
if (err && err.code === 'ENOENT') {
err.code = 'NotFound';
}
return fn(err, ...args);
};
return {
listObjects(params, callback) {
return s3.listObjects(params, wcb(callback));
},
headObject(params, callback) {
return s3.headObject(params, wcb(callback));
},
deleteObject(params, callback) {
return s3.deleteObject(params, wcb(callback));
},
putObject(params, callback) {
return s3.putObject(params, wcb(callback));
}
};
}
// if not mocking then setup real s3.
const AWS = require('aws-sdk');
AWS.config.update(config);
const s3 = new AWS.S3();
// need to change if additional options need to be specified.
return {
listObjects(params, callback) {
return s3.listObjects(params, callback);
},
headObject(params, callback) {
return s3.headObject(params, callback);
},
deleteObject(params, callback) {
return s3.deleteObject(params, callback);
},
putObject(params, callback) {
return s3.putObject(params, callback);
}
};
};
//
// function to get the mocking control function. if not mocking it returns a no-op.
//
// if mocking it sets up the mock http interceptors that use the mocked s3 file system
// to fulfill reponses.
module.exports.get_mockS3Http = function() {
let mock_s3 = false;
if (!process.env.node_pre_gyp_mock_s3) {
return () => mock_s3;
}
const nock = require('nock');
// the bucket used for testing, as addressed by https.
const host = 'https://mapbox-node-pre-gyp-public-testing-bucket.s3.us-east-1.amazonaws.com';
const mockDir = process.env.node_pre_gyp_mock_s3 + '/mapbox-node-pre-gyp-public-testing-bucket';
// function to setup interceptors. they are "turned off" by setting mock_s3 to false.
const mock_http = () => {
// eslint-disable-next-line no-unused-vars
function get(uri, requestBody) {
const filepath = path.join(mockDir, uri.replace('%2B', '+'));
try {
fs.accessSync(filepath, fs.constants.R_OK);
} catch (e) {
return [404, 'not found\n'];
}
// the mock s3 functions just write to disk, so just read from it.
return [200, fs.createReadStream(filepath)];
}
// eslint-disable-next-line no-unused-vars
return nock(host)
.persist()
.get(() => mock_s3) // mock any uri for s3 when true
.reply(get);
};
// setup interceptors. they check the mock_s3 flag to determine whether to intercept.
mock_http(nock, host, mockDir);
// function to turn matching all requests to s3 on/off.
const mockS3Http = (action) => {
const previous = mock_s3;
if (action === 'off') {
mock_s3 = false;
} else if (action === 'on') {
mock_s3 = true;
} else if (action !== 'get') {
throw new Error(`illegal action for setMockHttp ${action}`);
}
return previous;
};
// call mockS3Http with the argument
// - 'on' - turn it on
// - 'off' - turn it off (used by fetch.test.js so it doesn't interfere with redirects)
// - 'get' - return true or false for 'on' or 'off'
return mockS3Http;
};

View File

@ -0,0 +1,335 @@
'use strict';
module.exports = exports;
const path = require('path');
const semver = require('semver');
const url = require('url');
const detect_libc = require('detect-libc');
const napi = require('./napi.js');
let abi_crosswalk;
// This is used for unit testing to provide a fake
// ABI crosswalk that emulates one that is not updated
// for the current version
if (process.env.NODE_PRE_GYP_ABI_CROSSWALK) {
abi_crosswalk = require(process.env.NODE_PRE_GYP_ABI_CROSSWALK);
} else {
abi_crosswalk = require('./abi_crosswalk.json');
}
const major_versions = {};
Object.keys(abi_crosswalk).forEach((v) => {
const major = v.split('.')[0];
if (!major_versions[major]) {
major_versions[major] = v;
}
});
function get_electron_abi(runtime, target_version) {
if (!runtime) {
throw new Error('get_electron_abi requires valid runtime arg');
}
if (typeof target_version === 'undefined') {
// erroneous CLI call
throw new Error('Empty target version is not supported if electron is the target.');
}
// Electron guarantees that patch version update won't break native modules.
const sem_ver = semver.parse(target_version);
return runtime + '-v' + sem_ver.major + '.' + sem_ver.minor;
}
module.exports.get_electron_abi = get_electron_abi;
function get_node_webkit_abi(runtime, target_version) {
if (!runtime) {
throw new Error('get_node_webkit_abi requires valid runtime arg');
}
if (typeof target_version === 'undefined') {
// erroneous CLI call
throw new Error('Empty target version is not supported if node-webkit is the target.');
}
return runtime + '-v' + target_version;
}
module.exports.get_node_webkit_abi = get_node_webkit_abi;
function get_node_abi(runtime, versions) {
if (!runtime) {
throw new Error('get_node_abi requires valid runtime arg');
}
if (!versions) {
throw new Error('get_node_abi requires valid process.versions object');
}
const sem_ver = semver.parse(versions.node);
if (sem_ver.major === 0 && sem_ver.minor % 2) { // odd series
// https://github.com/mapbox/node-pre-gyp/issues/124
return runtime + '-v' + versions.node;
} else {
// process.versions.modules added in >= v0.10.4 and v0.11.7
// https://github.com/joyent/node/commit/ccabd4a6fa8a6eb79d29bc3bbe9fe2b6531c2d8e
return versions.modules ? runtime + '-v' + (+versions.modules) :
'v8-' + versions.v8.split('.').slice(0, 2).join('.');
}
}
module.exports.get_node_abi = get_node_abi;
function get_runtime_abi(runtime, target_version) {
if (!runtime) {
throw new Error('get_runtime_abi requires valid runtime arg');
}
if (runtime === 'node-webkit') {
return get_node_webkit_abi(runtime, target_version || process.versions['node-webkit']);
} else if (runtime === 'electron') {
return get_electron_abi(runtime, target_version || process.versions.electron);
} else {
if (runtime !== 'node') {
throw new Error("Unknown Runtime: '" + runtime + "'");
}
if (!target_version) {
return get_node_abi(runtime, process.versions);
} else {
let cross_obj;
// abi_crosswalk generated with ./scripts/abi_crosswalk.js
if (abi_crosswalk[target_version]) {
cross_obj = abi_crosswalk[target_version];
} else {
const target_parts = target_version.split('.').map((i) => { return +i; });
if (target_parts.length !== 3) { // parse failed
throw new Error('Unknown target version: ' + target_version);
}
/*
The below code tries to infer the last known ABI compatible version
that we have recorded in the abi_crosswalk.json when an exact match
is not possible. The reasons for this to exist are complicated:
- We support passing --target to be able to allow developers to package binaries for versions of node
that are not the same one as they are running. This might also be used in combination with the
--target_arch or --target_platform flags to also package binaries for alternative platforms
- When --target is passed we can't therefore determine the ABI (process.versions.modules) from the node
version that is running in memory
- So, therefore node-pre-gyp keeps an "ABI crosswalk" (lib/util/abi_crosswalk.json) to be able to look
this info up for all versions
- But we cannot easily predict what the future ABI will be for released versions
- And node-pre-gyp needs to be a `bundledDependency` in apps that depend on it in order to work correctly
by being fully available at install time.
- So, the speed of node releases and the bundled nature of node-pre-gyp mean that a new node-pre-gyp release
need to happen for every node.js/io.js/node-webkit/nw.js/atom-shell/etc release that might come online if
you want the `--target` flag to keep working for the latest version
- Which is impractical ^^
- Hence the below code guesses about future ABI to make the need to update node-pre-gyp less demanding.
In practice then you can have a dependency of your app like `node-sqlite3` that bundles a `node-pre-gyp` that
only knows about node v0.10.33 in the `abi_crosswalk.json` but target node v0.10.34 (which is assumed to be
ABI compatible with v0.10.33).
TODO: use semver module instead of custom version parsing
*/
const major = target_parts[0];
let minor = target_parts[1];
let patch = target_parts[2];
// io.js: yeah if node.js ever releases 1.x this will break
// but that is unlikely to happen: https://github.com/iojs/io.js/pull/253#issuecomment-69432616
if (major === 1) {
// look for last release that is the same major version
// e.g. we assume io.js 1.x is ABI compatible with >= 1.0.0
while (true) {
if (minor > 0) --minor;
if (patch > 0) --patch;
const new_iojs_target = '' + major + '.' + minor + '.' + patch;
if (abi_crosswalk[new_iojs_target]) {
cross_obj = abi_crosswalk[new_iojs_target];
console.log('Warning: node-pre-gyp could not find exact match for ' + target_version);
console.log('Warning: but node-pre-gyp successfully choose ' + new_iojs_target + ' as ABI compatible target');
break;
}
if (minor === 0 && patch === 0) {
break;
}
}
} else if (major >= 2) {
// look for last release that is the same major version
if (major_versions[major]) {
cross_obj = abi_crosswalk[major_versions[major]];
console.log('Warning: node-pre-gyp could not find exact match for ' + target_version);
console.log('Warning: but node-pre-gyp successfully choose ' + major_versions[major] + ' as ABI compatible target');
}
} else if (major === 0) { // node.js
if (target_parts[1] % 2 === 0) { // for stable/even node.js series
// look for the last release that is the same minor release
// e.g. we assume node 0.10.x is ABI compatible with >= 0.10.0
while (--patch > 0) {
const new_node_target = '' + major + '.' + minor + '.' + patch;
if (abi_crosswalk[new_node_target]) {
cross_obj = abi_crosswalk[new_node_target];
console.log('Warning: node-pre-gyp could not find exact match for ' + target_version);
console.log('Warning: but node-pre-gyp successfully choose ' + new_node_target + ' as ABI compatible target');
break;
}
}
}
}
}
if (!cross_obj) {
throw new Error('Unsupported target version: ' + target_version);
}
// emulate process.versions
const versions_obj = {
node: target_version,
v8: cross_obj.v8 + '.0',
// abi_crosswalk uses 1 for node versions lacking process.versions.modules
// process.versions.modules added in >= v0.10.4 and v0.11.7
modules: cross_obj.node_abi > 1 ? cross_obj.node_abi : undefined
};
return get_node_abi(runtime, versions_obj);
}
}
}
module.exports.get_runtime_abi = get_runtime_abi;
const required_parameters = [
'module_name',
'module_path',
'host'
];
function validate_config(package_json, opts) {
const msg = package_json.name + ' package.json is not node-pre-gyp ready:\n';
const missing = [];
if (!package_json.main) {
missing.push('main');
}
if (!package_json.version) {
missing.push('version');
}
if (!package_json.name) {
missing.push('name');
}
if (!package_json.binary) {
missing.push('binary');
}
const o = package_json.binary;
if (o) {
required_parameters.forEach((p) => {
if (!o[p] || typeof o[p] !== 'string') {
missing.push('binary.' + p);
}
});
}
if (missing.length >= 1) {
throw new Error(msg + 'package.json must declare these properties: \n' + missing.join('\n'));
}
if (o) {
// enforce https over http
const protocol = url.parse(o.host).protocol;
if (protocol === 'http:') {
throw new Error("'host' protocol (" + protocol + ") is invalid - only 'https:' is accepted");
}
}
napi.validate_package_json(package_json, opts);
}
module.exports.validate_config = validate_config;
function eval_template(template, opts) {
Object.keys(opts).forEach((key) => {
const pattern = '{' + key + '}';
while (template.indexOf(pattern) > -1) {
template = template.replace(pattern, opts[key]);
}
});
return template;
}
// url.resolve needs single trailing slash
// to behave correctly, otherwise a double slash
// may end up in the url which breaks requests
// and a lacking slash may not lead to proper joining
function fix_slashes(pathname) {
if (pathname.slice(-1) !== '/') {
return pathname + '/';
}
return pathname;
}
// remove double slashes
// note: path.normalize will not work because
// it will convert forward to back slashes
function drop_double_slashes(pathname) {
return pathname.replace(/\/\//g, '/');
}
function get_process_runtime(versions) {
let runtime = 'node';
if (versions['node-webkit']) {
runtime = 'node-webkit';
} else if (versions.electron) {
runtime = 'electron';
}
return runtime;
}
module.exports.get_process_runtime = get_process_runtime;
const default_package_name = '{module_name}-v{version}-{node_abi}-{platform}-{arch}.tar.gz';
const default_remote_path = '';
module.exports.evaluate = function(package_json, options, napi_build_version) {
options = options || {};
validate_config(package_json, options); // options is a suitable substitute for opts in this case
const v = package_json.version;
const module_version = semver.parse(v);
const runtime = options.runtime || get_process_runtime(process.versions);
const opts = {
name: package_json.name,
configuration: options.debug ? 'Debug' : 'Release',
debug: options.debug,
module_name: package_json.binary.module_name,
version: module_version.version,
prerelease: module_version.prerelease.length ? module_version.prerelease.join('.') : '',
build: module_version.build.length ? module_version.build.join('.') : '',
major: module_version.major,
minor: module_version.minor,
patch: module_version.patch,
runtime: runtime,
node_abi: get_runtime_abi(runtime, options.target),
node_abi_napi: napi.get_napi_version(options.target) ? 'napi' : get_runtime_abi(runtime, options.target),
napi_version: napi.get_napi_version(options.target), // non-zero numeric, undefined if unsupported
napi_build_version: napi_build_version || '',
node_napi_label: napi_build_version ? 'napi-v' + napi_build_version : get_runtime_abi(runtime, options.target),
target: options.target || '',
platform: options.target_platform || process.platform,
target_platform: options.target_platform || process.platform,
arch: options.target_arch || process.arch,
target_arch: options.target_arch || process.arch,
libc: options.target_libc || detect_libc.familySync() || 'unknown',
module_main: package_json.main,
toolset: options.toolset || '', // address https://github.com/mapbox/node-pre-gyp/issues/119
bucket: package_json.binary.bucket,
region: package_json.binary.region,
s3ForcePathStyle: package_json.binary.s3ForcePathStyle || false
};
// support host mirror with npm config `--{module_name}_binary_host_mirror`
// e.g.: https://github.com/node-inspector/v8-profiler/blob/master/package.json#L25
// > npm install v8-profiler --profiler_binary_host_mirror=https://npm.taobao.org/mirrors/node-inspector/
const validModuleName = opts.module_name.replace('-', '_');
const host = process.env['npm_config_' + validModuleName + '_binary_host_mirror'] || package_json.binary.host;
opts.host = fix_slashes(eval_template(host, opts));
opts.module_path = eval_template(package_json.binary.module_path, opts);
// now we resolve the module_path to ensure it is absolute so that binding.gyp variables work predictably
if (options.module_root) {
// resolve relative to known module root: works for pre-binding require
opts.module_path = path.join(options.module_root, opts.module_path);
} else {
// resolve relative to current working directory: works for node-pre-gyp commands
opts.module_path = path.resolve(opts.module_path);
}
opts.module = path.join(opts.module_path, opts.module_name + '.node');
opts.remote_path = package_json.binary.remote_path ? drop_double_slashes(fix_slashes(eval_template(package_json.binary.remote_path, opts))) : default_remote_path;
const package_name = package_json.binary.package_name ? package_json.binary.package_name : default_package_name;
opts.package_name = eval_template(package_name, opts);
opts.staged_tarball = path.join('build/stage', opts.remote_path, opts.package_name);
opts.hosted_path = url.resolve(opts.host, opts.remote_path);
opts.hosted_tarball = url.resolve(opts.hosted_path, opts.package_name);
return opts;
};

View File

@ -0,0 +1,62 @@
{
"name": "@mapbox/node-pre-gyp",
"description": "Node.js native addon binary install tool",
"version": "1.0.11",
"keywords": [
"native",
"addon",
"module",
"c",
"c++",
"bindings",
"binary"
],
"license": "BSD-3-Clause",
"author": "Dane Springmeyer <dane@mapbox.com>",
"repository": {
"type": "git",
"url": "git://github.com/mapbox/node-pre-gyp.git"
},
"bin": "./bin/node-pre-gyp",
"main": "./lib/node-pre-gyp.js",
"dependencies": {
"detect-libc": "^2.0.0",
"https-proxy-agent": "^5.0.0",
"make-dir": "^3.1.0",
"node-fetch": "^2.6.7",
"nopt": "^5.0.0",
"npmlog": "^5.0.1",
"rimraf": "^3.0.2",
"semver": "^7.3.5",
"tar": "^6.1.11"
},
"devDependencies": {
"@mapbox/cloudfriend": "^5.1.0",
"@mapbox/eslint-config-mapbox": "^3.0.0",
"aws-sdk": "^2.1087.0",
"codecov": "^3.8.3",
"eslint": "^7.32.0",
"eslint-plugin-node": "^11.1.0",
"mock-aws-s3": "^4.0.2",
"nock": "^12.0.3",
"node-addon-api": "^4.3.0",
"nyc": "^15.1.0",
"tape": "^5.5.2",
"tar-fs": "^2.1.1"
},
"nyc": {
"all": true,
"skip-full": false,
"exclude": [
"test/**"
]
},
"scripts": {
"coverage": "nyc --all --include index.js --include lib/ npm test",
"upload-coverage": "nyc report --reporter json && codecov --clear --flags=unit --file=./coverage/coverage-final.json",
"lint": "eslint bin/node-pre-gyp lib/*js lib/util/*js test/*js scripts/*js",
"fix": "npm run lint -- --fix",
"update-crosswalk": "node scripts/abi_crosswalk.js",
"test": "tape test/*test.js"
}
}

View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) Microsoft Corporation.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE

View File

@ -0,0 +1,16 @@
# Installation
> `npm install --save @types/base64-js`
# Summary
This package contains type definitions for base64-js (https://github.com/beatgammit/base64-js).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/base64-js.
### Additional Details
* Last updated: Sat, 30 May 2020 11:37:42 GMT
* Dependencies: none
* Global values: `base64js`
# Credits
These definitions were written by [Peter Safranek](https://github.com/pe8ter), and [Piotr Błażejewicz](https://github.com/peterblazejewicz).

View File

@ -0,0 +1,23 @@
// Type definitions for base64-js 1.3
// Project: https://github.com/beatgammit/base64-js
// Definitions by: Peter Safranek <https://github.com/pe8ter>
// Piotr Błażejewicz <https://github.com/peterblazejewicz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/**
* Takes a base64 string and returns length of byte array
*/
export function byteLength(encoded: string): number;
/**
* Takes a base64 string and returns a byte array
*/
export function toByteArray(encoded: string): Uint8Array;
/**
* Takes a byte array and returns a base64 string
*/
export function fromByteArray(bytes: Uint8Array): string;
/**
* base64-js does basic base64 encoding/decoding in pure JS.
*/
export as namespace base64js;

View File

@ -0,0 +1,29 @@
{
"name": "@types/base64-js",
"version": "1.3.0",
"description": "TypeScript definitions for base64-js",
"license": "MIT",
"contributors": [
{
"name": "Peter Safranek",
"url": "https://github.com/pe8ter",
"githubUsername": "pe8ter"
},
{
"name": "Piotr Błażejewicz",
"url": "https://github.com/peterblazejewicz",
"githubUsername": "peterblazejewicz"
}
],
"main": "",
"types": "index.d.ts",
"repository": {
"type": "git",
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
"directory": "types/base64-js"
},
"scripts": {},
"dependencies": {},
"typesPublisherContentHash": "e6bd0df8b11e91971b368458cd8efd876cd22efd2530529d73b9e810725d15bd",
"typeScriptVersion": "3.0"
}

View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) Microsoft Corporation.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE

View File

@ -0,0 +1,16 @@
# Installation
> `npm install --save @types/pako`
# Summary
This package contains type definitions for pako (https://github.com/nodeca/pako).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/pako.
### Additional Details
* Last updated: Thu, 12 May 2022 19:01:46 GMT
* Dependencies: none
* Global values: `pako`
# Credits
These definitions were written by [Caleb Eggensperger](https://github.com/calebegg), [Muhammet Öztürk](https://github.com/hlthi), and [Thibault Poisson](https://github.com/OrIOg).

165
npm-packages/mac-v2.4.x/@types/pako/index.d.ts vendored Executable file
View File

@ -0,0 +1,165 @@
// Type definitions for pako 2.0
// Project: https://github.com/nodeca/pako
// Definitions by: Caleb Eggensperger <https://github.com/calebegg>
// Muhammet Öztürk <https://github.com/hlthi>
// Thibault Poisson <https://github.com/OrIOg>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = Pako;
export as namespace pako;
declare namespace Pako {
enum constants {
// FlushValues
Z_NO_FLUSH = 0,
Z_PARTIAL_FLUSH = 1,
Z_SYNC_FLUSH = 2,
Z_FULL_FLUSH = 3,
Z_FINISH = 4,
Z_BLOCK = 5,
Z_TREES = 6,
// StrategyValues
Z_FILTERED = 1,
Z_HUFFMAN_ONLY = 2,
Z_RLE = 3,
Z_FIXED = 4,
Z_DEFAULT_STRATEGY = 0,
// ReturnCodes
Z_OK = 0,
Z_STREAM_END = 1,
Z_NEED_DICT = 2,
Z_ERRNO = -1,
Z_STREAM_ERROR = -2,
Z_DATA_ERROR = -3,
Z_BUF_ERROR = -5,
}
type FlushValues =
| constants.Z_NO_FLUSH
| constants.Z_PARTIAL_FLUSH
| constants.Z_SYNC_FLUSH
| constants.Z_FINISH
| constants.Z_BLOCK
| constants.Z_TREES;
type StrategyValues =
| constants.Z_FILTERED
| constants.Z_HUFFMAN_ONLY
| constants.Z_RLE
| constants.Z_FIXED
| constants.Z_DEFAULT_STRATEGY;
type ReturnCodes =
| constants.Z_OK
| constants.Z_STREAM_END
| constants.Z_NEED_DICT
| constants.Z_ERRNO
| constants.Z_STREAM_ERROR
| constants.Z_DATA_ERROR
| constants.Z_BUF_ERROR
| constants.Z_DEFAULT_STRATEGY;
interface DeflateOptions {
level?: -1 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | undefined;
windowBits?: number | undefined;
memLevel?: number | undefined;
strategy?: StrategyValues | undefined;
dictionary?: any;
raw?: boolean | undefined;
chunkSize?: number | undefined;
gzip?: boolean | undefined;
header?: Header | undefined;
}
interface DeflateFunctionOptions {
level?: -1 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | undefined;
windowBits?: number | undefined;
memLevel?: number | undefined;
strategy?: StrategyValues | undefined;
dictionary?: any;
raw?: boolean | undefined;
}
interface InflateOptions {
windowBits?: number | undefined;
dictionary?: any;
raw?: boolean | undefined;
to?: 'string' | undefined;
chunkSize?: number | undefined;
}
interface InflateFunctionOptions {
windowBits?: number | undefined;
raw?: boolean | undefined;
to?: 'string' | undefined;
}
interface Header {
text?: boolean | undefined;
time?: number | undefined;
os?: number | undefined;
extra?: number[] | undefined;
name?: string | undefined;
comment?: string | undefined;
hcrc?: boolean | undefined;
}
type Data = Uint8Array | ArrayBuffer;
/**
* Compress data with deflate algorithm and options.
*/
function deflate(data: Data | string, options?: DeflateFunctionOptions): Uint8Array;
/**
* The same as deflate, but creates raw data, without wrapper (header and adler32 crc).
*/
function deflateRaw(data: Data | string, options?: DeflateFunctionOptions): Uint8Array;
/**
* The same as deflate, but create gzip wrapper instead of deflate one.
*/
function gzip(data: Data | string, options?: DeflateFunctionOptions): Uint8Array;
/**
* Decompress data with inflate/ungzip and options. Autodetect format via wrapper header
* by default. That's why we don't provide separate ungzip method.
*/
function inflate(data: Data, options: InflateFunctionOptions & { to: 'string' }): string;
function inflate(data: Data, options?: InflateFunctionOptions): Uint8Array;
/**
* The same as inflate, but creates raw data, without wrapper (header and adler32 crc).
*/
function inflateRaw(data: Data, options: InflateFunctionOptions & { to: 'string' }): string;
function inflateRaw(data: Data, options?: InflateFunctionOptions): Uint8Array;
/**
* Just shortcut to inflate, because it autodetects format by header.content. Done for convenience.
*/
function ungzip(data: Data, options: InflateFunctionOptions & { to: 'string' }): string;
function ungzip(data: Data, options?: InflateFunctionOptions): Uint8Array;
// https://github.com/nodeca/pako/blob/893381abcafa10fa2081ce60dae7d4d8e873a658/lib/deflate.js
class Deflate {
constructor(options?: DeflateOptions);
err: ReturnCodes;
msg: string;
result: Uint8Array;
onData(chunk: Data): void;
onEnd(status: number): void;
push(data: Data | string, mode?: FlushValues | boolean): boolean;
}
// https://github.com/nodeca/pako/blob/893381abcafa10fa2081ce60dae7d4d8e873a658/lib/inflate.js
class Inflate {
constructor(options?: InflateOptions);
header?: Header | undefined;
err: ReturnCodes;
msg: string;
result: Uint8Array | string;
onData(chunk: Data): void;
onEnd(status: number): void;
push(data: Data, mode?: FlushValues | boolean): boolean;
}
}

View File

@ -0,0 +1,35 @@
{
"name": "@types/pako",
"version": "2.0.0",
"description": "TypeScript definitions for pako",
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/pako",
"license": "MIT",
"contributors": [
{
"name": "Caleb Eggensperger",
"url": "https://github.com/calebegg",
"githubUsername": "calebegg"
},
{
"name": "Muhammet Öztürk",
"url": "https://github.com/hlthi",
"githubUsername": "hlthi"
},
{
"name": "Thibault Poisson",
"url": "https://github.com/OrIOg",
"githubUsername": "OrIOg"
}
],
"main": "",
"types": "index.d.ts",
"repository": {
"type": "git",
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
"directory": "types/pako"
},
"scripts": {},
"dependencies": {},
"typesPublisherContentHash": "0a882d9f463daa4cbaa64b6990d0bfd752a2e64fed6f24266d589f8ae4faca1d",
"typeScriptVersion": "3.9"
}

View File

@ -0,0 +1,46 @@
This software is dual-licensed under the ISC and MIT licenses.
You may use this software under EITHER of the following licenses.
----------
The ISC License
Copyright (c) Isaac Z. Schlueter and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
----------
Copyright Isaac Z. Schlueter and Contributors
All rights reserved.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1,23 @@
# abbrev-js
Just like [ruby's Abbrev](http://apidock.com/ruby/Abbrev).
Usage:
var abbrev = require("abbrev");
abbrev("foo", "fool", "folding", "flop");
// returns:
{ fl: 'flop'
, flo: 'flop'
, flop: 'flop'
, fol: 'folding'
, fold: 'folding'
, foldi: 'folding'
, foldin: 'folding'
, folding: 'folding'
, foo: 'foo'
, fool: 'fool'
}
This is handy for command-line scripts, or other cases where you want to be able to accept shorthands.

View File

@ -0,0 +1,61 @@
module.exports = exports = abbrev.abbrev = abbrev
abbrev.monkeyPatch = monkeyPatch
function monkeyPatch () {
Object.defineProperty(Array.prototype, 'abbrev', {
value: function () { return abbrev(this) },
enumerable: false, configurable: true, writable: true
})
Object.defineProperty(Object.prototype, 'abbrev', {
value: function () { return abbrev(Object.keys(this)) },
enumerable: false, configurable: true, writable: true
})
}
function abbrev (list) {
if (arguments.length !== 1 || !Array.isArray(list)) {
list = Array.prototype.slice.call(arguments, 0)
}
for (var i = 0, l = list.length, args = [] ; i < l ; i ++) {
args[i] = typeof list[i] === "string" ? list[i] : String(list[i])
}
// sort them lexicographically, so that they're next to their nearest kin
args = args.sort(lexSort)
// walk through each, seeing how much it has in common with the next and previous
var abbrevs = {}
, prev = ""
for (var i = 0, l = args.length ; i < l ; i ++) {
var current = args[i]
, next = args[i + 1] || ""
, nextMatches = true
, prevMatches = true
if (current === next) continue
for (var j = 0, cl = current.length ; j < cl ; j ++) {
var curChar = current.charAt(j)
nextMatches = nextMatches && curChar === next.charAt(j)
prevMatches = prevMatches && curChar === prev.charAt(j)
if (!nextMatches && !prevMatches) {
j ++
break
}
}
prev = current
if (j === cl) {
abbrevs[current] = current
continue
}
for (var a = current.substr(0, j) ; j <= cl ; j ++) {
abbrevs[a] = current
a += current.charAt(j)
}
}
return abbrevs
}
function lexSort (a, b) {
return a === b ? 0 : a > b ? 1 : -1
}

View File

@ -0,0 +1,21 @@
{
"name": "abbrev",
"version": "1.1.1",
"description": "Like ruby's abbrev module, but in js",
"author": "Isaac Z. Schlueter <i@izs.me>",
"main": "abbrev.js",
"scripts": {
"test": "tap test.js --100",
"preversion": "npm test",
"postversion": "npm publish",
"postpublish": "git push origin --all; git push origin --tags"
},
"repository": "http://github.com/isaacs/abbrev-js",
"license": "ISC",
"devDependencies": {
"tap": "^10.1"
},
"files": [
"abbrev.js"
]
}

View File

@ -0,0 +1,280 @@
# Changelog
## v15.3.0
- Added support for smart layer puppet filter (`placedLayer.filter`)
## v15.2.0
- Added handling missing `font` in text layer style by assuming first font on the list
## v15.1.0
- Added support for float color in effects, new color type was added
```ts
export type FRGB = { fr: number; fg: number; fb: number; }; // values from 0 to 1 (can be above 1)
```
- Changed `time` field on `LinkedFile` from `Date` to `string` type
## v15.0.0
- Added support for frame and timeline animations
## v14.5.0
- Added support for zip compression without prediction of image data
- Added support for `compress` option when writing
## v14.4.0
- Added support for `layerMaskAsGlobalMask` flag
- Added support for `interpolationMethod` for gradient overlay layer blending mode
## v14.3.13
- Fixed handling files with incorrect channel image data length
## v14.3.11
- Fixed corrupted file when passing non-integer values to `layer.left`, `.top`, `.right`, `.bottom`
## v14.3.9
- Fixed reading some corrupted files
## v14.3.8
- Fixed handling files with incorrect section sizes
## v14.3.6
- Fixed incorrect writing of `vogk` section in some cases resulting in a broken file
## v14.3.6
- Fixed incorrect writing of `vogk` section in some cases resulting in a broken file
## v14.3.2
- Added `nonAffineTransform` field to smart object transform when nonAffineTransform is diferent than regular transform
## v14.3.1
- Fixed writing paragraphStyle autoLeading property (previous it was writing incorrectly for whole values, like 1.0 or 2.0)
## v14.3.0
- Added support for `fillOpacity` and `transparencyShapesLayer`
- Fixed error in some cases when reading files with deeply nested layers
## v14.2.0
- Added `readCsh` function for reading photoshop custom shape files
## v14.1.0
- Added support for `imageReadyVariables` and `imageReadyDataSets` image resources
- Fix missing support for alternative image resource block signatures
## v14.0.1
- Added missing handling for new platform and platformLCD text anti-aliasing modes
## v14.0.0
- Added handling for annotations
- **BREAKING CHANGE:** Fixed reading and writing non-RGB colors and documented value ranges (value ranger for HSB, CMYK, Lab and Grayscale colors different from previous versions)
```ts
export type RGBA = { r: number; g: number; b: number; a: number; }; // values from 0 to 255
export type RGB = { r: number; g: number; b: number; }; // values from 0 to 255
export type HSB = { h: number; s: number; b: number; }; // values from 0 to 1
export type CMYK = { c: number; m: number; y: number; k: number; }; // values from 0 to 255
export type LAB = { l: number; a: number; b: number; }; // values `l` from 0 to 1; `a` and `b` from -1 to 1
export type Grayscale = { k: number }; // values from 0 to 255
export type Color = RGBA | RGB | HSB | CMYK | LAB | Grayscale;
```
- Fixed not handling correct value for text gridding
## v13.0.2
- Fixed error when opening PSB file with smart objects
## v13.0.1
- Fixed reading layer groups with missing section divider info
## v13.0.0
- **BREAKING CHANGE:** Changed how `meshPoints` are represented in warps
```ts
// old representation
interface Warp {
meshPoints: { type: 'horizontal' | 'vertical'; values: number[]; }[];
}
// new representation
interface Warp {
meshPoints: { x: number; y: number; }[];
}
```
- Fixed handling for complex warps
## v12.2.0
- Fixed incorrect length of style and paragraph style runs when reading or writing
- Added handling for `pathSelectionState`
## v12.1.0
- Added support for reading and writing PSB files (Large Document Format)
Use `psb: true` in write options to write file in PSB format)
The sizes are still limited by 32bit integer number range and will throw an error if you attempt to read any file larger than 2GB.
- Fixed some fields not handled in `vectorOrigination`
## v12.0.0
- **BREAKING CHANGE:** Added support for multiples of the same layer blending effect, these `layer.effects` keys are now arrays:
- `dropShadow`
- `innerShadow`
- `solidFill`
- `stroke`
- `gradientOverlay`
WARNING: adding more than one of effect in these arrays will result in file being saved with new version of effects section that is not readable on older versions of Photoshop.
## v11.6.2
- Fixed smart layer block info not parsing correctly in some cases
- Added automatic deduplication of layer IDs
## v11.6.1
- Fixed group blending modes not writing correctly
## v11.6.0
- Added `fromVectorData` field to `mask` object that indicates if mask image data comes from vector data attached to the layer
- Added handling `globalLayerMaskInfo` field
- Fixed vector and bitmap masks not writing correctly when used at the same time on one layer
## v11.5.1
- Added missing field `operation` to paths in vector layers
## v11.5.0
- Added `noBackground` write option to force treating bottom layer as layer instead of background when it doesn't have any transparent pixels
## v11.4.0
- Added handling for artboards
- Fixed issues with handling smart objects
- Fixed issues with handling vector layers
## v11.3.0
- Added handling for *Vector Origination Data* and *Compositor Used*
- Added handling for *ICC Untagged Profile*
- Added handling for *Lock Artbords* layer option
## v11.2.0
- Added handling for smart objects
- Changed types for text warp
## v11.1.0
- Added handling for text shape (point, box)
- Fixed incorrect parsing of utf-16 strings
## v11.0.0
- **BREAKING CHANGE:** Changed all color fields from r, g, b, a array to color mode specific objects
```js
// old
var color = [red, green, blue, alpha];
// new
var rgbColor = { r: red, g: green, b: blue };
var hsbColor = { h: hue, s: saturation, b: brightness };
var labColor = { l: L, a: A, b: B };
var cmykColor = { c: cyan, m: magenta, y: yellow, k: black };
var grayscaleColor = { k: grayscaleValue };
// reading new colors
if ('r' in color) {
// read RGB color
} else if ('h' in color) {
// read HSB color
} else if ('l' in color) {
// read Lab color
} else if ('c' in color) {
// read CMYK color
} else {
// read grayscale color
}
// almost all color in PSD document follow main document color mode, so you can use this shortcut in your code
if ('r' in color) {
// read RGB color
} else {
// error or use default
}
```
## v10.0.0
- **BREAKING CHANGE:** Removed `unicodeAlphaNames` image resource (use `alphaChannelNames` instead)
- **BREAKING CHANGE:** Replaced `sheetColors` layer field with `layerColor` field
- **BREAKING CHANGE:** Changed mask density fields to be in 0-1 range (instead of 0-255)
- Removed `metadata` field from layers
- Fixed incorrectly writing layer masks information in some cases
- Added handling for adjustment layers
- Added `timestamp` field to layers
- Added `printInformation` image resource
## v9.1.1
- Fixed saved PSD files broken in some cases
## v9.1.0
- Added missing support for "stroke" blending option
## v9.0.0
- **BREAKING CHANGE:** Changed some numerical fields in effects objects to value+units fields
- Added handling for vector layers
- Added option for reading and writing raw image data using `imageData` fields corresponding to `canvas` fields on layer objects. (use `useImageData` option for reading raw data instead of using canvas objects, for writing initialize `imageData` fields instead of `canvas` fields)
- Added option for reading and writing raw, compressed thumbnail image data using `thumbnailRaw` field. (use `useRawThumbnail` option for reading raw data instead of using canvas object)
- Added `backgroundColor` image resource
- Added `xmpMetadata` image resource
- Added `printFlags` image resource
- Added `idsSeedNumber` image resource
- Added typescript type for blendModes
- Fixed writing incorrect binary data in some cases
- Fixed field name for `sectionDivider.subType`
- Fixed reading mask parameters
## v8.0.0
- Added handling for reading and writing text layer data (with some limitations)
- Added `invalidateTextLayers` write options for forcing Photoshop to redraw updated text layer.
- Removed unnecessary `version` fields from `pixelAspectRatio` and `versionInfo` image resources.
## v7.0.0
- **BREAKING CHANGE:** Normalized handling of opacity (now all opacity fields are in 0-1 range, instead of 0-255)
- **BREAKING CHANGE:** Fixed handling for colors (colors are now represented by an array of 4 values in 0-255 range as [R, G, B, A], for example: `[255, 0, 0, 255]` for opaque red color)
- Added handling for layer effects (blending options) (supports all effects except "Pattern Overlay")
- Added `writePsdUint8Array` function for saving to `Uint8Array` (this avoids double memory allocation)
- Removed unnecessary `version` field from `gridAndGuidesInformation` field
## v6.3.0
- Added exported byteArrayToBase64 function
- Updated readme with exampla of usage in web worker
## v6.2.0
- Added print scale image resource handling
- Added caption digest image resource handling
## v6.1.0
- Added loading and saving layer masks
## v6.0.0
- Changed reading to ignore not implemented features by default instead of throwing
- Removed logging missing handling for layer info
- Added `throwForMissingFeatures` and `logMissingFeatures` read options for previous behavior
## v5.0.0
- Simplified canvas initialization on NodeJS
before:
```typescript
import { createCanvas } from 'canvas';
import { readPsd, initializeCanvas } from 'ag-psd';
initializeCanvas(createCanvas);
```
after:
```typescript
import 'ag-psd/initialize-canvas';
import { readPsd } from 'ag-psd';
```
- Changed `writePsd()` method to always return `ArrayBuffer`. If you need `Buffer` as a result use `writePsdBuffer()` method instead.
- Simplified script import on browser, now import is the same on both platforms.
before:
```typescript
// node
import { readPsd } from 'ag-psd';
// browser
import { readPsd } from 'ag-psd/dist/browser';
```
after:
```typescript
// node or browser
import { readPsd } from 'ag-psd';
```

View File

@ -0,0 +1,26 @@
The MIT License (MIT)
Copyright (c) 2016 Agamnentzar
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Any image or brush files included in this repository are not covered by this
license and belong to their copyright holders.

View File

@ -0,0 +1,518 @@
# ag-psd
[![Build Status](https://travis-ci.org/Agamnentzar/ag-psd.svg)](https://travis-ci.org/Agamnentzar/ag-psd)
[![npm version](https://img.shields.io/npm/v/ag-psd)](https://www.npmjs.com/package/ag-psd)
JavaScript library for reading and writing PSD files (Photoshop Document files)
Implemented according to [official documentation](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/)
, [fileformat.info](http://www.fileformat.info/format/psd/egff.htm) and a lot of trial and error.
## Limitations
* Does not support reading Indexed, CMYK, Multichannel, Duotone and LAB color modes (all supported color modes are converted to RGB mode when reading)
* Does not support writing any color modes other than RGB
* Does not support 16 bits per channel
* Does not support The Large Document Format (8BPB/PSB)
* Does not support color palettes
* Does not support animations
* Does not support patterns (or "Pattern Overlay" layer effect)
* Does not support some metadata fields
* Does not support 3d effects
* Does not support some new features from latest versions of Photoshop
* Text layers implementation is incomplete
* Writing text layer with "vertical" orientation may result in broken PSD file
* Does not support writing or reading predefined "Paragraph Styles" or "Character Styles"
* The library does not redraw bitmap data for the text layer, so files with updated/written text layers will result in a warning prompt when opening the file in Photoshop. [see more below](#updating-text-layers)
* This library does not handle redrawing layer and composite image data by itself when blending options, vector data or text options are changed. Any updates to image data have to be done by the user or updated by opening and re-saving the file in Photoshop.
## Installation
```bash
npm install ag-psd
```
## Usage
Description of the structure of Psd object used by `readPsd` and `writePsd` functions can be found in our [PSD Readme document](/README_PSD.md)
### Functions
```ts
// read PSD from ArrayBuffer, typed array or Node.js Buffer object
export function readPsd(buffer: Buffer | ArrayBuffer | BufferLike, options?: ReadOptions): Psd;
// write PSD to ArrayBuffer
export function writePsd(psd: Psd, options?: WriteOptions): ArrayBuffer;
// write PSD to Uint8Array (avoids some memory allocation)
export function writePsdUint8Array(psd: Psd, options?: WriteOptions): Uint8Array;
// write PSD to Node.js Buffer object
export function writePsdBuffer(psd: Psd, options?: WriteOptions): Buffer;
```
### Node.js
#### Reading
Needs [node-canvas](https://github.com/Automattic/node-canvas) to read image data and thumbnails.
```javascript
import * as fs from 'fs';
import 'ag-psd/initialize-canvas'; // only needed for reading image data and thumbnails
import { readPsd } from 'ag-psd';
const buffer = fs.readFileSync('my-file.psd');
// read only document structure
const psd1 = readPsd(buffer, { skipLayerImageData: true, skipCompositeImageData: true, skipThumbnail: true });
console.log(psd1);
// read document structure and image data
const psd2 = readPsd(buffer);
console.log(psd2);
// by defaults `canvas` field type is HTMLCanvasElement, so it needs to be cast to `any`
// or node-canvas `Canvas` type, in order to call `toBuffer` method
fs.writeFileSync('layer-1.png', (psd2.children[0].canvas as any).toBuffer());
```
#### Writing
```javascript
import * as fs from 'fs';
import 'ag-psd/initialize-canvas'; // only needed for writing image data and thumbnails
import { writePsdBuffer } from 'ag-psd';
const psd = {
width: 300,
height: 200,
children: [
{
name: 'Layer #1',
}
]
};
const buffer = writePsdBuffer(psd);
fs.writeFileSync('my-file.psd', buffer);
```
### Browser
#### Reading
```javascript
import { readPsd } from 'ag-psd';
const xhr = new XMLHttpRequest();
xhr.open('GET', 'my-file.psd', true);
xhr.responseType = 'arraybuffer';
xhr.addEventListener('load', function () {
const buffer = xhr.response;
const psd = readPsd(buffer);
console.log(psd);
document.body.appendChild(psd.children[0].canvas);
}, false);
xhr.send();
```
#### Writing
`saveAs` function from [FileSaver.js](https://github.com/eligrey/FileSaver.js/)
```javascript
import { writePsd } from 'ag-psd';
const psd = {
width: 300,
height: 200,
children: [
{
name: 'Layer #1',
}
]
};
const buffer = writePsd(psd);
const blob = new Blob([buffer], { type: 'application/octet-stream' });
saveAs(blob, 'my-file.psd');
```
### Browser (bundle)
```html
<script src="node_modules/ag-psd/dist/bundle.js"></script>
<script>
var readPsd = agPsd.readPsd;
// rest the same as above
</script>
```
### Browser in Web Worker
#### Reading
Browser has to support `OffscreenCanvas` and `bitmaprenderer` context.
```js
// worker.js
importScripts('bundle.js');
const createCanvas = (width, height) => {
const canvas = new OffscreenCanvas(width, height);
canvas.width = width;
canvas.height = height;
return canvas;
};
const createCanvasFromData = (data) => {
const image = new Image();
image.src = 'data:image/jpeg;base64,' + agPsd.byteArrayToBase64(data);
const canvas = new OffscreenCanvas(image.width, image.height);
canvas.width = image.width;
canvas.height = image.height;
canvas.getContext('2d').drawImage(image, 0, 0);
return canvas;
};
agPsd.initializeCanvas(createCanvas, createCanvasFromData);
onmessage = message => {
// skipping thumbnail and layer images here so we don't have to clear and convert them all
// before posting data back
const psd = agPsd.readPsd(message.data, { skipLayerImageData: true, skipThumbnail: true });
const bmp = psd.canvas.transferToImageBitmap();
delete psd.canvas; // can't post canvases back from workers
postMessage({ psd: psd, image: bmp }, [bmp]); // need to mark bitmap for transfer
};
// main script (assumes using bundle)
const worker = new Worker('worker.js');
worker.onmessage = message => {
const psd = message.data.psd;
const image = message.data.image;
// convert image back to canvas
const canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
canvas.getContext('bitmaprenderer').transferFromImageBitmap(image);
document.body.appendChild(canvas);
console.log('psd:', psd);
};
const xhr = new XMLHttpRequest();
xhr.open('GET', 'src.psd', true);
xhr.responseType = 'arraybuffer';
xhr.addEventListener('load', function () {
// read using worker
worker.postMessage(buffer, [buffer]);
}, false);
xhr.send();
```
#### Writing
```js
// worker.js
importScripts('bundle.js');
const createCanvas = (width, height) => {
const canvas = new OffscreenCanvas(width, height);
canvas.width = width;
canvas.height = height;
return canvas;
};
const createCanvasFromData = (data) => {
const image = new Image();
image.src = 'data:image/jpeg;base64,' + agPsd.byteArrayToBase64(data);
const canvas = new OffscreenCanvas(image.width, image.height);
canvas.width = image.width;
canvas.height = image.height;
canvas.getContext('2d').drawImage(image, 0, 0);
return canvas;
};
agPsd.initializeCanvas(createCanvas, createCanvasFromData);
onmessage = message => {
const psd = message.data.psd;
const image = message.data.image;
// convert bitmap back to canvas
const canvas = new OffscreenCanvas(image.width, image.height);
canvas.getContext('bitmaprenderer').transferFromImageBitmap(image);
// need to draw onto new canvas because single canvas can't use both '2d' and 'bitmaprenderer' contexts
const canvas2 = new OffscreenCanvas(canvas.width, canvas.height);
canvas2.getContext('2d').drawImage(canvas, 0, 0);
console.log(psd, canvas2);
psd.children[0].canvas = canvas2;
psd.canvas = canvas2;
const data = agPsd.writePsd(psd);
postMessage(data, [data]); // mark data as transferable
};
// main script (assumes using bundle)
const worker = new Worker('/test/worker-write.js');
worker.onmessage = message => {
const blob = new Blob([message.data]);
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.textContent = 'Download generated PSD';
a.download = 'example_psd.psd';
document.body.appendChild(a);
};
const canvas = new OffscreenCanvas(200, 200);
const context = canvas.getContext('2d');
context.fillStyle = 'white';
context.fillRect(0, 0, 200, 200);
context.fillStyle = 'red';
context.fillRect(50, 50, 120, 110);
const bmp = canvas.transferToImageBitmap(); // convert canvas to image bitmap for transfering to worker
const psd = {
width: 200,
height: 200,
children: [
{
name: 'Layer 1',
}
]
};
worker.postMessage({ psd: psd, image: bmp }, [bmp]);
```
You can see working example in `test/index.html`, `test/worker-read.js` and `test/worker-write.js`.
### Options
```typescript
interface ReadOptions {
/** Does not load layer image data. */
skipLayerImageData?: boolean;
/** Does not load composite image data. */
skipCompositeImageData?: boolean;
/** Does not load thumbnail. */
skipThumbnail?: boolean;
/** Does not load linked files (used in smart-objects). */
skipLinkedFilesData?: boolean;
/** Throws exception if features are missing. */
throwForMissingFeatures?: boolean;
/** Logs if features are missing. */
logMissingFeatures?: boolean;
/** Keep image data as byte array instead of canvas.
* (image data will appear in `imageData` fields instead of `canvas` fields)
* This avoids issues with canvas premultiplied alpha corrupting image data. */
useImageData?: boolean;
/** Loads thumbnail raw data instead of decoding it's content into canvas.
* `thumnailRaw` field is used instead of `thumbnail` field. */
useRawThumbnail?: boolean;
/** Usend only for development */
logDevFeatures?: boolean;
}
interface WriteOptions {
/** Automatically generates thumbnail from composite image. */
generateThumbnail?: boolean;
/** Trims transparent pixels from layer image data. */
trimImageData?: boolean;
/** Invalidates text layer data, forcing Photoshop to redraw them on load.
* Use this option if you're updating loaded text layer properties. */
invalidateTextLayers?: boolean;
/** Logs if features are missing. */
logMissingFeatures?: boolean;
/** Forces bottom layer to be treated as layer and not background even when it's missing any transparency
* (by default Photoshop treats bottom layer as background if it doesn't have any transparent pixels) */
noBackground?: boolean;
}
```
### Sample PSD document
Below is a simple example of document structure returned from `readPsd`. You can see full document structure in [psd.ts file](https://github.com/Agamnentzar/ag-psd/blob/master/src/psd.ts)
```json
{
"width": 300,
"height": 200,
"channels": 3,
"bitsPerChannel": 8,
"colorMode": 3,
"children": [
{
"top": 0,
"left": 0,
"bottom": 200,
"right": 300,
"blendMode": "normal",
"opacity": 1,
"transparencyProtected": false,
"hidden": true,
"clipping": false,
"name": "Layer 0",
"canvas": [Canvas]
},
{
"top": 0,
"left": 0,
"bottom": 0,
"right": 0,
"blendMode": "multiply",
"opacity": 1,
"transparencyProtected": true,
"hidden": false,
"clipping": false,
"name": "Layer 3",
"canvas": [Canvas]
}
],
"canvas": [Canvas]
}
```
## Modifying documents
General approach with `ag-psd` to modifying documents is to read the document, apply the updates and write the document back.
If you read and write the same document, image data can get corrupted by automatic alpha channel pre-multiplication that happens when you load data into the canvas element. To avoid that, use raw image data, set `useImageData` option to `true` in `ReadOptions`. You can also use `useRawThumbnail` option to avoid any changes to thumbnail image.
```js
const psd = readPsd(inputBuffer, { useImageData: true });
// TODO: update psd document here
const outuptBuffer = writePsd(psd);
```
Updating general properties that don't have visual impact on the canvas, like printing info or layer name will work correctly without any extra work.
This library does NOT generate new composite canvas based on the layer data, so changing layer order, adding or removing layers or changing layer canvas data, or blending mode, or any other property that has visual impact on the canvas will cause the composite image and thumbnail to not be valid anymore. If you need composite image or thumbnail to be correct you need to update them yourself by updating `psd.canvas` or `psd.imageData` and `psd.imageResources.thumbnail` or `psd.imageResources.thumbnailRaw` fields. Composite image data is not required for PSD file to be readble in Photoshop so leaving old version or removing it completely may be good option. Thumbnail is only necessary for file preview in programs like Adobe Bridge or File Explorer, if you don't need to support that you can skip thumbnail as well.
This library also does NOT generate new layer canvas based on layer settings, so if you're changing any layer properties, that impact layer bitmap, you also need to update `layer.canvas` or `layer.imageData`. This includes: text layer properties, vector layer properties, smart object, etc. (this does not include layer blending options)
### Writing text layers
```js
// simple example
const psd = {
width: 200,
height: 200,
children: [
{
name: 'text layer',
text: {
text: 'Hello world', // text you want to draw
transform: [1, 0, 0, 1, 50, 50], // move text 50px horizontally and 50px vertically
style: {
font: { name: 'ArialMT' }, // need to provide full name here
fontSize: 30,
fillColor: { r: 255, g: 0, b: 0 }, // opaque red
},
},
},
],
};
const buffer = writePsd(psd);
```
```js
// advanced example
const psd = {
width: 200,
height: 200,
children: [
{
name: 'text layer',
text: {
text: 'Hello world\nanother line', // text you want to draw
transform: [1, 0, 0, 1, 50, 50], // move text 50px horizontally and 50px vertically
style: {
font: { name: 'ArialMT' }, // need to provide full name here
fontSize: 30,
},
styleRuns: [
{
length: 5, // length of 'Hello'
style: { fillColor: { r: 255, g: 0, b: 0 } }, // make 'Hello' red
},
{
length: 7, // length of ' world\n'
style: { fillColor: { r: 0, g: 0, b: 255 } }, // make 'world' blue
},
{
length: 12, // length of 'another line'
style: { fillColor: { r: 0, g: 255, b: 0 }, underline: true }, // make 'another line' green and underlined
},
],
paragraphStyle: {
justification: 'center', // center justify whole block of text
},
},
},
],
};
const buffer = writePsd(psd);
```
### Updating text layers
```js
const psd = readPsd(inputBuffer);
// assuming first layer is the one you want to update and has text already present
psd.children[0].text.text = 'New text here';
// optionally remove outdated image data
psd.children[0].canvas = undefined;
// needs `invalidateTextLayers` option to force Photoshop to redraw text layer on load,
// otherwise it will keep the old image data
const outuptBuffer = writePsd(psd, { invalidateTextLayers: true });
```
When you add text layer to PSD file it is missing image data and additional text engine information. When you open file created this way in Photoshop it will display this error message, prompting you to update layer image data. You should choose "Update" which will force Photoshop to redraw text layers from text data. Clicking "No" will result in text layers being left in broken state.
![](https://raw.githubusercontent.com/Agamnentzar/ag-psd/master/files/update-text-layers.png)
### Text layer issues
Writing or updating layer orientation to vertical can end up creating broken PSD file that will crash Photoshop on opening. This is result of incomplete text layer implementation.
## Development
### Building
```bash
gulp build
```
### Testing
```bash
gulp test # run tests
gulp cov # run tests & coverage
```
### Coding
Watch task with building, testing and code coverage
```bash
gulp dev # run with build watch task
gulp dev --coverage # run with build & tests & coverage watch tasks
npm run lint # run tslint
```

View File

@ -0,0 +1,732 @@
# PSD document format
This document describes structure of the Psd object used in `readPsd` and `writePsd` functions, you can see instructions on how to use these functions in our [main README document](/README.md#functions)
You can see examples of different PSD documents and their corresponding JSON data in our [test folder](/test/read). Each subfolder contains `src.psd` document and corresponding `data.json` file with object generated by our library. Additionally there is `canvas.png` file represending composite image data, `thumb.png` file representing thumbnail image data and `layer-#.png` files with image data of each layer.
## Basic document structure
```ts
// example psd document structure
const psd: Psd = {
"width": 300,
"height": 200,
"channels": 3,
"bitsPerChannel": 8,
"colorMode": 3,
"canvas": <Canvas>,
"children": [],
};
```
- The `width` and `height` properties specify PSD document size in pixels. These values are required when writing a document.
![](/files/width-height.png)
- `channels` property specifies number of color channels in the document, it's usually 3 channels (red, green, and blue, when document is in typical RGB color mode) Other color modes will have different channel count (grayscale - 1 channel, CMYK - 4 channels). This property can be ommited when writing, this library only supports RGB color mode with 3 channels at the moment.
- `bitsPerChannel` property specifies number of bits per each color channel, this value will ba 1 for one bit bitmap color mode and 8 in all other cases as this library is not supporting 16 or 32 bit color channels at the moment. It can also be ommited when writing a document and default value of 8 will be assumed.
- `colorMode` specifies color mode of the PSD document.
![](/files/color-mode.png)
Value is one of the numbers that can be matched to this enumerable:
```ts
enum ColorMode {
Bitmap = 0,
Grayscale = 1,
Indexed = 2,
RGB = 3,
CMYK = 4,
Multichannel = 7,
Duotone = 8,
Lab = 9,
}
```
The library supports "Bitmap", "Grayscale" and "RGB" color modes at the moment. "Bitmap" and "Grayscale" colors will be converted to "RGB" colors when reading PSD file. Writing is only supported for "RGB" mode. The value can be ommited for writing and "RGB" color mode will be assumed.
- `canvas` (or `imageData`) is a property containing bitmap with composite image data for the entire document. PSD file contains this extra bitmap additionally to bitmaps of each layer. `canvas` field will be an instance of `HTMLCanvasElement` (in browser environment) or `Canvas` object of `node-canvas` library (in nodejs environment).
You can choose to instead use `imageData` field by choosing `useImageData: true` option when reading PSD file. In that can `imageData` will be an instance of `ImageData` object, containing `width`, `height` and `data` properties. This is useful if you want to use bitmap data directly, and not use it for drawing using canvas. Additionally this will preserve accurate color information as canvas element will premultiply image alpha which will change color values slightly.
If you don't need to use this field you can specify `skipCompositeImageData: true` option, while reading PSD file, to skip reading this field and save on processing time and memory usage.
This image data is optional in PSD file so it may be missing in some PSD files that opted to skip it.
When writing you can provide either `canvas` or `imageData` property and the library will use the one you provide. You can also skip the field entirely and not write this data at all as it's not needed by Photohop to read the file. It might be used in some other application, for thumbnails or by some old versions of Adobe software, so you may want to still provide it to remain compatible with those programs.
If you're generating your own PSD file and want to provide this composite image data you will have to generate one yourself by composing all layer image data and effects yourself, this library does not provide any utilities to generate this image data for you.
- `children` list of layers and groups at the root of the document. [see Layers and Groups](#layers-and-groups)
- `imageResources` contains all document-wide parameters [see Image Resouces](#image-resources)
- `linkedFiles` contains list of files linked in smart objects [see Smart Objects](#smart-objects)
- `artboards` contains global options for artboards. Artboards is a feature in new versions of Photoshop that lets you have multiple canvases in a single PSD document. The information about positioning, name and color of each artboard is stored inside each layer, in `artboard` property. This property will be absent if the document does not have any artboards specified. It can be ommited when writing.
```ts
type Artboards = {
count: number; // number of artboards in the document
autoExpandOffset?: { horizontal: number; vertical: number; };
origin?: { horizontal: number; vertical: number; };
autoExpandEnabled?: boolean;
autoNestEnabled?: boolean;
autoPositionEnabled?: boolean;
shrinkwrapOnSaveEnabled?: boolean;
docDefaultNewArtboardBackgroundColor?: Color;
docDefaultNewArtboardBackgroundType?: number;
}
```
- `annotations` contains array of annotations, this field will be absent if the document does not have any annotations. It can be ommited when writing. Sound annotations are not supported by this library right at the moment.
![](/files/annotations.png)
Each annotation object has a following structure:
```ts
interface Annotation {
type: 'text' | 'sound';
open: boolean;
iconLocation: { left: number; top: number; right: number; bottom: number };
popupLocation: { left: number; top: number; right: number; bottom: number };
color: Color;
author: string;
name: string;
date: string;
data: string | Uint8Array; // annotation text or sound buffer
}
```
- `globalLayerMaskInfo` don't really know what this is, it can be ommited when writing.
- `filterMask` don't really know what this is, it can be ommited when writing.
## Layers and Groups
Psd document object has `children` property that contains all root level layers and groups in order from top to bottom as they appear in Photoshop (take note that if you want to draw the layer images to generate document image then you need to draw them in reverse order). The `children` property will contain both regular layers and groups. Each group will have `children` property, containing all the layers and groups that are inside that group. So the document will have a tree structure like this:
```js
var psd = {
// ... other fields
children: [
{
name: "layer 1",
// ... other fields
}
{
name: "group 1",
// ... other fields
children: [
{
name: "layer 2, inside group 1",
// ... other fields
},
{
name: "group 2, inside group 1",
// ... other fields
children: []
}
]
}
]
}
```
### Layer types
You can distinguish between different layer types by checking which properties thay have set on them. If a layer has `children` property set it meas the it's a group, if it has `text` property it's a text layer and so on. If you're only interested in the basic parsing of layers and want to just extract image data or layer parameter a simple parsing like this can be enough:
```js
// simple parsing
function parseLayer(layer) {
if ('children' in layer) {
// group
layer.children.forEach(parseLayer);
} else if (layer.canvas) {
// regular layer with canvas
} else {
// empty or special layer
}
}
```
If you need to know type of each layer, something like this could be a good approach:
```ts
// complex parsing
function parseLayer(layer) {
if ('children' in layer) {
// group
layer.children.forEach(parseLayer);
} else if ('text' in layer) {
// text layer
} else if ('adjustment' in layer) {
// adjustment layer
} else if ('placedLayer' in layer) {
// smart object layer
} else if ('vectorMask' in layer) {
// vector layer
} else {
// bitmap layer
}
}
```
But thake into account that a lot of properties are shared for different types of layers. Any layer can have a `mask` property for example.
### Layer
Example layer structure:
```js
{
"top": 0,
"left": 0,
"bottom": 200,
"right": 300,
"blendMode": "normal",
"opacity": 1,
"clipping": false,
"timestamp": 1448235572.7235785,
"transparencyProtected": true,
"protected": {
"transparency": true,
"composite": false,
"position": true
},
"hidden": false,
"name": "Background",
"nameSource": "bgnd",
"id": 1,
"layerColor": "none",
"blendClippendElements": true,
"blendInteriorElements": false,
"knockout": false,
"referencePoint": {
"x": 0,
"y": 0
},
"canvas": <Canvas>
},
```
- `top`, `left`, `bottom`, `right` properties specify location of layer image data withing the document. `top` specifies offset in pixel of the top of layer image data from the top edge of the document, `bottom` specifies offset of the bottom of the layer image data from the top adge of the document and similar for `left` and `right`.
This is necessary as layer image data can be smaller or large than the document size. This can cause in some cases the values of these fields to be negative. A value of `left: -100` means that the layer image data starts 100 pixels outside the left document edge. This can happen if you move the layer left beyond document edge in Photoshop.
`top` and `left` values can be ommited when writing and will be assumed to be 0. `bottom` and `right` values can be ommited and will always be ignored when writing and will instead be calculated from `canvas` (or `imageData`) width and height.
- `blendMode` is a layer blending mode and will be one of the following values:
```ts
type BlendMode = 'pass through' | 'normal' | 'dissolve' | 'darken' |
'multiply' | 'color burn' | 'linear burn' | 'darker color' | 'lighten'|
'screen' | 'color dodge' | 'linear dodge' | 'lighter color' | 'overlay' |
'soft light' | 'hard light' | 'vivid light' | 'linear light' | 'pin light' |
'hard mix' | 'difference' | 'exclusion' | 'subtract' | 'divide' | 'hue' |
'saturation' | 'color' | 'luminosity'
```
These values correspond to naming in layer blend mode dropdown. If ommited a value of `normal` will be assumed.
[](/files/blend-modes.png)
- `canvas` (or `imageData`) see `canvas` property description in [Basic document structure](#basic-socument-structure)
Vector, text and smart object layers still have image data with pregenerated bitmap. You also need to provide that image data when writing PSD files.
Reading this property can be skipped if `skipLayerImageData: true` option is passed to `readPsd` function. This can be done to save on memory usage and processing time if layer image data is not needed.
- `opacity` specifies level of layer transparency (the value range is from 0 to 1). Can be ommited when writing, a default value of 1 will be assumed.
![](/files/opacity.png)
- `clipping` indicates if layer clipping is enabled (if enabled the layer is clipped to the layer below it). Can be ommited when writing, a default value of `false` will be assumed.
![](/files/clipping.png)
![](/files/clipping-2.png)
- `timestamp` timestamp of last time layer was modified (in unix time). Can be ommited when writing.
- `transparencyProtected` and `protected` properties specify status of various locks that you can set for each layer.
![](/files/locks.png)
- `protected.position` indicates if moving layer is locked
- `protected.composite` indicates if drawing on the layer is locked
- `protected.transparency` indicates if drawing transparent pixels are locked
If the `transparencyProtected` is `true` but `protected.transparency` is `false` it means that the layer has "lock all" enabled. Both this fields can be ommited when writing, a values of `false` will be assumed for all of the ommited fields.
- `hidden` indicates if the layer is hidden. Can be ommited when writing, a value of `false` will be assumed.
![](/files/hidden.png)
- `name` name of the layer, can be any unicode string, can be empty. Can be ommited when writing, a value of `''` will be assumed.
- `nameSource` internal Photoshop information, can be ignored and ommited when writing.
- `id` unique ID number for layer, it may be missing in some PSD files. Can be ommited when writing, but if provided it has to be a unique number, if duplicate IDs are found they will be changed to a unique ones when writing the file.
- `layerColor` color of the layer in layer list, property will be missing or will be one of the following values:
```ts
type LayerColor = 'none' | 'red' | 'orange' | 'yellow' | 'green' | 'blue' | 'violet' | 'gray'
```
![](/files/layer-color.png)
- `version` _unknown functionality_
- `referencePoint` _unknown functionality_
- `mask` Layer mask, property has the following structure.
```ts
interface LayerMaskData {
top?: number;
left?: number;
bottom?: number;
right?: number;
defaultColor?: number;
disabled?: boolean;
positionRelativeToLayer?: boolean;
fromVectorData?: boolean; // set to true if the mask is generated from vector data, false if it's a bitmap provided by user
userMaskDensity?: number;
userMaskFeather?: number; // px
vectorMaskDensity?: number;
vectorMaskFeather?: number;
canvas?: HTMLCanvasElement;
imageData?: ImageData;
}
```
![](/files/mask.png)
Similar to layer image data this data has `top`, `left`, `bottom` and `right` offsets specified.
`fromVectorData` Specifies if the mask image data was generated from `vectorMask`, if `fromVectorData` is set to false and both `vectorMask` and `mask` properties are present it means that the layer has 2 active masks, bitmap mask and a vector mask.
`mask` property will be missing when layer has no mask, it can be ommited when writing.
- `effects` Object describing layer "Blending Options"
![](/files/effects.png)
![](/files/effects-2.png)
Effects property follows the following structure:
```ts
interface LayerEffectsInfo {
disabled?: boolean; // indicates if all effects are disabled
scale?: number;
dropShadow?: LayerEffectShadow[];
innerShadow?: LayerEffectShadow[];
outerGlow?: LayerEffectsOuterGlow;
innerGlow?: LayerEffectInnerGlow;
bevel?: LayerEffectBevel;
solidFill?: LayerEffectSolidFill[];
satin?: LayerEffectSatin;
stroke?: LayerEffectStroke[];
gradientOverlay?: LayerEffectGradientOverlay[];
patternOverlay?: LayerEffectPatternOverlay; // not supported yet
}
```
Some of the effects (specified here as arrays) can be specified multiple times. This is new feature, only supported in more recent versions of Photoshop.
This property is not present if there are not blending options set for the layer. This property can be ommited when writing.
- `text` text properties of text layer
_TODO_
- `patterns` _not supported yet_
- `vectorFill` Fill color, gradient or pattern for the vector mask. Use `type` field to distinguish between different vector fill types, like this:
```ts
switch (vectorFill.type) {
case 'color':
// solid color fill ({ color: Color } type)
break;
case 'solid':
// solid gradient fill (EffectSolidGradient type)
break;
case 'noise':
// noise gradient fill (EffectNoiseGradient type)
break;
case 'pattern':
// pattern fill (EffectPattern type)
break;
}
```
- `vectorStroke` Vector stroke parameters for the vector mask. This field also contains parameters related to `vectorFill`. This property has following structure:
```ts
type VectorStroke = {
strokeEnabled?: boolean; // vector drawing has stroke
fillEnabled?: boolean; // vector drawing has fill (specified by vectorFill property)
lineWidth?: UnitsValue;
lineDashOffset?: UnitsValue;
miterLimit?: number;
lineCapType?: LineCapType;
lineJoinType?: LineJoinType;
lineAlignment?: LineAlignment;
scaleLock?: boolean;
strokeAdjust?: boolean;
lineDashSet?: UnitsValue[];
blendMode?: BlendMode;
opacity?: number;
content?: VectorContent; // stroke color, gradient or pattern (see `vectorFill` field for more information)
resolution?: number;
}
```
- `vectorMask` Specifies vector mask used by `vectorFill` and `vectorStroke` to draw vector images.
_TODO: expand this description_
- `usingAlignedRendering` _unknown functionality_
- `pathList` _not supported yet_
- `adjustment` indicates that the layer is an adjustment layer. Adjustment layer do not have image data. This property is not present on non-adjustment layers.
![](/files/adjustment.png)
Use `type` field of the adjustment object to distinguish between different adjustment layer types.
```ts
switch (adjustment.type) {
case 'brightness/contrast':
// handle BrightnessAdjustment layer
break;
case 'levels':
// handle LevelsAdjustment layer
break;
// ... other cases ...
}
```
see all Adjustment layer types in [psd.ts file](/src/psd.ts)
- `placedLayer` indicates that this is smart object layer, see [Smart Objects section](#smart-objects) for more information. This property is only present on smart object layers.
- `vectorOrigination` _TODO_
- `compositorUsed` _internal photoshop information_
- `artboard` Artboard location and parameters, this property is only present when using artboards. Artbord is object is following this structure:
```ts
type Artboard = {
rect: { top: number; left: number; bottom: number; right: number; };
guideIndices?: any[];
presetName?: string;
color?: Color;
backgroundType?: number;
}
```
![](/files/artboards.png)
- **Advanced blending options**
![](/files/advanced-blending-options.png)
- `fillOpacity`"Fill Opacity" level (value ranges from 0 to 1)
![](/files/fill-opacity.png)
- `knockout` "Knockout" value
- `blendClippendElements` "Blend Clipped Layers as Group" value
- `blendInteriorElements` "Blend Interior Effects as Group" value
- `transparencyShapesLayer` "Transparency Shapes Layer" value
- `engineData` internal text information
### Group
Example group structure:
```js
{
"top": 0,
"left": 0,
"bottom": 0,
"right": 0,
"blendMode": "normal",
"opacity": 1,
"clipping": false,
"timestamp": 1450198418.5245173,
"transparencyProtected": false,
"hidden": false,
"name": "Group 1",
"nameSource": "lset",
"id": 5,
"sectionDivider": {
"type": 1,
"key": "pass",
"subType": 0
},
"protected": {
"transparency": false,
"composite": false,
"position": false
},
"layerColor": "none",
"referencePoint": {
"x": 0,
"y": 0
},
"opened": true,
"children": [
// layers here
]
}
```
Groups don't have `canvas` / `imageData` property, as you can't draw directly on a group. Groups don't have any other special layer property like `text`, `vectorFill`, `adjustment` or `placedLayer`.
**Group-only fields:**
- `children` contains list of all layers in this group. **Cannot** be ommited when writing, without this field a group will be assumed to be a regular layer. Use empty `children` array when writing empty group.
- `opened` indicates if the group is expanded or collapsed in the layer list. If ommited a default values of `true` will be assumed.
![](/files/group-open.png)
- `sectionDivider` internal Photoshop property, can be ignored and ommited when writing.
## Image Resources
Image resources are global document settings. Any of these settings can be ommited when writing. PSD file can have following global options:
- `versionInfo` Version information of Program that generated the PSD file, example value:
```js
versionInfo = {
"hasRealMergedData": true,
"writerName": "Adobe Photoshop",
"readerName": "Adobe Photoshop CS6",
"fileVersion": 1
}
```
- `layerSelectionIds` list of layer IDs of selected layers, these layers will be selected when you open PSD document in Photoshop.
- `pixelAspectRatio` Specifies aspect ratio of the PSD document pixels, almost always 1
```js
pixelAspectRatio = {
"aspect": 1
}
```
- `gridAndGuidesInformation` Information about document guides
![](/files/guides.png)
Example value:
```js
gridAndGuidesInformation = {
"grid": {
"horizontal": 576,
"vertical": 576
},
"guides": [
{
"location": 531.4375,
"direction": "vertical" // "horizontal" or "vertical"
},
// ... more guides here ...
]
};
```
- `resolutionInfo` Image resolution info, specifies physical size of the image pixels. Example value:
```js
resolutionInfo: {
"horizontalResolution": 72,
"horizontalResolutionUnit": "PPI", // 'PPI' (pixels per inch) or 'PPCM' (pixels per centimeter)
"widthUnit": "Inches",
"verticalResolution": 72,
"verticalResolutionUnit": "PPI",
"heightUnit": "Inches" // 'Inches', 'Centimeters', 'Points', 'Picas' or 'Columns'
},
```
- `thumbnail` Canvas element with thumbnail image for the document, this property can be missing in some PSD files. This property can be ommited when writing if there's no need to support tumbnails, this field can be automatically generated from composite image data if `generateThumbnail: true` option is passed to `writePsd` function.
- `thumbnailRaw` This property will be used instead if `useRawThumbnail` option is specitied when reading PSD file.
- `xmpMetadata` XMP metadata. File info as XML description. See http://www.adobe.com/devnet/xmp/
- `iccUntaggedProfile` ICC Untagged Profile
- `printInformation`, `printScale` and `printFlags` Specifies options for printing the document.
- `layerState` _TODO_
- `layersGroup` _TODO_
- `layerGroupsEnabledId` _TODO_
- `alphaIdentifiers` _TODO_
- `alphaChannelNames` _TODO_
- `globalAngle` _TODO_
- `globalAltitude` _TODO_
- `urlsList` _TODO_
- `captionDigest` _TODO_
- `backgroundColor` _TODO_
- `idsSeedNumber` _TODO_
- `pathSelectionState` _TODO_
- `imageReadyVariables` _TODO_
- `imageReadyDataSets` _TODO_
## Smart Objects
Layers with `placedLayer` property are smart object layers. `placedLayer` property has the following structure:
```ts
interface PlacedLayer {
id: string; // id of linked image file (psd.linkedFiles)
placed?: string; // unique id
type: PlacedLayerType;
transform: number[]; // x, y of 4 corners of the transform
nonAffineTransform?: number[]; // x, y of 4 corners of the transform
width?: number;
height?: number;
resolution?: UnitsValue;
warp?: Warp;
crop?: number;
}
```
The Psd object has `linkedFiles` property, that specifies list of all files linked in smart objects. Each linked file has following structure:
```ts
interface LinkedFile {
id: string;
name: string;
type?: string;
creator?: string;
data?: Uint8Array;
time?: Date; // for external files
childDocumentID?: string;
assetModTime?: number;
assetLockedState?: number;
}
```
`id` field in `PlacedLayer` refers to the `id` in `LinkedFile`. Example values:
```js
layer.placedLayer = {
"id": "20953ddb-9391-11ec-b4f1-c15674f50bc4", // id that matches linkedFiles ID
"placed": "20953dda-9391-11ec-b4f1-c15674f50bc4", // unique id for this object
"type": "raster", // one of the 'unknown', 'vector', 'raster' or 'image stack'
"transform": [ // x, y of 4 corners of the transform box
29,
28,
83,
28,
83,
82,
29,
82
],
"width": 32, // width and height of the target image
"height": 32,
"resolution": {
"value": 299.99940490722656,
"units": "Density"
}
};
psd.linkedFiles = [
{
"id": "20953ddb-9391-11ec-b4f1-c15674f50bc4",
"name": "cat.png"
"data": fileContentsAsUint8Array,
}
];
```
## Units value
Some fields in the PSD document specity a value with units, those fields use `UnitsValue` type:
```ts
interface UnitsValue {
units: Units;
value: number;
}
```
`value` fields can be any number value, `units` fields has to be one of the supported units: "Pixels", "Points", "Picas", "Millimeters", "Centimeters", "Inches", "None", "Density". Some fields only support some of the units, check with Photoshop for supported units.
Example values:
```ts
var distance = { value: 5, units: "Pixels" };
var lineWidth = { value: 3, units: "Points" };
```
## Colors
Many fields in PSD file support passing color in different color formats (RGBA, RGB, HSB, CMYK, LAB, Grayscale) Those fields will use `Color` type which is a union of all of these color formats. The color types have following structure:
```ts
type RGBA = { r: number; g: number; b: number; a: number; }; // values from 0 to 255
type RGB = { r: number; g: number; b: number; }; // values from 0 to 255
type FRGB = { fr: number; fg: number; fb: number; }; // values from 0 to 1 (can be above 1)
type HSB = { h: number; s: number; b: number; }; // values from 0 to 1
type CMYK = { c: number; m: number; y: number; k: number; }; // values from 0 to 255
type LAB = { l: number; a: number; b: number; }; // values `l` from 0 to 1; `a` and `b` from -1 to 1
type Grayscale = { k: number }; // values from 0 to 255
type Color = RGBA | RGB | FRGB | HSB | CMYK | LAB | Grayscale;
```
When you want to set field with a `Color` type, it's pretty straightforward, you can just choose any of the formats you like and set it on the field:
```ts
strokeEffect.color = { h: 0.79, s: 0.54, b: 0.93 };
```
Reading a color field is more complicated, you need to check what color format the field is in and then run correct code to handle it, here's how to do it for all color types:
```ts
if ('l' in color) {
// color is LAB
} else if ('c' in color) {
// color is CMYK
} else if ('h' in color) {
// color is HSB
} else if ('k' in color) {
// color is Grayscale
} else if ('a' in color) {
// color is RGBA
} else if ('rf' in color) {
// color is FRGB
} else {
// color is RGB
}
```
If you expect the fields to be in one specific format you can just verity that it's correct and throw an error if it's a format that you didn't expect:
```ts
// handle only RGB colors
if ('r' in color && !('a' in color)) {
// color is RGB
} else {
throw new Error('Invalid color');
}
```

View File

@ -0,0 +1,9 @@
- can we remove sectionDivider property ?
- can we remove nameSource property ?
- improve vector fill / stroke help sections
check: https://github.com/TheNicker/libpsd
- zip with prediction: https://github.com/TheNicker/libpsd/blob/master/src/psd_zip.c
- also support saving with zip compression ?

View File

@ -0,0 +1,3 @@
const fs = require('fs');
fs.rmSync('dist', { recursive: true, force: true });
fs.rmSync('dist-es', { recursive: true, force: true });

View File

@ -0,0 +1,132 @@
import { BlendMode, PatternInfo } from './psd';
export interface Abr {
brushes: Brush[];
samples: SampleInfo[];
patterns: PatternInfo[];
}
export interface SampleInfo {
id: string;
bounds: {
x: number;
y: number;
w: number;
h: number;
};
alpha: Uint8Array;
}
export interface BrushDynamics {
control: 'off' | 'fade' | 'pen pressure' | 'pen tilt' | 'stylus wheel' | 'initial direction' | 'direction' | 'initial rotation' | 'rotation';
steps: number;
jitter: number;
minimum: number;
}
export interface BrushShape {
name?: string;
size: number;
angle: number;
roundness: number;
hardness?: number;
spacingOn: boolean;
spacing: number;
flipX: boolean;
flipY: boolean;
sampledData?: string;
}
export interface Brush {
name: string;
shape: BrushShape;
shapeDynamics?: {
sizeDynamics: BrushDynamics;
minimumDiameter: number;
tiltScale: number;
angleDynamics: BrushDynamics;
roundnessDynamics: BrushDynamics;
minimumRoundness: number;
flipX: boolean;
flipY: boolean;
brushProjection: boolean;
};
scatter?: {
bothAxes: boolean;
scatterDynamics: BrushDynamics;
countDynamics: BrushDynamics;
count: number;
};
texture?: {
id: string;
name: string;
invert: boolean;
scale: number;
brightness: number;
contrast: number;
blendMode: BlendMode;
depth: number;
depthMinimum: number;
depthDynamics: BrushDynamics;
};
dualBrush?: {
flip: boolean;
shape: BrushShape;
blendMode: BlendMode;
useScatter: boolean;
spacing: number;
count: number;
bothAxes: boolean;
countDynamics: BrushDynamics;
scatterDynamics: BrushDynamics;
};
colorDynamics?: {
foregroundBackground: BrushDynamics;
hue: number;
saturation: number;
brightness: number;
purity: number;
perTip: boolean;
};
transfer?: {
flowDynamics: BrushDynamics;
opacityDynamics: BrushDynamics;
wetnessDynamics: BrushDynamics;
mixDynamics: BrushDynamics;
};
brushPose?: {
overrideAngle: boolean;
overrideTiltX: boolean;
overrideTiltY: boolean;
overridePressure: boolean;
pressure: number;
tiltX: number;
tiltY: number;
angle: number;
};
noise: boolean;
wetEdges: boolean;
protectTexture?: boolean;
spacing: number;
brushGroup?: undefined;
interpretation?: boolean;
useBrushSize: boolean;
toolOptions?: {
brushPreset: boolean;
flow: number;
smooth: number;
mode: BlendMode;
opacity: number;
smoothing: boolean;
smoothingValue: number;
smoothingRadiusMode: boolean;
smoothingCatchup: boolean;
smoothingCatchupAtEnd: boolean;
smoothingZoomCompensation: boolean;
pressureSmoothing: boolean;
usePressureOverridesSize: boolean;
usePressureOverridesOpacity: boolean;
useLegacy: boolean;
flowDynamics?: BrushDynamics;
opacityDynamics?: BrushDynamics;
sizeDynamics?: BrushDynamics;
};
}
export declare function readAbr(buffer: ArrayBufferView, options?: {
logMissingFeatures?: boolean;
}): Abr;

View File

@ -0,0 +1,266 @@
import { BlnM, parseAngle, parsePercent, parseUnitsToNumber, readVersionAndDescriptor } from './descriptor';
import { checkSignature, createReader, readBytes, readDataRLE, readInt16, readInt32, readPascalString, readPattern, readSignature, readUint16, readUint32, readUint8, skipBytes } from './psdReader';
var dynamicsControl = ['off', 'fade', 'pen pressure', 'pen tilt', 'stylus wheel', 'initial direction', 'direction', 'initial rotation', 'rotation'];
function parseDynamics(desc) {
return {
control: dynamicsControl[desc.bVTy],
steps: desc.fStp,
jitter: parsePercent(desc.jitter),
minimum: parsePercent(desc['Mnm ']),
};
}
function parseBrushShape(desc) {
var shape = {
size: parseUnitsToNumber(desc.Dmtr, 'Pixels'),
angle: parseAngle(desc.Angl),
roundness: parsePercent(desc.Rndn),
spacingOn: desc.Intr,
spacing: parsePercent(desc.Spcn),
flipX: desc.flipX,
flipY: desc.flipY,
};
if (desc['Nm '])
shape.name = desc['Nm '];
if (desc.Hrdn)
shape.hardness = parsePercent(desc.Hrdn);
if (desc.sampledData)
shape.sampledData = desc.sampledData;
return shape;
}
export function readAbr(buffer, options) {
var _a, _b, _c, _d;
if (options === void 0) { options = {}; }
var reader = createReader(buffer.buffer, buffer.byteOffset, buffer.byteLength);
var version = readInt16(reader);
var samples = [];
var brushes = [];
var patterns = [];
if (version === 1 || version === 2) {
throw new Error("Unsupported ABR version (".concat(version, ")")); // TODO: ...
}
else if (version === 6 || version === 7 || version === 9 || version === 10) {
var minorVersion = readInt16(reader);
if (minorVersion !== 1 && minorVersion !== 2)
throw new Error('Unsupported ABR minor version');
while (reader.offset < reader.view.byteLength) {
checkSignature(reader, '8BIM');
var type = readSignature(reader);
var size = readUint32(reader);
var end = reader.offset + size;
switch (type) {
case 'samp': {
while (reader.offset < end) {
var brushLength = readUint32(reader);
while (brushLength & 3)
brushLength++; // pad to 4 byte alignment
var brushEnd = reader.offset + brushLength;
var id = readPascalString(reader, 1);
// v1 - Skip the Int16 bounds rectangle and the unknown Int16.
// v2 - Skip the unknown bytes.
skipBytes(reader, minorVersion === 1 ? 10 : 264);
var y = readInt32(reader);
var x = readInt32(reader);
var h = readInt32(reader) - y;
var w = readInt32(reader) - x;
if (w <= 0 || h <= 0)
throw new Error('Invalid bounds');
var depth = readInt16(reader);
var compression = readUint8(reader); // 0 - raw, 1 - RLE
var alpha = new Uint8Array(w * h);
if (depth === 8) {
if (compression === 0) {
alpha.set(readBytes(reader, alpha.byteLength));
}
else if (compression === 1) {
readDataRLE(reader, { width: w, height: h, data: alpha }, w, h, 1, [0], false);
}
else {
throw new Error('Invalid compression');
}
}
else if (depth === 16) {
if (compression === 0) {
for (var i = 0; i < alpha.byteLength; i++) {
alpha[i] = readUint16(reader) >> 8; // convert to 8bit values
}
}
else if (compression === 1) {
throw new Error('not implemented (16bit RLE)'); // TODO: ...
}
else {
throw new Error('Invalid compression');
}
}
else {
throw new Error('Invalid depth');
}
samples.push({ id: id, bounds: { x: x, y: y, w: w, h: h }, alpha: alpha });
reader.offset = brushEnd;
}
break;
}
case 'desc': {
var desc = readVersionAndDescriptor(reader);
// console.log(require('util').inspect(desc, false, 99, true));
for (var _i = 0, _e = desc.Brsh; _i < _e.length; _i++) {
var brush = _e[_i];
var b = {
name: brush['Nm '],
shape: parseBrushShape(brush.Brsh),
spacing: parsePercent(brush.Spcn),
// TODO: brushGroup ???
wetEdges: brush.Wtdg,
noise: brush.Nose,
// TODO: TxtC ??? smoothing / build-up ?
// TODO: 'Rpt ' ???
useBrushSize: brush.useBrushSize, // ???
};
if (brush.interpretation != null)
b.interpretation = brush.interpretation;
if (brush.protectTexture != null)
b.protectTexture = brush.protectTexture;
if (brush.useTipDynamics) {
b.shapeDynamics = {
tiltScale: parsePercent(brush.tiltScale),
sizeDynamics: parseDynamics(brush.szVr),
angleDynamics: parseDynamics(brush.angleDynamics),
roundnessDynamics: parseDynamics(brush.roundnessDynamics),
flipX: brush.flipX,
flipY: brush.flipY,
brushProjection: brush.brushProjection,
minimumDiameter: parsePercent(brush.minimumDiameter),
minimumRoundness: parsePercent(brush.minimumRoundness),
};
}
if (brush.useScatter) {
b.scatter = {
count: brush['Cnt '],
bothAxes: brush.bothAxes,
countDynamics: parseDynamics(brush.countDynamics),
scatterDynamics: parseDynamics(brush.scatterDynamics),
};
}
if (brush.useTexture && brush.Txtr) {
b.texture = {
id: brush.Txtr.Idnt,
name: brush.Txtr['Nm '],
blendMode: BlnM.decode(brush.textureBlendMode),
depth: parsePercent(brush.textureDepth),
depthMinimum: parsePercent(brush.minimumDepth),
depthDynamics: parseDynamics(brush.textureDepthDynamics),
scale: parsePercent(brush.textureScale),
invert: brush.InvT,
brightness: brush.textureBrightness,
contrast: brush.textureContrast,
};
}
var db = brush.dualBrush;
if (db && db.useDualBrush) {
b.dualBrush = {
flip: db.Flip,
shape: parseBrushShape(db.Brsh),
blendMode: BlnM.decode(db.BlnM),
useScatter: db.useScatter,
spacing: parsePercent(db.Spcn),
count: db['Cnt '],
bothAxes: db.bothAxes,
countDynamics: parseDynamics(db.countDynamics),
scatterDynamics: parseDynamics(db.scatterDynamics),
};
}
if (brush.useColorDynamics) {
b.colorDynamics = {
foregroundBackground: parseDynamics(brush.clVr),
hue: parsePercent(brush['H ']),
saturation: parsePercent(brush.Strt),
brightness: parsePercent(brush.Brgh),
purity: parsePercent(brush.purity),
perTip: brush.colorDynamicsPerTip,
};
}
if (brush.usePaintDynamics) {
b.transfer = {
flowDynamics: parseDynamics(brush.prVr),
opacityDynamics: parseDynamics(brush.opVr),
wetnessDynamics: parseDynamics(brush.wtVr),
mixDynamics: parseDynamics(brush.mxVr),
};
}
if (brush.useBrushPose) {
b.brushPose = {
overrideAngle: brush.overridePoseAngle,
overrideTiltX: brush.overridePoseTiltX,
overrideTiltY: brush.overridePoseTiltY,
overridePressure: brush.overridePosePressure,
pressure: parsePercent(brush.brushPosePressure),
tiltX: brush.brushPoseTiltX,
tiltY: brush.brushPoseTiltY,
angle: brush.brushPoseAngle,
};
}
var to = brush.toolOptions;
if (to) {
b.toolOptions = {
brushPreset: to.brushPreset,
flow: (_a = to.flow) !== null && _a !== void 0 ? _a : 100,
smooth: (_b = to.Smoo) !== null && _b !== void 0 ? _b : 0,
mode: BlnM.decode(to['Md '] || 'BlnM.Nrml'),
opacity: (_c = to.Opct) !== null && _c !== void 0 ? _c : 100,
smoothing: !!to.smoothing,
smoothingValue: to.smoothingValue || 0,
smoothingRadiusMode: !!to.smoothingRadiusMode,
smoothingCatchup: !!to.smoothingCatchup,
smoothingCatchupAtEnd: !!to.smoothingCatchupAtEnd,
smoothingZoomCompensation: !!to.smoothingZoomCompensation,
pressureSmoothing: !!to.pressureSmoothing,
usePressureOverridesSize: !!to.usePressureOverridesSize,
usePressureOverridesOpacity: !!to.usePressureOverridesOpacity,
useLegacy: !!to.useLegacy,
};
if (to.prVr) {
b.toolOptions.flowDynamics = parseDynamics(to.prVr);
}
if (to.opVr) {
b.toolOptions.opacityDynamics = parseDynamics(to.opVr);
}
if (to.szVr) {
b.toolOptions.sizeDynamics = parseDynamics(to.szVr);
}
}
brushes.push(b);
}
break;
}
case 'patt': {
if (reader.offset < end) { // TODO: check multiple patterns
patterns.push(readPattern(reader));
reader.offset = end;
}
break;
}
case 'phry': {
// TODO: what is this ?
var desc = readVersionAndDescriptor(reader);
if (options.logMissingFeatures) {
if ((_d = desc.hierarchy) === null || _d === void 0 ? void 0 : _d.length) {
console.log('unhandled phry section', desc);
}
}
break;
}
default:
throw new Error("Invalid brush type: ".concat(type));
}
// align to 4 bytes
while (size % 4) {
reader.offset++;
size++;
}
}
}
else {
throw new Error("Unsupported ABR version (".concat(version, ")"));
}
return { samples: samples, patterns: patterns, brushes: brushes };
}
//# sourceMappingURL=abr.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,25 @@
import { LayerAdditionalInfo, BezierPath, Psd, ReadOptions, WriteOptions, BooleanOperation, LayerEffectsInfo, LayerVectorMask } from './psd';
import { PsdReader } from './psdReader';
import { PsdWriter } from './psdWriter';
export interface ExtendedWriteOptions extends WriteOptions {
layerIds: Set<number>;
layerToId: Map<any, number>;
}
type HasMethod = (target: LayerAdditionalInfo) => boolean;
type ReadMethod = (reader: PsdReader, target: LayerAdditionalInfo, left: () => number, psd: Psd, options: ReadOptions) => void;
type WriteMethod = (writer: PsdWriter, target: LayerAdditionalInfo, psd: Psd, options: ExtendedWriteOptions) => void;
export interface InfoHandler {
key: string;
has: HasMethod;
read: ReadMethod;
write: WriteMethod;
}
export declare const infoHandlers: InfoHandler[];
export declare const infoHandlersMap: {
[key: string]: InfoHandler;
};
export declare function readBezierKnot(reader: PsdReader, width: number, height: number): number[];
export declare const booleanOperations: BooleanOperation[];
export declare function readVectorMask(reader: PsdReader, vectorMask: LayerVectorMask, width: number, height: number, size: number): BezierPath[];
export declare function hasMultiEffects(effects: LayerEffectsInfo): boolean;
export {};

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,10 @@
import { LayerVectorMask } from './psd';
export interface Csh {
shapes: (LayerVectorMask & {
name: string;
id: string;
width: number;
height: number;
})[];
}
export declare function readCsh(buffer: ArrayBufferView): Csh;

View File

@ -0,0 +1,44 @@
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
import { readVectorMask } from './additionalInfo';
import { readUint32, checkSignature, createReader, readPascalString, readUnicodeString } from './psdReader';
export function readCsh(buffer) {
var reader = createReader(buffer.buffer, buffer.byteOffset, buffer.byteLength);
var csh = { shapes: [] };
checkSignature(reader, 'cush');
if (readUint32(reader) !== 2)
throw new Error('Invalid version');
var count = readUint32(reader);
for (var i = 0; i < count; i++) {
var name_1 = readUnicodeString(reader);
while (reader.offset % 4)
reader.offset++; // pad to 4byte bounds
if (readUint32(reader) !== 1)
throw new Error('Invalid shape version');
var size = readUint32(reader);
var end = reader.offset + size;
var id = readPascalString(reader, 1);
// this might not be correct ???
var y1 = readUint32(reader);
var x1 = readUint32(reader);
var y2 = readUint32(reader);
var x2 = readUint32(reader);
var width = x2 - x1;
var height = y2 - y1;
var mask = { paths: [] };
readVectorMask(reader, mask, width, height, end - reader.offset);
csh.shapes.push(__assign({ name: name_1, id: id, width: width, height: height }, mask));
reader.offset = end;
}
return csh;
}
//# sourceMappingURL=csh.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"csh.js","sourceRoot":"../src/","sources":["csh.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAElD,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,YAAY,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAW5G,MAAM,UAAU,OAAO,CAAC,MAAuB;IAC9C,IAAM,MAAM,GAAG,YAAY,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,UAAU,EAAE,MAAM,CAAC,UAAU,CAAC,CAAC;IACjF,IAAM,GAAG,GAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC;IAEhC,cAAc,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC/B,IAAI,UAAU,CAAC,MAAM,CAAC,KAAK,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAC;IACjE,IAAM,KAAK,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC;IAEjC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,EAAE,CAAC,EAAE,EAAE;QAC/B,IAAM,MAAI,GAAG,iBAAiB,CAAC,MAAM,CAAC,CAAC;QACvC,OAAO,MAAM,CAAC,MAAM,GAAG,CAAC;YAAE,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,sBAAsB;QACjE,IAAI,UAAU,CAAC,MAAM,CAAC,KAAK,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,uBAAuB,CAAC,CAAC;QACvE,IAAM,IAAI,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC;QAChC,IAAM,GAAG,GAAG,MAAM,CAAC,MAAM,GAAG,IAAI,CAAC;QACjC,IAAM,EAAE,GAAG,gBAAgB,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;QACvC,gCAAgC;QAChC,IAAM,EAAE,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC;QAC9B,IAAM,EAAE,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC;QAC9B,IAAM,EAAE,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC;QAC9B,IAAM,EAAE,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC;QAC9B,IAAM,KAAK,GAAG,EAAE,GAAG,EAAE,CAAC;QACtB,IAAM,MAAM,GAAG,EAAE,GAAG,EAAE,CAAC;QACvB,IAAM,IAAI,GAAoB,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC;QAC5C,cAAc,CAAC,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC;QACjE,GAAG,CAAC,MAAM,CAAC,IAAI,YAAG,IAAI,QAAA,EAAE,EAAE,IAAA,EAAE,KAAK,OAAA,EAAE,MAAM,QAAA,IAAK,IAAI,EAAG,CAAC;QAEtD,MAAM,CAAC,MAAM,GAAG,GAAG,CAAC;KACpB;IAED,OAAO,GAAG,CAAC;AACZ,CAAC"}

View File

@ -0,0 +1,415 @@
import { AntiAlias, BevelDirection, BevelStyle, BevelTechnique, BlendMode, Color, GlowSource, GlowTechnique, GradientStyle, InterpolationMethod, LayerEffectsInfo, LineAlignment, LineCapType, LineJoinType, Orientation, TextGridding, TimelineKeyInterpolation, TimelineTrack, TimelineTrackType, Units, UnitsValue, VectorContent, WarpStyle } from './psd';
import { PsdReader } from './psdReader';
import { PsdWriter } from './psdWriter';
export declare function setLogErrors(value: boolean): void;
export declare function readAsciiStringOrClassId(reader: PsdReader): string;
export declare function readDescriptorStructure(reader: PsdReader): any;
export declare function writeDescriptorStructure(writer: PsdWriter, name: string, classId: string, value: any, root: string): void;
export declare function readVersionAndDescriptor(reader: PsdReader): any;
export declare function writeVersionAndDescriptor(writer: PsdWriter, name: string, classID: string, descriptor: any, root?: string): void;
export type DescriptorUnits = 'Angle' | 'Density' | 'Distance' | 'None' | 'Percent' | 'Pixels' | 'Millimeters' | 'Points' | 'Picas' | 'Inches' | 'Centimeters';
export interface DescriptorUnitsValue {
units: DescriptorUnits;
value: number;
}
export type DescriptorColor = {
'Rd ': number;
'Grn ': number;
'Bl ': number;
} | {
'H ': DescriptorUnitsValue;
Strt: number;
Brgh: number;
} | {
'Cyn ': number;
Mgnt: number;
'Ylw ': number;
Blck: number;
} | {
'Gry ': number;
} | {
Lmnc: number;
'A ': number;
'B ': number;
} | {
redFloat: number;
greenFloat: number;
blueFloat: number;
};
export interface DesciptorPattern {
'Nm ': string;
Idnt: string;
}
export type DesciptorGradient = {
'Nm ': string;
GrdF: 'GrdF.CstS';
Intr: number;
Clrs: {
'Clr ': DescriptorColor;
Type: 'Clry.UsrS';
Lctn: number;
Mdpn: number;
}[];
Trns: {
Opct: DescriptorUnitsValue;
Lctn: number;
Mdpn: number;
}[];
} | {
GrdF: 'GrdF.ClNs';
Smth: number;
'Nm ': string;
ClrS: string;
RndS: number;
VctC?: boolean;
ShTr?: boolean;
'Mnm ': number[];
'Mxm ': number[];
};
export interface DescriptorColorContent {
'Clr ': DescriptorColor;
}
export interface DescriptorGradientContent {
Grad: DesciptorGradient;
Type: string;
Dthr?: boolean;
Rvrs?: boolean;
Angl?: DescriptorUnitsValue;
'Scl '?: DescriptorUnitsValue;
Algn?: boolean;
Ofst?: {
Hrzn: DescriptorUnitsValue;
Vrtc: DescriptorUnitsValue;
};
}
export interface DescriptorPatternContent {
Ptrn: DesciptorPattern;
Lnkd?: boolean;
phase?: {
Hrzn: number;
Vrtc: number;
};
}
export type DescriptorVectorContent = DescriptorColorContent | DescriptorGradientContent | DescriptorPatternContent;
export interface StrokeDescriptor {
strokeStyleVersion: number;
strokeEnabled: boolean;
fillEnabled: boolean;
strokeStyleLineWidth: DescriptorUnitsValue;
strokeStyleLineDashOffset: DescriptorUnitsValue;
strokeStyleMiterLimit: number;
strokeStyleLineCapType: string;
strokeStyleLineJoinType: string;
strokeStyleLineAlignment: string;
strokeStyleScaleLock: boolean;
strokeStyleStrokeAdjust: boolean;
strokeStyleLineDashSet: DescriptorUnitsValue[];
strokeStyleBlendMode: string;
strokeStyleOpacity: DescriptorUnitsValue;
strokeStyleContent: DescriptorVectorContent;
strokeStyleResolution: number;
}
export interface TextDescriptor {
'Txt ': string;
textGridding: string;
Ornt: string;
AntA: string;
TextIndex: number;
EngineData?: Uint8Array;
}
export interface WarpDescriptor {
warpStyle: string;
warpValue?: number;
warpValues?: number[];
warpPerspective: number;
warpPerspectiveOther: number;
warpRotate: string;
bounds?: {
'Top ': DescriptorUnitsValue;
Left: DescriptorUnitsValue;
Btom: DescriptorUnitsValue;
Rght: DescriptorUnitsValue;
};
uOrder: number;
vOrder: number;
customEnvelopeWarp?: {
meshPoints: {
type: 'Hrzn' | 'Vrtc';
values: number[];
}[];
};
}
export interface QuiltWarpDescriptor extends WarpDescriptor {
deformNumRows: number;
deformNumCols: number;
customEnvelopeWarp: {
quiltSliceX: {
type: 'quiltSliceX';
values: number[];
}[];
quiltSliceY: {
type: 'quiltSliceY';
values: number[];
}[];
meshPoints: {
type: 'Hrzn' | 'Vrtc';
values: number[];
}[];
};
}
export interface FractionDescriptor {
numerator: number;
denominator: number;
}
export interface HrznVrtcDescriptor {
Hrzn: number;
Vrtc: number;
}
export interface FrameDescriptor {
FrLs: number[];
enab?: boolean;
IMsk?: {
Ofst: HrznVrtcDescriptor;
};
VMsk?: {
Ofst: HrznVrtcDescriptor;
};
Ofst?: HrznVrtcDescriptor;
FXRf?: HrznVrtcDescriptor;
Lefx?: Lfx2Descriptor;
blendOptions?: {
Opct: DescriptorUnitsValue;
};
}
export interface FrameListDescriptor {
LaID: number;
LaSt: FrameDescriptor[];
}
export declare function horzVrtcToXY(hv: HrznVrtcDescriptor): {
x: number;
y: number;
};
export declare function xyToHorzVrtc(xy: {
x: number;
y: number;
}): HrznVrtcDescriptor;
export type TimelineAnimKeyDescriptor = {
Type: 'keyType.Opct';
Opct: DescriptorUnitsValue;
} | {
Type: 'keyType.Trnf';
'Scl ': HrznVrtcDescriptor;
Skew: HrznVrtcDescriptor;
rotation: number;
translation: HrznVrtcDescriptor;
} | {
Type: 'keyType.Pstn';
Hrzn: number;
Vrtc: number;
} | {
Type: 'keyType.sheetStyle';
sheetStyle: {
Vrsn: number;
Lefx?: Lfx2Descriptor;
blendOptions: {};
};
} | {
Type: 'keyType.globalLighting';
gblA: number;
globalAltitude: number;
};
export interface TimelineKeyDescriptor {
Vrsn: 1;
animInterpStyle: 'animInterpStyle.Lnr ' | 'animInterpStyle.hold';
time: FractionDescriptor;
animKey: TimelineAnimKeyDescriptor;
selected: boolean;
}
export interface TimelineTrackDescriptor {
trackID: 'stdTrackID.globalLightingTrack' | 'stdTrackID.opacityTrack' | 'stdTrackID.styleTrack' | 'stdTrackID.sheetTransformTrack' | 'stdTrackID.sheetPositionTrack';
Vrsn: 1;
enab: boolean;
Effc: boolean;
effectParams?: {
keyList: TimelineKeyDescriptor[];
fillCanvas: boolean;
zoomOrigin: number;
};
keyList: TimelineKeyDescriptor[];
}
export interface TimeScopeDescriptor {
Vrsn: 1;
Strt: FractionDescriptor;
duration: FractionDescriptor;
inTime: FractionDescriptor;
outTime: FractionDescriptor;
}
export interface TimelineDescriptor {
Vrsn: 1;
timeScope: TimeScopeDescriptor;
autoScope: boolean;
audioLevel: number;
LyrI: number;
trackList?: TimelineTrackDescriptor[];
}
export interface EffectDescriptor extends Partial<DescriptorGradientContent>, Partial<DescriptorPatternContent> {
enab?: boolean;
Styl: string;
PntT?: string;
'Md '?: string;
Opct?: DescriptorUnitsValue;
'Sz '?: DescriptorUnitsValue;
'Clr '?: DescriptorColor;
present?: boolean;
showInDialog?: boolean;
overprint?: boolean;
}
export interface Lfx2Descriptor {
'Scl '?: DescriptorUnitsValue;
masterFXSwitch?: boolean;
DrSh?: EffectDescriptor;
IrSh?: EffectDescriptor;
OrGl?: EffectDescriptor;
IrGl?: EffectDescriptor;
ebbl?: EffectDescriptor;
SoFi?: EffectDescriptor;
patternFill?: EffectDescriptor;
GrFl?: EffectDescriptor;
ChFX?: EffectDescriptor;
FrFX?: EffectDescriptor;
}
export interface LmfxDescriptor {
'Scl '?: DescriptorUnitsValue;
masterFXSwitch?: boolean;
numModifyingFX?: number;
OrGl?: EffectDescriptor;
IrGl?: EffectDescriptor;
ebbl?: EffectDescriptor;
ChFX?: EffectDescriptor;
dropShadowMulti?: EffectDescriptor[];
innerShadowMulti?: EffectDescriptor[];
solidFillMulti?: EffectDescriptor[];
gradientFillMulti?: EffectDescriptor[];
frameFXMulti?: EffectDescriptor[];
patternFill?: EffectDescriptor;
}
export declare function serializeEffects(e: LayerEffectsInfo, log: boolean, multi: boolean): Lfx2Descriptor & LmfxDescriptor;
export declare function parseEffects(info: Lfx2Descriptor & LmfxDescriptor, log: boolean): LayerEffectsInfo;
export declare function parseTrackList(trackList: TimelineTrackDescriptor[], logMissingFeatures: boolean): TimelineTrack[];
export declare function serializeTrackList(tracks: TimelineTrack[]): TimelineTrackDescriptor[];
export declare function parseVectorContent(descriptor: DescriptorVectorContent): VectorContent;
export declare function serializeVectorContent(content: VectorContent): {
descriptor: DescriptorVectorContent;
key: string;
};
export declare function parseColor(color: DescriptorColor): Color;
export declare function serializeColor(color: Color | undefined): DescriptorColor;
export declare function parseAngle(x: DescriptorUnitsValue): number;
export declare function parsePercent(x: DescriptorUnitsValue | undefined): number;
export declare function parsePercentOrAngle(x: DescriptorUnitsValue | undefined): number;
export declare function parseUnits({ units, value }: DescriptorUnitsValue): UnitsValue;
export declare function parseUnitsOrNumber(value: DescriptorUnitsValue | number, units?: Units): UnitsValue;
export declare function parseUnitsToNumber({ units, value }: DescriptorUnitsValue, expectedUnits: string): number;
export declare function unitsAngle(value: number | undefined): DescriptorUnitsValue;
export declare function unitsPercent(value: number | undefined): DescriptorUnitsValue;
export declare function unitsValue(x: UnitsValue | undefined, key: string): DescriptorUnitsValue;
export declare const textGridding: {
decode: (val: string) => TextGridding;
encode: (val: TextGridding | undefined) => string;
};
export declare const Ornt: {
decode: (val: string) => Orientation;
encode: (val: Orientation | undefined) => string;
};
export declare const Annt: {
decode: (val: string) => AntiAlias;
encode: (val: AntiAlias | undefined) => string;
};
export declare const warpStyle: {
decode: (val: string) => WarpStyle;
encode: (val: WarpStyle | undefined) => string;
};
export declare const BlnM: {
decode: (val: string) => BlendMode;
encode: (val: BlendMode | undefined) => string;
};
export declare const BESl: {
decode: (val: string) => BevelStyle;
encode: (val: BevelStyle | undefined) => string;
};
export declare const bvlT: {
decode: (val: string) => BevelTechnique;
encode: (val: BevelTechnique | undefined) => string;
};
export declare const BESs: {
decode: (val: string) => BevelDirection;
encode: (val: BevelDirection | undefined) => string;
};
export declare const BETE: {
decode: (val: string) => GlowTechnique;
encode: (val: GlowTechnique | undefined) => string;
};
export declare const IGSr: {
decode: (val: string) => GlowSource;
encode: (val: GlowSource | undefined) => string;
};
export declare const GrdT: {
decode: (val: string) => GradientStyle;
encode: (val: GradientStyle | undefined) => string;
};
export declare const animInterpStyleEnum: {
decode: (val: string) => TimelineKeyInterpolation;
encode: (val: TimelineKeyInterpolation | undefined) => string;
};
export declare const stdTrackID: {
decode: (val: string) => TimelineTrackType;
encode: (val: TimelineTrackType | undefined) => string;
};
export declare const gradientInterpolationMethodType: {
decode: (val: string) => InterpolationMethod;
encode: (val: InterpolationMethod | undefined) => string;
};
export declare const ClrS: {
decode: (val: string) => "rgb" | "hsb" | "lab";
encode: (val: "rgb" | "hsb" | "lab" | undefined) => string;
};
export declare const FStl: {
decode: (val: string) => "center" | "inside" | "outside";
encode: (val: "center" | "inside" | "outside" | undefined) => string;
};
export declare const FrFl: {
decode: (val: string) => "color" | "pattern" | "gradient";
encode: (val: "color" | "pattern" | "gradient" | undefined) => string;
};
export declare const ESliceType: {
decode: (val: string) => "image" | "noImage";
encode: (val: "image" | "noImage" | undefined) => string;
};
export declare const ESliceHorzAlign: {
decode: (val: string) => "default";
encode: (val: "default" | undefined) => string;
};
export declare const ESliceVertAlign: {
decode: (val: string) => "default";
encode: (val: "default" | undefined) => string;
};
export declare const ESliceOrigin: {
decode: (val: string) => "userGenerated" | "autoGenerated" | "layer";
encode: (val: "userGenerated" | "autoGenerated" | "layer" | undefined) => string;
};
export declare const ESliceBGColorType: {
decode: (val: string) => "none" | "color" | "matte";
encode: (val: "none" | "color" | "matte" | undefined) => string;
};
export declare const strokeStyleLineCapType: {
decode: (val: string) => LineCapType;
encode: (val: LineCapType | undefined) => string;
};
export declare const strokeStyleLineJoinType: {
decode: (val: string) => LineJoinType;
encode: (val: LineJoinType | undefined) => string;
};
export declare const strokeStyleLineAlignment: {
decode: (val: string) => LineAlignment;
encode: (val: LineAlignment | undefined) => string;
};

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,5 @@
import { LayerEffectsInfo } from './psd';
import { PsdReader } from './psdReader';
import { PsdWriter } from './psdWriter';
export declare function readEffects(reader: PsdReader): LayerEffectsInfo;
export declare function writeEffects(writer: PsdWriter, effects: LayerEffectsInfo): void;

View File

@ -0,0 +1,304 @@
import { toBlendMode, fromBlendMode } from './helpers';
import { checkSignature, readSignature, skipBytes, readUint16, readUint8, readUint32, readFixedPoint32, readColor } from './psdReader';
import { writeSignature, writeUint16, writeZeros, writeFixedPoint32, writeUint8, writeUint32, writeColor } from './psdWriter';
var bevelStyles = [
undefined, 'outer bevel', 'inner bevel', 'emboss', 'pillow emboss', 'stroke emboss'
];
function readBlendMode(reader) {
checkSignature(reader, '8BIM');
return toBlendMode[readSignature(reader)] || 'normal';
}
function writeBlendMode(writer, mode) {
writeSignature(writer, '8BIM');
writeSignature(writer, fromBlendMode[mode] || 'norm');
}
function readFixedPoint8(reader) {
return readUint8(reader) / 0xff;
}
function writeFixedPoint8(writer, value) {
writeUint8(writer, Math.round(value * 0xff) | 0);
}
export function readEffects(reader) {
var version = readUint16(reader);
if (version !== 0)
throw new Error("Invalid effects layer version: ".concat(version));
var effectsCount = readUint16(reader);
var effects = {};
for (var i = 0; i < effectsCount; i++) {
checkSignature(reader, '8BIM');
var type = readSignature(reader);
switch (type) {
case 'cmnS': { // common state (see See Effects layer, common state info)
var size = readUint32(reader);
var version_1 = readUint32(reader);
var visible = !!readUint8(reader);
skipBytes(reader, 2);
if (size !== 7 || version_1 !== 0 || !visible)
throw new Error("Invalid effects common state");
break;
}
case 'dsdw': // drop shadow (see See Effects layer, drop shadow and inner shadow info)
case 'isdw': { // inner shadow (see See Effects layer, drop shadow and inner shadow info)
var blockSize = readUint32(reader);
var version_2 = readUint32(reader);
if (blockSize !== 41 && blockSize !== 51)
throw new Error("Invalid shadow size: ".concat(blockSize));
if (version_2 !== 0 && version_2 !== 2)
throw new Error("Invalid shadow version: ".concat(version_2));
var size = readFixedPoint32(reader);
readFixedPoint32(reader); // intensity
var angle = readFixedPoint32(reader);
var distance = readFixedPoint32(reader);
var color = readColor(reader);
var blendMode = readBlendMode(reader);
var enabled = !!readUint8(reader);
var useGlobalLight = !!readUint8(reader);
var opacity = readFixedPoint8(reader);
if (blockSize >= 51)
readColor(reader); // native color
var shadowInfo = {
size: { units: 'Pixels', value: size },
distance: { units: 'Pixels', value: distance },
angle: angle,
color: color,
blendMode: blendMode,
enabled: enabled,
useGlobalLight: useGlobalLight,
opacity: opacity
};
if (type === 'dsdw') {
effects.dropShadow = [shadowInfo];
}
else {
effects.innerShadow = [shadowInfo];
}
break;
}
case 'oglw': { // outer glow (see See Effects layer, outer glow info)
var blockSize = readUint32(reader);
var version_3 = readUint32(reader);
if (blockSize !== 32 && blockSize !== 42)
throw new Error("Invalid outer glow size: ".concat(blockSize));
if (version_3 !== 0 && version_3 !== 2)
throw new Error("Invalid outer glow version: ".concat(version_3));
var size = readFixedPoint32(reader);
readFixedPoint32(reader); // intensity
var color = readColor(reader);
var blendMode = readBlendMode(reader);
var enabled = !!readUint8(reader);
var opacity = readFixedPoint8(reader);
if (blockSize >= 42)
readColor(reader); // native color
effects.outerGlow = {
size: { units: 'Pixels', value: size },
color: color,
blendMode: blendMode,
enabled: enabled,
opacity: opacity
};
break;
}
case 'iglw': { // inner glow (see See Effects layer, inner glow info)
var blockSize = readUint32(reader);
var version_4 = readUint32(reader);
if (blockSize !== 32 && blockSize !== 43)
throw new Error("Invalid inner glow size: ".concat(blockSize));
if (version_4 !== 0 && version_4 !== 2)
throw new Error("Invalid inner glow version: ".concat(version_4));
var size = readFixedPoint32(reader);
readFixedPoint32(reader); // intensity
var color = readColor(reader);
var blendMode = readBlendMode(reader);
var enabled = !!readUint8(reader);
var opacity = readFixedPoint8(reader);
if (blockSize >= 43) {
readUint8(reader); // inverted
readColor(reader); // native color
}
effects.innerGlow = {
size: { units: 'Pixels', value: size },
color: color,
blendMode: blendMode,
enabled: enabled,
opacity: opacity
};
break;
}
case 'bevl': { // bevel (see See Effects layer, bevel info)
var blockSize = readUint32(reader);
var version_5 = readUint32(reader);
if (blockSize !== 58 && blockSize !== 78)
throw new Error("Invalid bevel size: ".concat(blockSize));
if (version_5 !== 0 && version_5 !== 2)
throw new Error("Invalid bevel version: ".concat(version_5));
var angle = readFixedPoint32(reader);
var strength = readFixedPoint32(reader);
var size = readFixedPoint32(reader);
var highlightBlendMode = readBlendMode(reader);
var shadowBlendMode = readBlendMode(reader);
var highlightColor = readColor(reader);
var shadowColor = readColor(reader);
var style = bevelStyles[readUint8(reader)] || 'inner bevel';
var highlightOpacity = readFixedPoint8(reader);
var shadowOpacity = readFixedPoint8(reader);
var enabled = !!readUint8(reader);
var useGlobalLight = !!readUint8(reader);
var direction = readUint8(reader) ? 'down' : 'up';
if (blockSize >= 78) {
readColor(reader); // real highlight color
readColor(reader); // real shadow color
}
effects.bevel = {
size: { units: 'Pixels', value: size },
angle: angle,
strength: strength,
highlightBlendMode: highlightBlendMode,
shadowBlendMode: shadowBlendMode,
highlightColor: highlightColor,
shadowColor: shadowColor,
style: style,
highlightOpacity: highlightOpacity,
shadowOpacity: shadowOpacity,
enabled: enabled,
useGlobalLight: useGlobalLight,
direction: direction,
};
break;
}
case 'sofi': { // solid fill (Photoshop 7.0) (see See Effects layer, solid fill (added in Photoshop 7.0))
var size = readUint32(reader);
var version_6 = readUint32(reader);
if (size !== 34)
throw new Error("Invalid effects solid fill info size: ".concat(size));
if (version_6 !== 2)
throw new Error("Invalid effects solid fill info version: ".concat(version_6));
var blendMode = readBlendMode(reader);
var color = readColor(reader);
var opacity = readFixedPoint8(reader);
var enabled = !!readUint8(reader);
readColor(reader); // native color
effects.solidFill = [{ blendMode: blendMode, color: color, opacity: opacity, enabled: enabled }];
break;
}
default:
throw new Error("Invalid effect type: '".concat(type, "'"));
}
}
return effects;
}
function writeShadowInfo(writer, shadow) {
var _a;
writeUint32(writer, 51);
writeUint32(writer, 2);
writeFixedPoint32(writer, shadow.size && shadow.size.value || 0);
writeFixedPoint32(writer, 0); // intensity
writeFixedPoint32(writer, shadow.angle || 0);
writeFixedPoint32(writer, shadow.distance && shadow.distance.value || 0);
writeColor(writer, shadow.color);
writeBlendMode(writer, shadow.blendMode);
writeUint8(writer, shadow.enabled ? 1 : 0);
writeUint8(writer, shadow.useGlobalLight ? 1 : 0);
writeFixedPoint8(writer, (_a = shadow.opacity) !== null && _a !== void 0 ? _a : 1);
writeColor(writer, shadow.color); // native color
}
export function writeEffects(writer, effects) {
var _a, _b, _c, _d, _e, _f;
var dropShadow = (_a = effects.dropShadow) === null || _a === void 0 ? void 0 : _a[0];
var innerShadow = (_b = effects.innerShadow) === null || _b === void 0 ? void 0 : _b[0];
var outerGlow = effects.outerGlow;
var innerGlow = effects.innerGlow;
var bevel = effects.bevel;
var solidFill = (_c = effects.solidFill) === null || _c === void 0 ? void 0 : _c[0];
var count = 1;
if (dropShadow)
count++;
if (innerShadow)
count++;
if (outerGlow)
count++;
if (innerGlow)
count++;
if (bevel)
count++;
if (solidFill)
count++;
writeUint16(writer, 0);
writeUint16(writer, count);
writeSignature(writer, '8BIM');
writeSignature(writer, 'cmnS');
writeUint32(writer, 7); // size
writeUint32(writer, 0); // version
writeUint8(writer, 1); // visible
writeZeros(writer, 2);
if (dropShadow) {
writeSignature(writer, '8BIM');
writeSignature(writer, 'dsdw');
writeShadowInfo(writer, dropShadow);
}
if (innerShadow) {
writeSignature(writer, '8BIM');
writeSignature(writer, 'isdw');
writeShadowInfo(writer, innerShadow);
}
if (outerGlow) {
writeSignature(writer, '8BIM');
writeSignature(writer, 'oglw');
writeUint32(writer, 42);
writeUint32(writer, 2);
writeFixedPoint32(writer, ((_d = outerGlow.size) === null || _d === void 0 ? void 0 : _d.value) || 0);
writeFixedPoint32(writer, 0); // intensity
writeColor(writer, outerGlow.color);
writeBlendMode(writer, outerGlow.blendMode);
writeUint8(writer, outerGlow.enabled ? 1 : 0);
writeFixedPoint8(writer, outerGlow.opacity || 0);
writeColor(writer, outerGlow.color);
}
if (innerGlow) {
writeSignature(writer, '8BIM');
writeSignature(writer, 'iglw');
writeUint32(writer, 43);
writeUint32(writer, 2);
writeFixedPoint32(writer, ((_e = innerGlow.size) === null || _e === void 0 ? void 0 : _e.value) || 0);
writeFixedPoint32(writer, 0); // intensity
writeColor(writer, innerGlow.color);
writeBlendMode(writer, innerGlow.blendMode);
writeUint8(writer, innerGlow.enabled ? 1 : 0);
writeFixedPoint8(writer, innerGlow.opacity || 0);
writeUint8(writer, 0); // inverted
writeColor(writer, innerGlow.color);
}
if (bevel) {
writeSignature(writer, '8BIM');
writeSignature(writer, 'bevl');
writeUint32(writer, 78);
writeUint32(writer, 2);
writeFixedPoint32(writer, bevel.angle || 0);
writeFixedPoint32(writer, bevel.strength || 0);
writeFixedPoint32(writer, ((_f = bevel.size) === null || _f === void 0 ? void 0 : _f.value) || 0);
writeBlendMode(writer, bevel.highlightBlendMode);
writeBlendMode(writer, bevel.shadowBlendMode);
writeColor(writer, bevel.highlightColor);
writeColor(writer, bevel.shadowColor);
var style = bevelStyles.indexOf(bevel.style);
writeUint8(writer, style <= 0 ? 1 : style);
writeFixedPoint8(writer, bevel.highlightOpacity || 0);
writeFixedPoint8(writer, bevel.shadowOpacity || 0);
writeUint8(writer, bevel.enabled ? 1 : 0);
writeUint8(writer, bevel.useGlobalLight ? 1 : 0);
writeUint8(writer, bevel.direction === 'down' ? 1 : 0);
writeColor(writer, bevel.highlightColor);
writeColor(writer, bevel.shadowColor);
}
if (solidFill) {
writeSignature(writer, '8BIM');
writeSignature(writer, 'sofi');
writeUint32(writer, 34);
writeUint32(writer, 2);
writeBlendMode(writer, solidFill.blendMode);
writeColor(writer, solidFill.color);
writeFixedPoint8(writer, solidFill.opacity || 0);
writeUint8(writer, solidFill.enabled ? 1 : 0);
writeColor(writer, solidFill.color);
}
}
//# sourceMappingURL=effectsHelpers.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,2 @@
export declare function parseEngineData(data: number[] | Uint8Array): any;
export declare function serializeEngineData(data: any, condensed?: boolean): Uint8Array;

View File

@ -0,0 +1,332 @@
function isWhitespace(char) {
// ' ', '\n', '\r', '\t'
return char === 32 || char === 10 || char === 13 || char === 9;
}
function isNumber(char) {
// 0123456789.-
return (char >= 48 && char <= 57) || char === 46 || char === 45;
}
export function parseEngineData(data) {
var index = 0;
function skipWhitespace() {
while (index < data.length && isWhitespace(data[index])) {
index++;
}
}
function getTextByte() {
var byte = data[index];
index++;
if (byte === 92) { // \
byte = data[index];
index++;
}
return byte;
}
function getText() {
var result = '';
if (data[index] === 41) { // )
index++;
return result;
}
// Strings start with utf-16 BOM
if (data[index] !== 0xFE || data[index + 1] !== 0xFF) {
throw new Error('Invalid utf-16 BOM');
}
index += 2;
// ), ( and \ characters are escaped in ascii manner, remove the escapes before interpreting
// the bytes as utf-16
while (index < data.length && data[index] !== 41) { // )
var high = getTextByte();
var low = getTextByte();
var char = (high << 8) | low;
result += String.fromCharCode(char);
}
index++;
return result;
}
var root = null;
var stack = [];
function pushContainer(value) {
if (!stack.length) {
stack.push(value);
root = value;
}
else {
pushValue(value);
stack.push(value);
}
}
function pushValue(value) {
if (!stack.length)
throw new Error('Invalid data');
var top = stack[stack.length - 1];
if (typeof top === 'string') {
stack[stack.length - 2][top] = value;
pop();
}
else if (Array.isArray(top)) {
top.push(value);
}
else {
throw new Error('Invalid data');
}
}
function pushProperty(name) {
if (!stack.length)
pushContainer({});
var top = stack[stack.length - 1];
if (top && typeof top === 'string') {
if (name === 'nil') {
pushValue(null);
}
else {
pushValue("/".concat(name));
}
}
else if (top && typeof top === 'object') {
stack.push(name);
}
else {
throw new Error('Invalid data');
}
}
function pop() {
if (!stack.length)
throw new Error('Invalid data');
stack.pop();
}
skipWhitespace();
while (index < data.length) {
var i = index;
var char = data[i];
if (char === 60 && data[i + 1] === 60) { // <<
index += 2;
pushContainer({});
}
else if (char === 62 && data[i + 1] === 62) { // >>
index += 2;
pop();
}
else if (char === 47) { // /
index += 1;
var start = index;
while (index < data.length && !isWhitespace(data[index])) {
index++;
}
var name_1 = '';
for (var i_1 = start; i_1 < index; i_1++) {
name_1 += String.fromCharCode(data[i_1]);
}
pushProperty(name_1);
}
else if (char === 40) { // (
index += 1;
pushValue(getText());
}
else if (char === 91) { // [
index += 1;
pushContainer([]);
}
else if (char === 93) { // ]
index += 1;
pop();
}
else if (char === 110 && data[i + 1] === 117 && data[i + 2] === 108 && data[i + 3] === 108) { // null
index += 4;
pushValue(null);
}
else if (char === 116 && data[i + 1] === 114 && data[i + 2] === 117 && data[i + 3] === 101) { // true
index += 4;
pushValue(true);
}
else if (char === 102 && data[i + 1] === 97 && data[i + 2] === 108 && data[i + 3] === 115 && data[i + 4] === 101) { // false
index += 5;
pushValue(false);
}
else if (isNumber(char)) {
var value = '';
while (index < data.length && isNumber(data[index])) {
value += String.fromCharCode(data[index]);
index++;
}
pushValue(parseFloat(value));
}
else {
index += 1;
console.log("Invalid token ".concat(String.fromCharCode(char), " at ").concat(index));
// ` near ${String.fromCharCode.apply(null, data.slice(index - 10, index + 20) as any)}` +
// `data [${Array.from(data.slice(index - 10, index + 20)).join(', ')}]`
}
skipWhitespace();
}
return root;
}
var floatKeys = [
'Axis', 'XY', 'Zone', 'WordSpacing', 'FirstLineIndent', 'GlyphSpacing', 'StartIndent', 'EndIndent', 'SpaceBefore',
'SpaceAfter', 'LetterSpacing', 'Values', 'GridSize', 'GridLeading', 'PointBase', 'BoxBounds', 'TransformPoint0', 'TransformPoint1',
'TransformPoint2', 'FontSize', 'Leading', 'HorizontalScale', 'VerticalScale', 'BaselineShift', 'Tsume',
'OutlineWidth', 'AutoLeading',
];
var intArrays = ['RunLengthArray'];
// TODO: handle /nil
export function serializeEngineData(data, condensed) {
if (condensed === void 0) { condensed = false; }
var buffer = new Uint8Array(1024);
var offset = 0;
var indent = 0;
function write(value) {
if (offset >= buffer.length) {
var newBuffer = new Uint8Array(buffer.length * 2);
newBuffer.set(buffer);
buffer = newBuffer;
}
buffer[offset] = value;
offset++;
}
function writeString(value) {
for (var i = 0; i < value.length; i++) {
write(value.charCodeAt(i));
}
}
function writeIndent() {
if (condensed) {
writeString(' ');
}
else {
for (var i = 0; i < indent; i++) {
writeString('\t');
}
}
}
function writeProperty(key, value) {
writeIndent();
writeString("/".concat(key));
writeValue(value, key, true);
if (!condensed)
writeString('\n');
}
function serializeInt(value) {
return value.toString();
}
function serializeFloat(value) {
return value.toFixed(5)
.replace(/(\d)0+$/g, '$1')
.replace(/^0+\.([1-9])/g, '.$1')
.replace(/^-0+\.0(\d)/g, '-.0$1');
}
function serializeNumber(value, key) {
var isFloat = (key && floatKeys.indexOf(key) !== -1) || (value | 0) !== value;
return isFloat ? serializeFloat(value) : serializeInt(value);
}
function getKeys(value) {
var keys = Object.keys(value);
if (keys.indexOf('98') !== -1)
keys.unshift.apply(keys, keys.splice(keys.indexOf('99'), 1));
if (keys.indexOf('99') !== -1)
keys.unshift.apply(keys, keys.splice(keys.indexOf('99'), 1));
return keys;
}
function writeStringByte(value) {
if (value === 40 || value === 41 || value === 92) { // ( ) \
write(92); // \
}
write(value);
}
function writeValue(value, key, inProperty) {
if (inProperty === void 0) { inProperty = false; }
function writePrefix() {
if (inProperty) {
writeString(' ');
}
else {
writeIndent();
}
}
if (value === null) {
writePrefix();
writeString(condensed ? '/nil' : 'null');
}
else if (typeof value === 'number') {
writePrefix();
writeString(serializeNumber(value, key));
}
else if (typeof value === 'boolean') {
writePrefix();
writeString(value ? 'true' : 'false');
}
else if (typeof value === 'string') {
writePrefix();
if ((key === '99' || key === '98') && value.charAt(0) === '/') {
writeString(value);
}
else {
writeString('(');
write(0xfe);
write(0xff);
for (var i = 0; i < value.length; i++) {
var code = value.charCodeAt(i);
writeStringByte((code >> 8) & 0xff);
writeStringByte(code & 0xff);
}
writeString(')');
}
}
else if (Array.isArray(value)) {
writePrefix();
if (value.every(function (x) { return typeof x === 'number'; })) {
writeString('[');
var intArray = intArrays.indexOf(key) !== -1;
for (var _i = 0, value_1 = value; _i < value_1.length; _i++) {
var x = value_1[_i];
writeString(' ');
writeString(intArray ? serializeNumber(x) : serializeFloat(x));
}
writeString(' ]');
}
else {
writeString('[');
if (!condensed)
writeString('\n');
for (var _a = 0, value_2 = value; _a < value_2.length; _a++) {
var x = value_2[_a];
writeValue(x, key);
if (!condensed)
writeString('\n');
}
writeIndent();
writeString(']');
}
}
else if (typeof value === 'object') {
if (inProperty && !condensed)
writeString('\n');
writeIndent();
writeString('<<');
if (!condensed)
writeString('\n');
indent++;
for (var _b = 0, _c = getKeys(value); _b < _c.length; _b++) {
var key_1 = _c[_b];
writeProperty(key_1, value[key_1]);
}
indent--;
writeIndent();
writeString('>>');
}
return undefined;
}
if (condensed) {
if (typeof data === 'object') {
for (var _i = 0, _a = getKeys(data); _i < _a.length; _i++) {
var key = _a[_i];
writeProperty(key, data[key]);
}
}
}
else {
writeString('\n\n');
writeValue(data);
}
return buffer.slice(0, offset);
}
//# sourceMappingURL=engineData.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,93 @@
import { Layer, BlendMode, LayerColor } from './psd';
export declare const MOCK_HANDLERS = false;
export declare const RAW_IMAGE_DATA = false;
export declare const fromBlendMode: {
[key: string]: string;
};
export declare const toBlendMode: {
[key: string]: BlendMode;
};
export declare const layerColors: LayerColor[];
export declare const largeAdditionalInfoKeys: string[];
export interface Dict {
[key: string]: string;
}
export declare function revMap(map: Dict): Dict;
export declare function createEnum<T>(prefix: string, def: string, map: Dict): {
decode: (val: string) => T;
encode: (val: T | undefined) => string;
};
export declare const enum ColorSpace {
RGB = 0,
HSB = 1,
CMYK = 2,
Lab = 7,
Grayscale = 8
}
export declare const enum LayerMaskFlags {
PositionRelativeToLayer = 1,
LayerMaskDisabled = 2,
InvertLayerMaskWhenBlending = 4,
LayerMaskFromRenderingOtherData = 8,
MaskHasParametersAppliedToIt = 16
}
export declare const enum MaskParams {
UserMaskDensity = 1,
UserMaskFeather = 2,
VectorMaskDensity = 4,
VectorMaskFeather = 8
}
export declare const enum ChannelID {
Color0 = 0,
Color1 = 1,
Color2 = 2,
Color3 = 3,
Transparency = -1,
UserMask = -2,
RealUserMask = -3
}
export declare const enum Compression {
RawData = 0,
RleCompressed = 1,
ZipWithoutPrediction = 2,
ZipWithPrediction = 3
}
export interface ChannelData {
channelId: ChannelID;
compression: Compression;
buffer: Uint8Array | undefined;
length: number;
}
export interface Bounds {
top: number;
left: number;
right: number;
bottom: number;
}
export interface LayerChannelData {
layer: Layer;
channels: ChannelData[];
top: number;
left: number;
right: number;
bottom: number;
mask?: Bounds;
}
export type PixelArray = Uint8ClampedArray | Uint8Array;
export interface PixelData {
data: PixelArray;
width: number;
height: number;
}
export declare function offsetForChannel(channelId: ChannelID, cmyk: boolean): number;
export declare function clamp(value: number, min: number, max: number): number;
export declare function hasAlpha(data: PixelData): boolean;
export declare function resetImageData({ data }: PixelData): void;
export declare function decodeBitmap(input: PixelArray, output: PixelArray, width: number, height: number): void;
export declare function writeDataRaw(data: PixelData, offset: number, width: number, height: number): Uint8Array | undefined;
export declare function writeDataRLE(buffer: Uint8Array, { data, width, height }: PixelData, offsets: number[], large: boolean): Uint8Array | undefined;
export declare function writeDataZipWithoutPrediction({ data, width, height }: PixelData, offsets: number[]): Uint8Array;
export declare let createCanvas: (width: number, height: number) => HTMLCanvasElement;
export declare let createCanvasFromData: (data: Uint8Array) => HTMLCanvasElement;
export declare let createImageData: (width: number, height: number) => ImageData;
export declare function initializeCanvas(createCanvasMethod: (width: number, height: number) => HTMLCanvasElement, createCanvasFromDataMethod?: (data: Uint8Array) => HTMLCanvasElement, createImageDataMethod?: (width: number, height: number) => ImageData): void;

View File

@ -0,0 +1,315 @@
import { fromByteArray } from 'base64-js';
import { deflate } from 'pako';
export var MOCK_HANDLERS = false;
export var RAW_IMAGE_DATA = false;
export var fromBlendMode = {};
export var toBlendMode = {
'pass': 'pass through',
'norm': 'normal',
'diss': 'dissolve',
'dark': 'darken',
'mul ': 'multiply',
'idiv': 'color burn',
'lbrn': 'linear burn',
'dkCl': 'darker color',
'lite': 'lighten',
'scrn': 'screen',
'div ': 'color dodge',
'lddg': 'linear dodge',
'lgCl': 'lighter color',
'over': 'overlay',
'sLit': 'soft light',
'hLit': 'hard light',
'vLit': 'vivid light',
'lLit': 'linear light',
'pLit': 'pin light',
'hMix': 'hard mix',
'diff': 'difference',
'smud': 'exclusion',
'fsub': 'subtract',
'fdiv': 'divide',
'hue ': 'hue',
'sat ': 'saturation',
'colr': 'color',
'lum ': 'luminosity',
};
Object.keys(toBlendMode).forEach(function (key) { return fromBlendMode[toBlendMode[key]] = key; });
export var layerColors = [
'none', 'red', 'orange', 'yellow', 'green', 'blue', 'violet', 'gray'
];
export var largeAdditionalInfoKeys = [
// from documentation
'LMsk', 'Lr16', 'Lr32', 'Layr', 'Mt16', 'Mt32', 'Mtrn', 'Alph', 'FMsk', 'lnk2', 'FEid', 'FXid', 'PxSD',
// from guessing
'cinf',
];
export function revMap(map) {
var result = {};
Object.keys(map).forEach(function (key) { return result[map[key]] = key; });
return result;
}
export function createEnum(prefix, def, map) {
var rev = revMap(map);
var decode = function (val) {
var value = val.split('.')[1];
if (value && !rev[value])
throw new Error("Unrecognized value for enum: '".concat(val, "'"));
return rev[value] || def;
};
var encode = function (val) {
if (val && !map[val])
throw new Error("Invalid value for enum: '".concat(val, "'"));
return "".concat(prefix, ".").concat(map[val] || map[def]);
};
return { decode: decode, encode: encode };
}
export var ColorSpace;
(function (ColorSpace) {
ColorSpace[ColorSpace["RGB"] = 0] = "RGB";
ColorSpace[ColorSpace["HSB"] = 1] = "HSB";
ColorSpace[ColorSpace["CMYK"] = 2] = "CMYK";
ColorSpace[ColorSpace["Lab"] = 7] = "Lab";
ColorSpace[ColorSpace["Grayscale"] = 8] = "Grayscale";
})(ColorSpace || (ColorSpace = {}));
export var LayerMaskFlags;
(function (LayerMaskFlags) {
LayerMaskFlags[LayerMaskFlags["PositionRelativeToLayer"] = 1] = "PositionRelativeToLayer";
LayerMaskFlags[LayerMaskFlags["LayerMaskDisabled"] = 2] = "LayerMaskDisabled";
LayerMaskFlags[LayerMaskFlags["InvertLayerMaskWhenBlending"] = 4] = "InvertLayerMaskWhenBlending";
LayerMaskFlags[LayerMaskFlags["LayerMaskFromRenderingOtherData"] = 8] = "LayerMaskFromRenderingOtherData";
LayerMaskFlags[LayerMaskFlags["MaskHasParametersAppliedToIt"] = 16] = "MaskHasParametersAppliedToIt";
})(LayerMaskFlags || (LayerMaskFlags = {}));
export var MaskParams;
(function (MaskParams) {
MaskParams[MaskParams["UserMaskDensity"] = 1] = "UserMaskDensity";
MaskParams[MaskParams["UserMaskFeather"] = 2] = "UserMaskFeather";
MaskParams[MaskParams["VectorMaskDensity"] = 4] = "VectorMaskDensity";
MaskParams[MaskParams["VectorMaskFeather"] = 8] = "VectorMaskFeather";
})(MaskParams || (MaskParams = {}));
export var ChannelID;
(function (ChannelID) {
ChannelID[ChannelID["Color0"] = 0] = "Color0";
ChannelID[ChannelID["Color1"] = 1] = "Color1";
ChannelID[ChannelID["Color2"] = 2] = "Color2";
ChannelID[ChannelID["Color3"] = 3] = "Color3";
ChannelID[ChannelID["Transparency"] = -1] = "Transparency";
ChannelID[ChannelID["UserMask"] = -2] = "UserMask";
ChannelID[ChannelID["RealUserMask"] = -3] = "RealUserMask";
})(ChannelID || (ChannelID = {}));
export var Compression;
(function (Compression) {
Compression[Compression["RawData"] = 0] = "RawData";
Compression[Compression["RleCompressed"] = 1] = "RleCompressed";
Compression[Compression["ZipWithoutPrediction"] = 2] = "ZipWithoutPrediction";
Compression[Compression["ZipWithPrediction"] = 3] = "ZipWithPrediction";
})(Compression || (Compression = {}));
export function offsetForChannel(channelId, cmyk) {
switch (channelId) {
case 0 /* ChannelID.Color0 */: return 0;
case 1 /* ChannelID.Color1 */: return 1;
case 2 /* ChannelID.Color2 */: return 2;
case 3 /* ChannelID.Color3 */: return cmyk ? 3 : channelId + 1;
case -1 /* ChannelID.Transparency */: return cmyk ? 4 : 3;
default: return channelId + 1;
}
}
export function clamp(value, min, max) {
return value < min ? min : (value > max ? max : value);
}
export function hasAlpha(data) {
var size = data.width * data.height * 4;
for (var i = 3; i < size; i += 4) {
if (data.data[i] !== 255) {
return true;
}
}
return false;
}
export function resetImageData(_a) {
var data = _a.data;
var buffer = new Uint32Array(data.buffer);
var size = buffer.length | 0;
for (var p = 0; p < size; p = (p + 1) | 0) {
buffer[p] = 0xff000000;
}
}
export function decodeBitmap(input, output, width, height) {
for (var y = 0, p = 0, o = 0; y < height; y++) {
for (var x = 0; x < width;) {
var b = input[o++];
for (var i = 0; i < 8 && x < width; i++, x++) {
var v = b & 0x80 ? 0 : 255;
b = b << 1;
output[p++] = v;
output[p++] = v;
output[p++] = v;
output[p++] = 255;
}
}
}
}
export function writeDataRaw(data, offset, width, height) {
if (!width || !height)
return undefined;
var array = new Uint8Array(width * height);
for (var i = 0; i < array.length; i++) {
array[i] = data.data[i * 4 + offset];
}
return array;
}
export function writeDataRLE(buffer, _a, offsets, large) {
var data = _a.data, width = _a.width, height = _a.height;
if (!width || !height)
return undefined;
var stride = (4 * width) | 0;
var ol = 0;
var o = (offsets.length * (large ? 4 : 2) * height) | 0;
for (var _i = 0, offsets_1 = offsets; _i < offsets_1.length; _i++) {
var offset = offsets_1[_i];
for (var y = 0, p = offset | 0; y < height; y++) {
var strideStart = (y * stride) | 0;
var strideEnd = (strideStart + stride) | 0;
var lastIndex = (strideEnd + offset - 4) | 0;
var lastIndex2 = (lastIndex - 4) | 0;
var startOffset = o;
for (p = (strideStart + offset) | 0; p < strideEnd; p = (p + 4) | 0) {
if (p < lastIndex2) {
var value1 = data[p];
p = (p + 4) | 0;
var value2 = data[p];
p = (p + 4) | 0;
var value3 = data[p];
if (value1 === value2 && value1 === value3) {
var count = 3;
while (count < 128 && p < lastIndex && data[(p + 4) | 0] === value1) {
count = (count + 1) | 0;
p = (p + 4) | 0;
}
buffer[o++] = 1 - count;
buffer[o++] = value1;
}
else {
var countIndex = o;
var writeLast = true;
var count = 1;
buffer[o++] = 0;
buffer[o++] = value1;
while (p < lastIndex && count < 128) {
p = (p + 4) | 0;
value1 = value2;
value2 = value3;
value3 = data[p];
if (value1 === value2 && value1 === value3) {
p = (p - 12) | 0;
writeLast = false;
break;
}
else {
count++;
buffer[o++] = value1;
}
}
if (writeLast) {
if (count < 127) {
buffer[o++] = value2;
buffer[o++] = value3;
count += 2;
}
else if (count < 128) {
buffer[o++] = value2;
count++;
p = (p - 4) | 0;
}
else {
p = (p - 8) | 0;
}
}
buffer[countIndex] = count - 1;
}
}
else if (p === lastIndex) {
buffer[o++] = 0;
buffer[o++] = data[p];
}
else { // p === lastIndex2
buffer[o++] = 1;
buffer[o++] = data[p];
p = (p + 4) | 0;
buffer[o++] = data[p];
}
}
var length_1 = o - startOffset;
if (large) {
buffer[ol++] = (length_1 >> 24) & 0xff;
buffer[ol++] = (length_1 >> 16) & 0xff;
}
buffer[ol++] = (length_1 >> 8) & 0xff;
buffer[ol++] = length_1 & 0xff;
}
}
return buffer.slice(0, o);
}
export function writeDataZipWithoutPrediction(_a, offsets) {
var data = _a.data, width = _a.width, height = _a.height;
var size = width * height;
var channel = new Uint8Array(size);
var buffers = [];
var totalLength = 0;
for (var _i = 0, offsets_2 = offsets; _i < offsets_2.length; _i++) {
var offset = offsets_2[_i];
for (var i = 0, o = offset; i < size; i++, o += 4) {
channel[i] = data[o];
}
var buffer = deflate(channel);
buffers.push(buffer);
totalLength += buffer.byteLength;
}
if (buffers.length > 0) {
var buffer = new Uint8Array(totalLength);
var offset = 0;
for (var _b = 0, buffers_1 = buffers; _b < buffers_1.length; _b++) {
var b = buffers_1[_b];
buffer.set(b, offset);
offset += b.byteLength;
}
return buffer;
}
else {
return buffers[0];
}
}
export var createCanvas = function () {
throw new Error('Canvas not initialized, use initializeCanvas method to set up createCanvas method');
};
export var createCanvasFromData = function () {
throw new Error('Canvas not initialized, use initializeCanvas method to set up createCanvasFromData method');
};
var tempCanvas = undefined;
export var createImageData = function (width, height) {
if (!tempCanvas)
tempCanvas = createCanvas(1, 1);
return tempCanvas.getContext('2d').createImageData(width, height);
};
if (typeof document !== 'undefined') {
createCanvas = function (width, height) {
var canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
return canvas;
};
createCanvasFromData = function (data) {
var image = new Image();
image.src = 'data:image/jpeg;base64,' + fromByteArray(data);
var canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
canvas.getContext('2d').drawImage(image, 0, 0);
return canvas;
};
}
export function initializeCanvas(createCanvasMethod, createCanvasFromDataMethod, createImageDataMethod) {
createCanvas = createCanvasMethod;
createCanvasFromData = createCanvasFromDataMethod || createCanvasFromData;
createImageData = createImageDataMethod || createImageData;
}
//# sourceMappingURL=helpers.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,13 @@
import { ImageResources, ReadOptions } from './psd';
import { PsdReader } from './psdReader';
import { PsdWriter } from './psdWriter';
export interface ResourceHandler {
key: number;
has: (target: ImageResources) => boolean | number;
read: (reader: PsdReader, target: ImageResources, left: () => number, options: ReadOptions) => void;
write: (writer: PsdWriter, target: ImageResources, index: number) => void;
}
export declare const resourceHandlers: ResourceHandler[];
export declare const resourceHandlersMap: {
[key: number]: ResourceHandler;
};

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,20 @@
/// <reference types="node" />
import { Psd, ReadOptions, WriteOptions } from './psd';
import { PsdWriter } from './psdWriter';
import { PsdReader } from './psdReader';
export * from './abr';
export * from './csh';
export { initializeCanvas } from './helpers';
export * from './psd';
import { fromByteArray } from 'base64-js';
export { PsdReader, PsdWriter };
interface BufferLike {
buffer: ArrayBuffer;
byteOffset: number;
byteLength: number;
}
export declare const byteArrayToBase64: typeof fromByteArray;
export declare function readPsd(buffer: ArrayBuffer | BufferLike, options?: ReadOptions): Psd;
export declare function writePsd(psd: Psd, options?: WriteOptions): ArrayBuffer;
export declare function writePsdUint8Array(psd: Psd, options?: WriteOptions): Uint8Array;
export declare function writePsdBuffer(psd: Psd, options?: WriteOptions): Buffer;

View File

@ -0,0 +1,31 @@
import { writePsd as writePsdInternal, getWriterBuffer, createWriter, getWriterBufferNoCopy } from './psdWriter';
import { readPsd as readPsdInternal, createReader } from './psdReader';
export * from './abr';
export * from './csh';
export { initializeCanvas } from './helpers';
export * from './psd';
import { fromByteArray } from 'base64-js';
export var byteArrayToBase64 = fromByteArray;
export function readPsd(buffer, options) {
var reader = 'buffer' in buffer ?
createReader(buffer.buffer, buffer.byteOffset, buffer.byteLength) :
createReader(buffer);
return readPsdInternal(reader, options);
}
export function writePsd(psd, options) {
var writer = createWriter();
writePsdInternal(writer, psd, options);
return getWriterBuffer(writer);
}
export function writePsdUint8Array(psd, options) {
var writer = createWriter();
writePsdInternal(writer, psd, options);
return getWriterBufferNoCopy(writer);
}
export function writePsdBuffer(psd, options) {
if (typeof Buffer === 'undefined') {
throw new Error('Buffer not supported on this platform');
}
return Buffer.from(writePsdUint8Array(psd, options));
}
//# sourceMappingURL=index.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"../src/","sources":["index.ts"],"names":[],"mappings":"AACA,OAAO,EAAa,QAAQ,IAAI,gBAAgB,EAAE,eAAe,EAAE,YAAY,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAC5H,OAAO,EAAa,OAAO,IAAI,eAAe,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAClF,cAAc,OAAO,CAAC;AACtB,cAAc,OAAO,CAAC;AACtB,OAAO,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAC7C,cAAc,OAAO,CAAC;AACtB,OAAO,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AAS1C,MAAM,CAAC,IAAM,iBAAiB,GAAG,aAAa,CAAC;AAE/C,MAAM,UAAU,OAAO,CAAC,MAAgC,EAAE,OAAqB;IAC9E,IAAM,MAAM,GAAG,QAAQ,IAAI,MAAM,CAAC,CAAC;QAClC,YAAY,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,UAAU,EAAE,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC;QACnE,YAAY,CAAC,MAAM,CAAC,CAAC;IACtB,OAAO,eAAe,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AACzC,CAAC;AAED,MAAM,UAAU,QAAQ,CAAC,GAAQ,EAAE,OAAsB;IACxD,IAAM,MAAM,GAAG,YAAY,EAAE,CAAC;IAC9B,gBAAgB,CAAC,MAAM,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;IACvC,OAAO,eAAe,CAAC,MAAM,CAAC,CAAC;AAChC,CAAC;AAED,MAAM,UAAU,kBAAkB,CAAC,GAAQ,EAAE,OAAsB;IAClE,IAAM,MAAM,GAAG,YAAY,EAAE,CAAC;IAC9B,gBAAgB,CAAC,MAAM,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;IACvC,OAAO,qBAAqB,CAAC,MAAM,CAAC,CAAC;AACtC,CAAC;AAED,MAAM,UAAU,cAAc,CAAC,GAAQ,EAAE,OAAsB;IAC9D,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;QAClC,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;KACzD;IAED,OAAO,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;AACtD,CAAC"}

View File

@ -0,0 +1 @@
export declare function initialize(): void;

View File

@ -0,0 +1,22 @@
import { createCanvas } from 'canvas';
import { initializeCanvas } from './index';
import { decodeJpeg } from './jpeg';
function createCanvasFromData(data) {
var canvas = createCanvas(100, 100);
try {
var context_1 = canvas.getContext('2d');
var imageData = decodeJpeg(data, function (w, h) { return context_1.createImageData(w, h); });
canvas.width = imageData.width;
canvas.height = imageData.height;
context_1.putImageData(imageData, 0, 0);
}
catch (e) {
console.error('JPEG decompression error', e.message);
}
return canvas;
}
initializeCanvas(createCanvas, createCanvasFromData);
export function initialize() {
initializeCanvas(createCanvas, createCanvasFromData);
}
//# sourceMappingURL=initializeCanvas.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"initializeCanvas.js","sourceRoot":"../src/","sources":["initializeCanvas.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AACtC,OAAO,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAC3C,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AAEpC,SAAS,oBAAoB,CAAC,IAAgB;IAC7C,IAAM,MAAM,GAAG,YAAY,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;IAEtC,IAAI;QACH,IAAM,SAAO,GAAG,MAAM,CAAC,UAAU,CAAC,IAAI,CAAE,CAAC;QACzC,IAAM,SAAS,GAAG,UAAU,CAAC,IAAI,EAAE,UAAC,CAAC,EAAE,CAAC,IAAK,OAAA,SAAO,CAAC,eAAe,CAAC,CAAC,EAAE,CAAC,CAAC,EAA7B,CAA6B,CAAC,CAAC;QAC5E,MAAM,CAAC,KAAK,GAAG,SAAS,CAAC,KAAK,CAAC;QAC/B,MAAM,CAAC,MAAM,GAAG,SAAS,CAAC,MAAM,CAAC;QACjC,SAAO,CAAC,YAAY,CAAC,SAAS,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;KACtC;IAAC,OAAO,CAAM,EAAE;QAChB,OAAO,CAAC,KAAK,CAAC,0BAA0B,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC;KACrD;IAED,OAAO,MAAM,CAAC;AACf,CAAC;AAED,gBAAgB,CAAC,YAAY,EAAE,oBAAoB,CAAC,CAAC;AAErD,MAAM,UAAU,UAAU;IACzB,gBAAgB,CAAC,YAAY,EAAE,oBAAoB,CAAC,CAAC;AACtD,CAAC"}

View File

@ -0,0 +1 @@
export declare function decodeJpeg(encoded: Uint8Array, createImageData: (width: number, height: number) => ImageData): ImageData;

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,19 @@
export var ColorMode;
(function (ColorMode) {
ColorMode[ColorMode["Bitmap"] = 0] = "Bitmap";
ColorMode[ColorMode["Grayscale"] = 1] = "Grayscale";
ColorMode[ColorMode["Indexed"] = 2] = "Indexed";
ColorMode[ColorMode["RGB"] = 3] = "RGB";
ColorMode[ColorMode["CMYK"] = 4] = "CMYK";
ColorMode[ColorMode["Multichannel"] = 7] = "Multichannel";
ColorMode[ColorMode["Duotone"] = 8] = "Duotone";
ColorMode[ColorMode["Lab"] = 9] = "Lab";
})(ColorMode || (ColorMode = {}));
export var SectionDividerType;
(function (SectionDividerType) {
SectionDividerType[SectionDividerType["Other"] = 0] = "Other";
SectionDividerType[SectionDividerType["OpenFolder"] = 1] = "OpenFolder";
SectionDividerType[SectionDividerType["ClosedFolder"] = 2] = "ClosedFolder";
SectionDividerType[SectionDividerType["BoundingSectionDivider"] = 3] = "BoundingSectionDivider";
})(SectionDividerType || (SectionDividerType = {}));
//# sourceMappingURL=psd.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"psd.js","sourceRoot":"../src/","sources":["psd.ts"],"names":[],"mappings":"AAMA,MAAM,CAAN,IAAkB,SASjB;AATD,WAAkB,SAAS;IAC1B,6CAAU,CAAA;IACV,mDAAa,CAAA;IACb,+CAAW,CAAA;IACX,uCAAO,CAAA;IACP,yCAAQ,CAAA;IACR,yDAAgB,CAAA;IAChB,+CAAW,CAAA;IACX,uCAAO,CAAA;AACR,CAAC,EATiB,SAAS,KAAT,SAAS,QAS1B;AAED,MAAM,CAAN,IAAkB,kBAKjB;AALD,WAAkB,kBAAkB;IACnC,6DAAS,CAAA;IACT,uEAAc,CAAA;IACd,2EAAgB,CAAA;IAChB,+FAA0B,CAAA;AAC3B,CAAC,EALiB,kBAAkB,KAAlB,kBAAkB,QAKnC"}

View File

@ -0,0 +1,36 @@
import { Psd, ColorMode, ReadOptions, Color, PatternInfo } from './psd';
import { PixelData } from './helpers';
export declare const supportedColorModes: ColorMode[];
export interface PsdReader {
offset: number;
view: DataView;
strict: boolean;
debug: boolean;
}
export declare function createReader(buffer: ArrayBuffer, offset?: number, length?: number): PsdReader;
export declare function warnOrThrow(reader: PsdReader, message: string): void;
export declare function readUint8(reader: PsdReader): number;
export declare function peekUint8(reader: PsdReader): number;
export declare function readInt16(reader: PsdReader): number;
export declare function readUint16(reader: PsdReader): number;
export declare function readInt32(reader: PsdReader): number;
export declare function readInt32LE(reader: PsdReader): number;
export declare function readUint32(reader: PsdReader): number;
export declare function readFloat32(reader: PsdReader): number;
export declare function readFloat64(reader: PsdReader): number;
export declare function readFixedPoint32(reader: PsdReader): number;
export declare function readFixedPointPath32(reader: PsdReader): number;
export declare function readBytes(reader: PsdReader, length: number): Uint8Array;
export declare function readSignature(reader: PsdReader): string;
export declare function readPascalString(reader: PsdReader, padTo: number): string;
export declare function readUnicodeString(reader: PsdReader): string;
export declare function readUnicodeStringWithLength(reader: PsdReader, length: number): string;
export declare function readAsciiString(reader: PsdReader, length: number): string;
export declare function skipBytes(reader: PsdReader, count: number): void;
export declare function checkSignature(reader: PsdReader, a: string, b?: string): void;
export declare function readPsd(reader: PsdReader, options?: ReadOptions): Psd;
export declare function readDataZipWithoutPrediction(reader: PsdReader, length: number, pixelData: PixelData | undefined, width: number, height: number, step: number, offset: number): void;
export declare function readDataRLE(reader: PsdReader, pixelData: PixelData | undefined, _width: number, height: number, step: number, offsets: number[], large: boolean): void;
export declare function readSection<T>(reader: PsdReader, round: number, func: (left: () => number) => T, skipEmpty?: boolean, eightBytes?: boolean): T | undefined;
export declare function readColor(reader: PsdReader): Color;
export declare function readPattern(reader: PsdReader): PatternInfo;

View File

@ -0,0 +1,956 @@
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
import { inflate } from 'pako';
import { resetImageData, offsetForChannel, decodeBitmap, createCanvas, createImageData, toBlendMode, RAW_IMAGE_DATA, largeAdditionalInfoKeys } from './helpers';
import { infoHandlersMap } from './additionalInfo';
import { resourceHandlersMap } from './imageResources';
export var supportedColorModes = [0 /* ColorMode.Bitmap */, 1 /* ColorMode.Grayscale */, 3 /* ColorMode.RGB */];
var colorModes = ['bitmap', 'grayscale', 'indexed', 'RGB', 'CMYK', 'multichannel', 'duotone', 'lab'];
function setupGrayscale(data) {
var size = data.width * data.height * 4;
for (var i = 0; i < size; i += 4) {
data.data[i + 1] = data.data[i];
data.data[i + 2] = data.data[i];
}
}
export function createReader(buffer, offset, length) {
var view = new DataView(buffer, offset, length);
return { view: view, offset: 0, strict: false, debug: false };
}
export function warnOrThrow(reader, message) {
if (reader.strict)
throw new Error(message);
if (reader.debug)
console.warn(message);
}
export function readUint8(reader) {
reader.offset += 1;
return reader.view.getUint8(reader.offset - 1);
}
export function peekUint8(reader) {
return reader.view.getUint8(reader.offset);
}
export function readInt16(reader) {
reader.offset += 2;
return reader.view.getInt16(reader.offset - 2, false);
}
export function readUint16(reader) {
reader.offset += 2;
return reader.view.getUint16(reader.offset - 2, false);
}
export function readInt32(reader) {
reader.offset += 4;
return reader.view.getInt32(reader.offset - 4, false);
}
export function readInt32LE(reader) {
reader.offset += 4;
return reader.view.getInt32(reader.offset - 4, true);
}
export function readUint32(reader) {
reader.offset += 4;
return reader.view.getUint32(reader.offset - 4, false);
}
export function readFloat32(reader) {
reader.offset += 4;
return reader.view.getFloat32(reader.offset - 4, false);
}
export function readFloat64(reader) {
reader.offset += 8;
return reader.view.getFloat64(reader.offset - 8, false);
}
// 32-bit fixed-point number 16.16
export function readFixedPoint32(reader) {
return readInt32(reader) / (1 << 16);
}
// 32-bit fixed-point number 8.24
export function readFixedPointPath32(reader) {
return readInt32(reader) / (1 << 24);
}
export function readBytes(reader, length) {
var start = reader.view.byteOffset + reader.offset;
reader.offset += length;
if ((start + length) > reader.view.buffer.byteLength) {
// fix for broken PSD files that are missing part of file at the end
warnOrThrow(reader, 'Reading bytes exceeding buffer length');
if (length > (100 * 1024 * 1024))
throw new Error('Reading past end of file'); // limit to 100MB
var result = new Uint8Array(length);
var len = Math.min(length, reader.view.byteLength - start);
if (len > 0)
result.set(new Uint8Array(reader.view.buffer, start, len));
return result;
}
else {
return new Uint8Array(reader.view.buffer, start, length);
}
}
export function readSignature(reader) {
return readShortString(reader, 4);
}
export function readPascalString(reader, padTo) {
var length = readUint8(reader);
var text = length ? readShortString(reader, length) : '';
while (++length % padTo) {
reader.offset++;
}
return text;
}
export function readUnicodeString(reader) {
var length = readUint32(reader);
return readUnicodeStringWithLength(reader, length);
}
export function readUnicodeStringWithLength(reader, length) {
var text = '';
while (length--) {
var value = readUint16(reader);
if (value || length > 0) { // remove trailing \0
text += String.fromCharCode(value);
}
}
return text;
}
export function readAsciiString(reader, length) {
var text = '';
while (length--) {
text += String.fromCharCode(readUint8(reader));
}
return text;
}
export function skipBytes(reader, count) {
reader.offset += count;
}
export function checkSignature(reader, a, b) {
var offset = reader.offset;
var signature = readSignature(reader);
if (signature !== a && signature !== b) {
throw new Error("Invalid signature: '".concat(signature, "' at 0x").concat(offset.toString(16)));
}
}
function readShortString(reader, length) {
var buffer = readBytes(reader, length);
var result = '';
for (var i = 0; i < buffer.length; i++) {
result += String.fromCharCode(buffer[i]);
}
return result;
}
function isValidSignature(sig) {
return sig === '8BIM' || sig === 'MeSa' || sig === 'AgHg' || sig === 'PHUT' || sig === 'DCSR';
}
export function readPsd(reader, options) {
var _a;
if (options === void 0) { options = {}; }
// header
checkSignature(reader, '8BPS');
var version = readUint16(reader);
if (version !== 1 && version !== 2)
throw new Error("Invalid PSD file version: ".concat(version));
skipBytes(reader, 6);
var channels = readUint16(reader);
var height = readUint32(reader);
var width = readUint32(reader);
var bitsPerChannel = readUint16(reader);
var colorMode = readUint16(reader);
var maxSize = version === 1 ? 30000 : 300000;
if (width > maxSize || height > maxSize)
throw new Error("Invalid size");
if (channels > 16)
throw new Error("Invalid channel count");
if (bitsPerChannel > 32)
throw new Error("Invalid bitsPerChannel count");
if (supportedColorModes.indexOf(colorMode) === -1)
throw new Error("Color mode not supported: ".concat((_a = colorModes[colorMode]) !== null && _a !== void 0 ? _a : colorMode));
var psd = { width: width, height: height, channels: channels, bitsPerChannel: bitsPerChannel, colorMode: colorMode };
var opt = __assign(__assign({}, options), { large: version === 2 });
var fixOffsets = [0, 1, -1, 2, -2, 3, -3, 4, -4];
// color mode data
readSection(reader, 1, function (left) {
if (opt.throwForMissingFeatures)
throw new Error('Color mode data not supported');
skipBytes(reader, left());
});
// image resources
readSection(reader, 1, function (left) {
var _loop_1 = function () {
var sigOffset = reader.offset;
var sig = '';
// attempt to fix broken document by realigning with the signature
for (var _i = 0, fixOffsets_1 = fixOffsets; _i < fixOffsets_1.length; _i++) {
var offset = fixOffsets_1[_i];
try {
reader.offset = sigOffset + offset;
sig = readSignature(reader);
}
catch (_a) { }
if (isValidSignature(sig))
break;
}
if (!isValidSignature(sig)) {
throw new Error("Invalid signature: '".concat(sig, "' at 0x").concat((sigOffset).toString(16)));
}
var id = readUint16(reader);
readPascalString(reader, 2); // name
readSection(reader, 2, function (left) {
var handler = resourceHandlersMap[id];
var skip = id === 1036 && !!opt.skipThumbnail;
if (!psd.imageResources) {
psd.imageResources = {};
}
if (handler && !skip) {
try {
handler.read(reader, psd.imageResources, left, opt);
}
catch (e) {
if (opt.throwForMissingFeatures)
throw e;
skipBytes(reader, left());
}
}
else {
// options.logMissingFeatures && console.log(`Unhandled image resource: ${id}`);
skipBytes(reader, left());
}
});
};
while (left()) {
_loop_1();
}
});
// layer and mask info
var globalAlpha = false;
readSection(reader, 1, function (left) {
globalAlpha = readLayerInfo(reader, psd, opt);
// SAI does not include this section
if (left() > 0) {
var globalLayerMaskInfo = readGlobalLayerMaskInfo(reader);
if (globalLayerMaskInfo)
psd.globalLayerMaskInfo = globalLayerMaskInfo;
}
else {
// revert back to end of section if exceeded section limits
// opt.logMissingFeatures && console.log('reverting to end of section');
skipBytes(reader, left());
}
while (left() > 0) {
// sometimes there are empty bytes here
while (left() && peekUint8(reader) === 0) {
// opt.logMissingFeatures && console.log('skipping 0 byte');
skipBytes(reader, 1);
}
if (left() >= 12) {
readAdditionalLayerInfo(reader, psd, psd, opt);
}
else {
// opt.logMissingFeatures && console.log('skipping leftover bytes', left());
skipBytes(reader, left());
}
}
}, undefined, opt.large);
var hasChildren = psd.children && psd.children.length;
var skipComposite = opt.skipCompositeImageData && (opt.skipLayerImageData || hasChildren);
if (!skipComposite) {
readImageData(reader, psd, globalAlpha, opt);
}
// TODO: show converted color mode instead of original PSD file color mode
// but add option to preserve file color mode (need to return image data instead of canvas in that case)
// psd.colorMode = ColorMode.RGB; // we convert all color modes to RGB
return psd;
}
function readLayerInfo(reader, psd, options) {
var globalAlpha = false;
readSection(reader, 2, function (left) {
var layerCount = readInt16(reader);
if (layerCount < 0) {
globalAlpha = true;
layerCount = -layerCount;
}
var layers = [];
var layerChannels = [];
for (var i = 0; i < layerCount; i++) {
var _a = readLayerRecord(reader, psd, options), layer = _a.layer, channels = _a.channels;
layers.push(layer);
layerChannels.push(channels);
}
if (!options.skipLayerImageData) {
for (var i = 0; i < layerCount; i++) {
readLayerChannelImageData(reader, psd, layers[i], layerChannels[i], options);
}
}
skipBytes(reader, left());
if (!psd.children)
psd.children = [];
var stack = [psd];
for (var i = layers.length - 1; i >= 0; i--) {
var l = layers[i];
var type = l.sectionDivider ? l.sectionDivider.type : 0 /* SectionDividerType.Other */;
if (type === 1 /* SectionDividerType.OpenFolder */ || type === 2 /* SectionDividerType.ClosedFolder */) {
l.opened = type === 1 /* SectionDividerType.OpenFolder */;
l.children = [];
stack[stack.length - 1].children.unshift(l);
stack.push(l);
}
else if (type === 3 /* SectionDividerType.BoundingSectionDivider */) {
stack.pop();
// this was workaround because I didn't know what `lsdk` section was, now it's probably not needed anymore
// } else if (l.name === '</Layer group>' && !l.sectionDivider && !l.top && !l.left && !l.bottom && !l.right) {
// // sometimes layer group terminator doesn't have sectionDivider, so we just guess here (PS bug ?)
// stack.pop();
}
else {
stack[stack.length - 1].children.unshift(l);
}
}
}, undefined, options.large);
return globalAlpha;
}
function readLayerRecord(reader, psd, options) {
var layer = {};
layer.top = readInt32(reader);
layer.left = readInt32(reader);
layer.bottom = readInt32(reader);
layer.right = readInt32(reader);
var channelCount = readUint16(reader);
var channels = [];
for (var i = 0; i < channelCount; i++) {
var channelID = readInt16(reader);
var channelLength = readUint32(reader);
if (options.large) {
if (channelLength !== 0)
throw new Error('Sizes larger than 4GB are not supported');
channelLength = readUint32(reader);
}
channels.push({ id: channelID, length: channelLength });
}
checkSignature(reader, '8BIM');
var blendMode = readSignature(reader);
if (!toBlendMode[blendMode])
throw new Error("Invalid blend mode: '".concat(blendMode, "'"));
layer.blendMode = toBlendMode[blendMode];
layer.opacity = readUint8(reader) / 0xff;
layer.clipping = readUint8(reader) === 1;
var flags = readUint8(reader);
layer.transparencyProtected = (flags & 0x01) !== 0;
layer.hidden = (flags & 0x02) !== 0;
// 0x04 - obsolete
// 0x08 - 1 for Photoshop 5.0 and later, tells if bit 4 has useful information
// 0x10 - pixel data irrelevant to appearance of document
// 0x20 - ???
// if (flags & 0x20) (layer as any)._2 = true; // TEMP !!!!
skipBytes(reader, 1);
readSection(reader, 1, function (left) {
var mask = readLayerMaskData(reader, options);
if (mask)
layer.mask = mask;
/*const blendingRanges =*/ readLayerBlendingRanges(reader);
layer.name = readPascalString(reader, 4);
while (left()) {
readAdditionalLayerInfo(reader, layer, psd, options);
}
});
return { layer: layer, channels: channels };
}
function readLayerMaskData(reader, options) {
return readSection(reader, 1, function (left) {
if (!left())
return undefined;
var mask = {};
mask.top = readInt32(reader);
mask.left = readInt32(reader);
mask.bottom = readInt32(reader);
mask.right = readInt32(reader);
mask.defaultColor = readUint8(reader);
var flags = readUint8(reader);
mask.positionRelativeToLayer = (flags & 1 /* LayerMaskFlags.PositionRelativeToLayer */) !== 0;
mask.disabled = (flags & 2 /* LayerMaskFlags.LayerMaskDisabled */) !== 0;
mask.fromVectorData = (flags & 8 /* LayerMaskFlags.LayerMaskFromRenderingOtherData */) !== 0;
if (flags & 16 /* LayerMaskFlags.MaskHasParametersAppliedToIt */) {
var params = readUint8(reader);
if (params & 1 /* MaskParams.UserMaskDensity */)
mask.userMaskDensity = readUint8(reader) / 0xff;
if (params & 2 /* MaskParams.UserMaskFeather */)
mask.userMaskFeather = readFloat64(reader);
if (params & 4 /* MaskParams.VectorMaskDensity */)
mask.vectorMaskDensity = readUint8(reader) / 0xff;
if (params & 8 /* MaskParams.VectorMaskFeather */)
mask.vectorMaskFeather = readFloat64(reader);
}
if (left() > 2) {
options.logMissingFeatures && console.log('Unhandled extra mask params');
// TODO: handle these values
/*const realFlags =*/ readUint8(reader);
/*const realUserMaskBackground =*/ readUint8(reader);
/*const top2 =*/ readInt32(reader);
/*const left2 =*/ readInt32(reader);
/*const bottom2 =*/ readInt32(reader);
/*const right2 =*/ readInt32(reader);
}
skipBytes(reader, left());
return mask;
});
}
function readLayerBlendingRanges(reader) {
return readSection(reader, 1, function (left) {
var compositeGrayBlendSource = readUint32(reader);
var compositeGraphBlendDestinationRange = readUint32(reader);
var ranges = [];
while (left()) {
var sourceRange = readUint32(reader);
var destRange = readUint32(reader);
ranges.push({ sourceRange: sourceRange, destRange: destRange });
}
return { compositeGrayBlendSource: compositeGrayBlendSource, compositeGraphBlendDestinationRange: compositeGraphBlendDestinationRange, ranges: ranges };
});
}
function readLayerChannelImageData(reader, psd, layer, channels, options) {
var layerWidth = (layer.right || 0) - (layer.left || 0);
var layerHeight = (layer.bottom || 0) - (layer.top || 0);
var cmyk = psd.colorMode === 4 /* ColorMode.CMYK */;
var imageData;
if (layerWidth && layerHeight) {
if (cmyk) {
imageData = { width: layerWidth, height: layerHeight, data: new Uint8ClampedArray(layerWidth * layerHeight * 5) };
for (var p = 4; p < imageData.data.byteLength; p += 5)
imageData.data[p] = 255;
}
else {
imageData = createImageData(layerWidth, layerHeight);
resetImageData(imageData);
}
}
if (RAW_IMAGE_DATA)
layer.imageDataRaw = [];
for (var _i = 0, channels_1 = channels; _i < channels_1.length; _i++) {
var channel = channels_1[_i];
if (channel.length === 0)
continue;
if (channel.length < 2)
throw new Error('Invalid channel length');
var start = reader.offset;
var compression = readUint16(reader);
// try to fix broken files where there's 1 byte shift of channel
if (compression > 3) {
reader.offset -= 1;
compression = readUint16(reader);
}
// try to fix broken files where there's 1 byte shift of channel
if (compression > 3) {
reader.offset -= 3;
compression = readUint16(reader);
}
if (compression > 3)
throw new Error("Invalid compression: ".concat(compression));
if (channel.id === -2 /* ChannelID.UserMask */) {
var mask = layer.mask;
if (!mask)
throw new Error("Missing layer mask data");
var maskWidth = (mask.right || 0) - (mask.left || 0);
var maskHeight = (mask.bottom || 0) - (mask.top || 0);
if (maskWidth && maskHeight) {
var maskData = createImageData(maskWidth, maskHeight);
resetImageData(maskData);
var start_1 = reader.offset;
readData(reader, channel.length, maskData, compression, maskWidth, maskHeight, 0, options.large, 4);
if (RAW_IMAGE_DATA) {
layer.maskDataRaw = new Uint8Array(reader.view.buffer, reader.view.byteOffset + start_1, reader.offset - start_1);
}
setupGrayscale(maskData);
if (options.useImageData) {
mask.imageData = maskData;
}
else {
mask.canvas = createCanvas(maskWidth, maskHeight);
mask.canvas.getContext('2d').putImageData(maskData, 0, 0);
}
}
}
else {
var offset = offsetForChannel(channel.id, cmyk);
var targetData = imageData;
if (offset < 0) {
targetData = undefined;
if (options.throwForMissingFeatures) {
throw new Error("Channel not supported: ".concat(channel.id));
}
}
readData(reader, channel.length, targetData, compression, layerWidth, layerHeight, offset, options.large, cmyk ? 5 : 4);
if (RAW_IMAGE_DATA) {
layer.imageDataRaw[channel.id] = new Uint8Array(reader.view.buffer, reader.view.byteOffset + start + 2, channel.length - 2);
}
reader.offset = start + channel.length;
if (targetData && psd.colorMode === 1 /* ColorMode.Grayscale */) {
setupGrayscale(targetData);
}
}
}
if (imageData) {
if (cmyk) {
var cmykData = imageData;
imageData = createImageData(cmykData.width, cmykData.height);
cmykToRgb(cmykData, imageData, false);
}
if (options.useImageData) {
layer.imageData = imageData;
}
else {
layer.canvas = createCanvas(layerWidth, layerHeight);
layer.canvas.getContext('2d').putImageData(imageData, 0, 0);
}
}
}
function readData(reader, length, data, compression, width, height, offset, large, step) {
if (compression === 0 /* Compression.RawData */) {
readDataRaw(reader, data, width, height, step, offset);
}
else if (compression === 1 /* Compression.RleCompressed */) {
readDataRLE(reader, data, width, height, step, [offset], large);
}
else if (compression === 2 /* Compression.ZipWithoutPrediction */) {
readDataZipWithoutPrediction(reader, length, data, width, height, step, offset);
}
else if (compression === 3 /* Compression.ZipWithPrediction */) {
throw new Error("Compression type not supported: ".concat(compression));
}
else {
throw new Error("Invalid Compression type: ".concat(compression));
}
}
function readGlobalLayerMaskInfo(reader) {
return readSection(reader, 1, function (left) {
if (!left())
return undefined;
var overlayColorSpace = readUint16(reader);
var colorSpace1 = readUint16(reader);
var colorSpace2 = readUint16(reader);
var colorSpace3 = readUint16(reader);
var colorSpace4 = readUint16(reader);
var opacity = readUint16(reader) / 0xff;
var kind = readUint8(reader);
skipBytes(reader, left()); // 3 bytes of padding ?
return { overlayColorSpace: overlayColorSpace, colorSpace1: colorSpace1, colorSpace2: colorSpace2, colorSpace3: colorSpace3, colorSpace4: colorSpace4, opacity: opacity, kind: kind };
});
}
function readAdditionalLayerInfo(reader, target, psd, options) {
var sig = readSignature(reader);
if (sig !== '8BIM' && sig !== '8B64')
throw new Error("Invalid signature: '".concat(sig, "' at 0x").concat((reader.offset - 4).toString(16)));
var key = readSignature(reader);
// `largeAdditionalInfoKeys` fallback, because some keys don't have 8B64 signature even when they are 64bit
var u64 = sig === '8B64' || (options.large && largeAdditionalInfoKeys.indexOf(key) !== -1);
readSection(reader, 2, function (left) {
var handler = infoHandlersMap[key];
if (handler) {
try {
handler.read(reader, target, left, psd, options);
}
catch (e) {
if (options.throwForMissingFeatures)
throw e;
}
}
else {
options.logMissingFeatures && console.log("Unhandled additional info: ".concat(key));
skipBytes(reader, left());
}
if (left()) {
options.logMissingFeatures && console.log("Unread ".concat(left(), " bytes left for additional info: ").concat(key));
skipBytes(reader, left());
}
}, false, u64);
}
function readImageData(reader, psd, globalAlpha, options) {
var compression = readUint16(reader);
if (supportedColorModes.indexOf(psd.colorMode) === -1)
throw new Error("Color mode not supported: ".concat(psd.colorMode));
if (compression !== 0 /* Compression.RawData */ && compression !== 1 /* Compression.RleCompressed */)
throw new Error("Compression type not supported: ".concat(compression));
var imageData = createImageData(psd.width, psd.height);
resetImageData(imageData);
switch (psd.colorMode) {
case 0 /* ColorMode.Bitmap */: {
var bytes = void 0;
if (compression === 0 /* Compression.RawData */) {
bytes = readBytes(reader, Math.ceil(psd.width / 8) * psd.height);
}
else if (compression === 1 /* Compression.RleCompressed */) {
bytes = new Uint8Array(psd.width * psd.height);
readDataRLE(reader, { data: bytes, width: psd.width, height: psd.height }, psd.width, psd.height, 1, [0], options.large);
}
else {
throw new Error("Bitmap compression not supported: ".concat(compression));
}
decodeBitmap(bytes, imageData.data, psd.width, psd.height);
break;
}
case 3 /* ColorMode.RGB */:
case 1 /* ColorMode.Grayscale */: {
var channels = psd.colorMode === 1 /* ColorMode.Grayscale */ ? [0] : [0, 1, 2];
if (psd.channels && psd.channels > 3) {
for (var i = 3; i < psd.channels; i++) {
// TODO: store these channels in additional image data
channels.push(i);
}
}
else if (globalAlpha) {
channels.push(3);
}
if (compression === 0 /* Compression.RawData */) {
for (var i = 0; i < channels.length; i++) {
readDataRaw(reader, imageData, psd.width, psd.height, 4, channels[i]);
}
}
else if (compression === 1 /* Compression.RleCompressed */) {
var start = reader.offset;
readDataRLE(reader, imageData, psd.width, psd.height, 4, channels, options.large);
if (RAW_IMAGE_DATA)
psd.imageDataRaw = new Uint8Array(reader.view.buffer, reader.view.byteOffset + start, reader.offset - start);
}
if (psd.colorMode === 1 /* ColorMode.Grayscale */) {
setupGrayscale(imageData);
}
break;
}
case 4 /* ColorMode.CMYK */: {
if (psd.channels !== 4)
throw new Error("Invalid channel count");
var channels = [0, 1, 2, 3];
if (globalAlpha)
channels.push(4);
if (compression === 0 /* Compression.RawData */) {
throw new Error("Not implemented");
// TODO: ...
// for (let i = 0; i < channels.length; i++) {
// readDataRaw(reader, imageData, channels[i], psd.width, psd.height);
// }
}
else if (compression === 1 /* Compression.RleCompressed */) {
var cmykImageData = {
width: imageData.width,
height: imageData.height,
data: new Uint8Array(imageData.width * imageData.height * 5),
};
var start = reader.offset;
readDataRLE(reader, cmykImageData, psd.width, psd.height, 5, channels, options.large);
cmykToRgb(cmykImageData, imageData, true);
if (RAW_IMAGE_DATA)
psd.imageDataRaw = new Uint8Array(reader.view.buffer, reader.view.byteOffset + start, reader.offset - start);
}
break;
}
default: throw new Error("Color mode not supported: ".concat(psd.colorMode));
}
// remove weird white matte
if (globalAlpha) {
var p = imageData.data;
var size = imageData.width * imageData.height * 4;
for (var i = 0; i < size; i += 4) {
var pa = p[i + 3];
if (pa != 0 && pa != 255) {
var a = pa / 255;
var ra = 1 / a;
var invA = 255 * (1 - ra);
p[i + 0] = p[i + 0] * ra + invA;
p[i + 1] = p[i + 1] * ra + invA;
p[i + 2] = p[i + 2] * ra + invA;
}
}
}
if (options.useImageData) {
psd.imageData = imageData;
}
else {
psd.canvas = createCanvas(psd.width, psd.height);
psd.canvas.getContext('2d').putImageData(imageData, 0, 0);
}
}
function cmykToRgb(cmyk, rgb, reverseAlpha) {
var size = rgb.width * rgb.height * 4;
var srcData = cmyk.data;
var dstData = rgb.data;
for (var src = 0, dst = 0; dst < size; src += 5, dst += 4) {
var c = srcData[src];
var m = srcData[src + 1];
var y = srcData[src + 2];
var k = srcData[src + 3];
dstData[dst] = ((((c * k) | 0) / 255) | 0);
dstData[dst + 1] = ((((m * k) | 0) / 255) | 0);
dstData[dst + 2] = ((((y * k) | 0) / 255) | 0);
dstData[dst + 3] = reverseAlpha ? 255 - srcData[src + 4] : srcData[src + 4];
}
// for (let src = 0, dst = 0; dst < size; src += 5, dst += 4) {
// const c = 1 - (srcData[src + 0] / 255);
// const m = 1 - (srcData[src + 1] / 255);
// const y = 1 - (srcData[src + 2] / 255);
// // const k = srcData[src + 3] / 255;
// dstData[dst + 0] = ((1 - c * 0.8) * 255) | 0;
// dstData[dst + 1] = ((1 - m * 0.8) * 255) | 0;
// dstData[dst + 2] = ((1 - y * 0.8) * 255) | 0;
// dstData[dst + 3] = reverseAlpha ? 255 - srcData[src + 4] : srcData[src + 4];
// }
}
function readDataRaw(reader, pixelData, width, height, step, offset) {
var size = width * height;
var buffer = readBytes(reader, size);
if (pixelData && offset < step) {
var data = pixelData.data;
for (var i = 0, p = offset | 0; i < size; i++, p = (p + step) | 0) {
data[p] = buffer[i];
}
}
}
export function readDataZipWithoutPrediction(reader, length, pixelData, width, height, step, offset) {
var compressed = readBytes(reader, length);
var decompressed = inflate(compressed);
var size = width * height;
if (pixelData && offset < step) {
var data = pixelData.data;
for (var i = 0, p = offset | 0; i < size; i++, p = (p + step) | 0) {
data[p] = decompressed[i];
}
}
}
export function readDataRLE(reader, pixelData, _width, height, step, offsets, large) {
var data = pixelData && pixelData.data;
var lengths;
if (large) {
lengths = new Uint32Array(offsets.length * height);
for (var o = 0, li = 0; o < offsets.length; o++) {
for (var y = 0; y < height; y++, li++) {
lengths[li] = readUint32(reader);
}
}
}
else {
lengths = new Uint16Array(offsets.length * height);
for (var o = 0, li = 0; o < offsets.length; o++) {
for (var y = 0; y < height; y++, li++) {
lengths[li] = readUint16(reader);
}
}
}
var extraLimit = (step - 1) | 0; // 3 for rgb, 4 for cmyk
for (var c = 0, li = 0; c < offsets.length; c++) {
var offset = offsets[c] | 0;
var extra = c > extraLimit || offset > extraLimit;
if (!data || extra) {
for (var y = 0; y < height; y++, li++) {
skipBytes(reader, lengths[li]);
}
}
else {
for (var y = 0, p = offset | 0; y < height; y++, li++) {
var length_1 = lengths[li];
var buffer = readBytes(reader, length_1);
for (var i = 0; i < length_1; i++) {
var header = buffer[i];
if (header > 128) {
var value = buffer[++i];
header = (256 - header) | 0;
for (var j = 0; j <= header; j = (j + 1) | 0) {
data[p] = value;
p = (p + step) | 0;
}
}
else if (header < 128) {
for (var j = 0; j <= header; j = (j + 1) | 0) {
data[p] = buffer[++i];
p = (p + step) | 0;
}
}
else {
// ignore 128
}
// This showed up on some images from non-photoshop programs, ignoring it seems to work just fine.
// if (i >= length) throw new Error(`Invalid RLE data: exceeded buffer size ${i}/${length}`);
}
}
}
}
}
export function readSection(reader, round, func, skipEmpty, eightBytes) {
if (skipEmpty === void 0) { skipEmpty = true; }
if (eightBytes === void 0) { eightBytes = false; }
var length = readUint32(reader);
if (eightBytes) {
if (length !== 0)
throw new Error('Sizes larger than 4GB are not supported');
length = readUint32(reader);
}
if (length <= 0 && skipEmpty)
return undefined;
var end = reader.offset + length;
if (end > reader.view.byteLength)
throw new Error('Section exceeds file size');
var result = func(function () { return end - reader.offset; });
if (reader.offset !== end) {
if (reader.offset > end) {
warnOrThrow(reader, 'Exceeded section limits');
}
else {
warnOrThrow(reader, "Unread section data"); // : ${end - reader.offset} bytes at 0x${reader.offset.toString(16)}`);
}
}
while (end % round)
end++;
reader.offset = end;
return result;
}
export function readColor(reader) {
var colorSpace = readUint16(reader);
switch (colorSpace) {
case 0 /* ColorSpace.RGB */: {
var r = readUint16(reader) / 257;
var g = readUint16(reader) / 257;
var b = readUint16(reader) / 257;
skipBytes(reader, 2);
return { r: r, g: g, b: b };
}
case 1 /* ColorSpace.HSB */: {
var h = readUint16(reader) / 0xffff;
var s = readUint16(reader) / 0xffff;
var b = readUint16(reader) / 0xffff;
skipBytes(reader, 2);
return { h: h, s: s, b: b };
}
case 2 /* ColorSpace.CMYK */: {
var c = readUint16(reader) / 257;
var m = readUint16(reader) / 257;
var y = readUint16(reader) / 257;
var k = readUint16(reader) / 257;
return { c: c, m: m, y: y, k: k };
}
case 7 /* ColorSpace.Lab */: {
var l = readInt16(reader) / 10000;
var ta = readInt16(reader);
var tb = readInt16(reader);
var a = ta < 0 ? (ta / 12800) : (ta / 12700);
var b = tb < 0 ? (tb / 12800) : (tb / 12700);
skipBytes(reader, 2);
return { l: l, a: a, b: b };
}
case 8 /* ColorSpace.Grayscale */: {
var k = readUint16(reader) * 255 / 10000;
skipBytes(reader, 6);
return { k: k };
}
default:
throw new Error('Invalid color space');
}
}
export function readPattern(reader) {
readUint32(reader); // length
var version = readUint32(reader);
if (version !== 1)
throw new Error("Invalid pattern version: ".concat(version));
var colorMode = readUint32(reader);
var x = readInt16(reader);
var y = readInt16(reader);
// we only support RGB and grayscale for now
if (colorMode !== 3 /* ColorMode.RGB */ && colorMode !== 1 /* ColorMode.Grayscale */ && colorMode !== 2 /* ColorMode.Indexed */) {
throw new Error("Unsupported pattern color mode: ".concat(colorMode));
}
var name = readUnicodeString(reader);
var id = readPascalString(reader, 1);
var palette = [];
if (colorMode === 2 /* ColorMode.Indexed */) {
for (var i = 0; i < 256; i++) {
palette.push({
r: readUint8(reader),
g: readUint8(reader),
b: readUint8(reader),
});
}
skipBytes(reader, 4); // no idea what this is
}
// virtual memory array list
var version2 = readUint32(reader);
if (version2 !== 3)
throw new Error("Invalid pattern VMAL version: ".concat(version2));
readUint32(reader); // length
var top = readUint32(reader);
var left = readUint32(reader);
var bottom = readUint32(reader);
var right = readUint32(reader);
var channelsCount = readUint32(reader);
var width = right - left;
var height = bottom - top;
var data = new Uint8Array(width * height * 4);
for (var i = 3; i < data.byteLength; i += 4) {
data[i] = 255;
}
for (var i = 0, ch = 0; i < (channelsCount + 2); i++) {
var has = readUint32(reader);
if (!has)
continue;
var length_2 = readUint32(reader);
var pixelDepth = readUint32(reader);
var ctop = readUint32(reader);
var cleft = readUint32(reader);
var cbottom = readUint32(reader);
var cright = readUint32(reader);
var pixelDepth2 = readUint16(reader);
var compressionMode = readUint8(reader); // 0 - raw, 1 - zip
var dataLength = length_2 - (4 + 16 + 2 + 1);
var cdata = readBytes(reader, dataLength);
if (pixelDepth !== 8 || pixelDepth2 !== 8) {
throw new Error('16bit pixel depth not supported for patterns');
}
var w = cright - cleft;
var h = cbottom - ctop;
var ox = cleft - left;
var oy = ctop - top;
if (compressionMode === 0) {
if (colorMode === 3 /* ColorMode.RGB */ && ch < 3) {
for (var y_1 = 0; y_1 < h; y_1++) {
for (var x_1 = 0; x_1 < w; x_1++) {
var src = x_1 + y_1 * w;
var dst = (ox + x_1 + (y_1 + oy) * width) * 4;
data[dst + ch] = cdata[src];
}
}
}
if (colorMode === 1 /* ColorMode.Grayscale */ && ch < 1) {
for (var y_2 = 0; y_2 < h; y_2++) {
for (var x_2 = 0; x_2 < w; x_2++) {
var src = x_2 + y_2 * w;
var dst = (ox + x_2 + (y_2 + oy) * width) * 4;
var value = cdata[src];
data[dst + 0] = value;
data[dst + 1] = value;
data[dst + 2] = value;
}
}
}
if (colorMode === 2 /* ColorMode.Indexed */) {
// TODO:
throw new Error('Indexed pattern color mode not implemented');
}
}
else if (compressionMode === 1) {
// console.log({ colorMode });
// require('fs').writeFileSync('zip.bin', Buffer.from(cdata));
// const data = require('zlib').inflateRawSync(cdata);
// const data = require('zlib').unzipSync(cdata);
// console.log(data);
// throw new Error('Zip compression not supported for pattern');
// throw new Error('Unsupported pattern compression');
console.error('Unsupported pattern compression');
name += ' (failed to decode)';
}
else {
throw new Error('Invalid pattern compression mode');
}
ch++;
}
// TODO: use canvas instead of data ?
return { id: id, name: name, x: x, y: y, bounds: { x: left, y: top, w: width, h: height }, data: data };
}
//# sourceMappingURL=psdReader.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,27 @@
import { Psd, WriteOptions, Color } from './psd';
export interface PsdWriter {
offset: number;
buffer: ArrayBuffer;
view: DataView;
}
export declare function createWriter(size?: number): PsdWriter;
export declare function getWriterBuffer(writer: PsdWriter): ArrayBuffer;
export declare function getWriterBufferNoCopy(writer: PsdWriter): Uint8Array;
export declare function writeUint8(writer: PsdWriter, value: number): void;
export declare function writeInt16(writer: PsdWriter, value: number): void;
export declare function writeUint16(writer: PsdWriter, value: number): void;
export declare function writeInt32(writer: PsdWriter, value: number): void;
export declare function writeUint32(writer: PsdWriter, value: number): void;
export declare function writeFloat32(writer: PsdWriter, value: number): void;
export declare function writeFloat64(writer: PsdWriter, value: number): void;
export declare function writeFixedPoint32(writer: PsdWriter, value: number): void;
export declare function writeFixedPointPath32(writer: PsdWriter, value: number): void;
export declare function writeBytes(writer: PsdWriter, buffer: Uint8Array | undefined): void;
export declare function writeZeros(writer: PsdWriter, count: number): void;
export declare function writeSignature(writer: PsdWriter, signature: string): void;
export declare function writePascalString(writer: PsdWriter, text: string, padTo: number): void;
export declare function writeUnicodeString(writer: PsdWriter, text: string): void;
export declare function writeUnicodeStringWithPadding(writer: PsdWriter, text: string): void;
export declare function writeSection(writer: PsdWriter, round: number, func: () => void, writeTotalLength?: boolean, large?: boolean): void;
export declare function writePsd(writer: PsdWriter, psd: Psd, options?: WriteOptions): void;
export declare function writeColor(writer: PsdWriter, color: Color | undefined): void;

View File

@ -0,0 +1,692 @@
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
import { hasAlpha, createCanvas, writeDataRLE, offsetForChannel, createImageData, fromBlendMode, clamp, largeAdditionalInfoKeys, RAW_IMAGE_DATA, writeDataZipWithoutPrediction } from './helpers';
import { hasMultiEffects, infoHandlers } from './additionalInfo';
import { resourceHandlers } from './imageResources';
export function createWriter(size) {
if (size === void 0) { size = 4096; }
var buffer = new ArrayBuffer(size);
var view = new DataView(buffer);
var offset = 0;
return { buffer: buffer, view: view, offset: offset };
}
export function getWriterBuffer(writer) {
return writer.buffer.slice(0, writer.offset);
}
export function getWriterBufferNoCopy(writer) {
return new Uint8Array(writer.buffer, 0, writer.offset);
}
export function writeUint8(writer, value) {
var offset = addSize(writer, 1);
writer.view.setUint8(offset, value);
}
export function writeInt16(writer, value) {
var offset = addSize(writer, 2);
writer.view.setInt16(offset, value, false);
}
export function writeUint16(writer, value) {
var offset = addSize(writer, 2);
writer.view.setUint16(offset, value, false);
}
export function writeInt32(writer, value) {
var offset = addSize(writer, 4);
writer.view.setInt32(offset, value, false);
}
export function writeUint32(writer, value) {
var offset = addSize(writer, 4);
writer.view.setUint32(offset, value, false);
}
export function writeFloat32(writer, value) {
var offset = addSize(writer, 4);
writer.view.setFloat32(offset, value, false);
}
export function writeFloat64(writer, value) {
var offset = addSize(writer, 8);
writer.view.setFloat64(offset, value, false);
}
// 32-bit fixed-point number 16.16
export function writeFixedPoint32(writer, value) {
writeInt32(writer, value * (1 << 16));
}
// 32-bit fixed-point number 8.24
export function writeFixedPointPath32(writer, value) {
writeInt32(writer, value * (1 << 24));
}
export function writeBytes(writer, buffer) {
if (buffer) {
ensureSize(writer, writer.offset + buffer.length);
var bytes = new Uint8Array(writer.buffer);
bytes.set(buffer, writer.offset);
writer.offset += buffer.length;
}
}
export function writeZeros(writer, count) {
for (var i = 0; i < count; i++) {
writeUint8(writer, 0);
}
}
export function writeSignature(writer, signature) {
if (signature.length !== 4)
throw new Error("Invalid signature: '".concat(signature, "'"));
for (var i = 0; i < 4; i++) {
writeUint8(writer, signature.charCodeAt(i));
}
}
export function writePascalString(writer, text, padTo) {
var length = text.length;
writeUint8(writer, length);
for (var i = 0; i < length; i++) {
var code = text.charCodeAt(i);
writeUint8(writer, code < 128 ? code : '?'.charCodeAt(0));
}
while (++length % padTo) {
writeUint8(writer, 0);
}
}
export function writeUnicodeString(writer, text) {
writeUint32(writer, text.length);
for (var i = 0; i < text.length; i++) {
writeUint16(writer, text.charCodeAt(i));
}
}
export function writeUnicodeStringWithPadding(writer, text) {
writeUint32(writer, text.length + 1);
for (var i = 0; i < text.length; i++) {
writeUint16(writer, text.charCodeAt(i));
}
writeUint16(writer, 0);
}
function getLargestLayerSize(layers) {
if (layers === void 0) { layers = []; }
var max = 0;
for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
var layer = layers_1[_i];
if (layer.canvas || layer.imageData) {
var _a = getLayerDimentions(layer), width = _a.width, height = _a.height;
max = Math.max(max, 2 * height + 2 * width * height);
}
if (layer.children) {
max = Math.max(max, getLargestLayerSize(layer.children));
}
}
return max;
}
export function writeSection(writer, round, func, writeTotalLength, large) {
if (writeTotalLength === void 0) { writeTotalLength = false; }
if (large === void 0) { large = false; }
if (large)
writeUint32(writer, 0);
var offset = writer.offset;
writeUint32(writer, 0);
func();
var length = writer.offset - offset - 4;
var len = length;
while ((len % round) !== 0) {
writeUint8(writer, 0);
len++;
}
if (writeTotalLength) {
length = len;
}
writer.view.setUint32(offset, length, false);
}
export function writePsd(writer, psd, options) {
if (options === void 0) { options = {}; }
if (!(+psd.width > 0 && +psd.height > 0))
throw new Error('Invalid document size');
if ((psd.width > 30000 || psd.height > 30000) && !options.psb)
throw new Error('Document size is too large (max is 30000x30000, use PSB format instead)');
var imageResources = psd.imageResources || {};
var opt = __assign(__assign({}, options), { layerIds: new Set(), layerToId: new Map() });
if (opt.generateThumbnail) {
imageResources = __assign(__assign({}, imageResources), { thumbnail: createThumbnail(psd) });
}
var imageData = psd.imageData;
if (!imageData && psd.canvas) {
imageData = psd.canvas.getContext('2d').getImageData(0, 0, psd.canvas.width, psd.canvas.height);
}
if (imageData && (psd.width !== imageData.width || psd.height !== imageData.height))
throw new Error('Document canvas must have the same size as document');
var globalAlpha = !!imageData && hasAlpha(imageData);
var maxBufferSize = Math.max(getLargestLayerSize(psd.children), 4 * 2 * psd.width * psd.height + 2 * psd.height);
var tempBuffer = new Uint8Array(maxBufferSize);
// header
writeSignature(writer, '8BPS');
writeUint16(writer, options.psb ? 2 : 1); // version
writeZeros(writer, 6);
writeUint16(writer, globalAlpha ? 4 : 3); // channels
writeUint32(writer, psd.height);
writeUint32(writer, psd.width);
writeUint16(writer, 8); // bits per channel
writeUint16(writer, 3 /* ColorMode.RGB */); // we only support saving RGB right now
// color mode data
writeSection(writer, 1, function () {
// TODO: implement
});
// image resources
writeSection(writer, 1, function () {
var _loop_1 = function (handler) {
var has = handler.has(imageResources);
var count = has === false ? 0 : (has === true ? 1 : has);
var _loop_2 = function (i) {
writeSignature(writer, '8BIM');
writeUint16(writer, handler.key);
writePascalString(writer, '', 2);
writeSection(writer, 2, function () { return handler.write(writer, imageResources, i); });
};
for (var i = 0; i < count; i++) {
_loop_2(i);
}
};
for (var _i = 0, resourceHandlers_1 = resourceHandlers; _i < resourceHandlers_1.length; _i++) {
var handler = resourceHandlers_1[_i];
_loop_1(handler);
}
});
// layer and mask info
writeSection(writer, 2, function () {
writeLayerInfo(tempBuffer, writer, psd, globalAlpha, opt);
writeGlobalLayerMaskInfo(writer, psd.globalLayerMaskInfo);
writeAdditionalLayerInfo(writer, psd, psd, opt);
}, undefined, !!opt.psb);
// image data
var channels = globalAlpha ? [0, 1, 2, 3] : [0, 1, 2];
var width = imageData ? imageData.width : psd.width;
var height = imageData ? imageData.height : psd.height;
var data = { data: new Uint8Array(width * height * 4), width: width, height: height };
writeUint16(writer, 1 /* Compression.RleCompressed */); // Photoshop doesn't support zip compression of composite image data
if (RAW_IMAGE_DATA && psd.imageDataRaw) {
console.log('writing raw image data');
writeBytes(writer, psd.imageDataRaw);
}
else {
if (imageData)
data.data.set(new Uint8Array(imageData.data.buffer, imageData.data.byteOffset, imageData.data.byteLength));
// add weird white matte
if (globalAlpha) {
var size = data.width * data.height * 4;
var p = data.data;
for (var i = 0; i < size; i += 4) {
var pa = p[i + 3];
if (pa != 0 && pa != 255) {
var a = pa / 255;
var ra = 255 * (1 - a);
p[i + 0] = p[i + 0] * a + ra;
p[i + 1] = p[i + 1] * a + ra;
p[i + 2] = p[i + 2] * a + ra;
}
}
}
writeBytes(writer, writeDataRLE(tempBuffer, data, channels, !!options.psb));
}
}
function writeLayerInfo(tempBuffer, writer, psd, globalAlpha, options) {
writeSection(writer, 4, function () {
var _a;
var layers = [];
addChildren(layers, psd.children);
if (!layers.length)
layers.push({});
writeInt16(writer, globalAlpha ? -layers.length : layers.length);
var layersData = layers.map(function (l, i) { return getChannels(tempBuffer, l, i === 0, options); });
var _loop_3 = function (layerData) {
var layer = layerData.layer, top_1 = layerData.top, left = layerData.left, bottom = layerData.bottom, right = layerData.right, channels = layerData.channels;
writeInt32(writer, top_1);
writeInt32(writer, left);
writeInt32(writer, bottom);
writeInt32(writer, right);
writeUint16(writer, channels.length);
for (var _e = 0, channels_1 = channels; _e < channels_1.length; _e++) {
var c = channels_1[_e];
writeInt16(writer, c.channelId);
if (options.psb)
writeUint32(writer, 0);
writeUint32(writer, c.length);
}
writeSignature(writer, '8BIM');
writeSignature(writer, fromBlendMode[layer.blendMode] || 'norm');
writeUint8(writer, Math.round(clamp((_a = layer.opacity) !== null && _a !== void 0 ? _a : 1, 0, 1) * 255));
writeUint8(writer, layer.clipping ? 1 : 0);
var flags = 0x08; // 1 for Photoshop 5.0 and later, tells if bit 4 has useful information
if (layer.transparencyProtected)
flags |= 0x01;
if (layer.hidden)
flags |= 0x02;
if (layer.vectorMask || (layer.sectionDivider && layer.sectionDivider.type !== 0 /* SectionDividerType.Other */)) {
flags |= 0x10; // pixel data irrelevant to appearance of document
}
if (layer.effects && hasMultiEffects(layer.effects)) { // TODO: this is not correct
flags |= 0x20; // just guessing this one, might be completely incorrect
}
// if ('_2' in layer) flags |= 0x20; // TEMP!!!
writeUint8(writer, flags);
writeUint8(writer, 0); // filler
writeSection(writer, 1, function () {
writeLayerMaskData(writer, layer, layerData);
writeLayerBlendingRanges(writer, psd);
writePascalString(writer, layer.name || '', 4);
writeAdditionalLayerInfo(writer, layer, psd, options);
});
};
// layer records
for (var _i = 0, layersData_1 = layersData; _i < layersData_1.length; _i++) {
var layerData = layersData_1[_i];
_loop_3(layerData);
}
// layer channel image data
for (var _b = 0, layersData_2 = layersData; _b < layersData_2.length; _b++) {
var layerData = layersData_2[_b];
for (var _c = 0, _d = layerData.channels; _c < _d.length; _c++) {
var channel = _d[_c];
writeUint16(writer, channel.compression);
if (channel.buffer) {
writeBytes(writer, channel.buffer);
}
}
}
}, true, options.psb);
}
function writeLayerMaskData(writer, _a, layerData) {
var mask = _a.mask;
writeSection(writer, 1, function () {
if (!mask)
return;
var m = layerData.mask || {};
writeInt32(writer, m.top);
writeInt32(writer, m.left);
writeInt32(writer, m.bottom);
writeInt32(writer, m.right);
writeUint8(writer, mask.defaultColor);
var params = 0;
if (mask.userMaskDensity !== undefined)
params |= 1 /* MaskParams.UserMaskDensity */;
if (mask.userMaskFeather !== undefined)
params |= 2 /* MaskParams.UserMaskFeather */;
if (mask.vectorMaskDensity !== undefined)
params |= 4 /* MaskParams.VectorMaskDensity */;
if (mask.vectorMaskFeather !== undefined)
params |= 8 /* MaskParams.VectorMaskFeather */;
var flags = 0;
if (mask.disabled)
flags |= 2 /* LayerMaskFlags.LayerMaskDisabled */;
if (mask.positionRelativeToLayer)
flags |= 1 /* LayerMaskFlags.PositionRelativeToLayer */;
if (mask.fromVectorData)
flags |= 8 /* LayerMaskFlags.LayerMaskFromRenderingOtherData */;
if (params)
flags |= 16 /* LayerMaskFlags.MaskHasParametersAppliedToIt */;
writeUint8(writer, flags);
if (params) {
writeUint8(writer, params);
if (mask.userMaskDensity !== undefined)
writeUint8(writer, Math.round(mask.userMaskDensity * 0xff));
if (mask.userMaskFeather !== undefined)
writeFloat64(writer, mask.userMaskFeather);
if (mask.vectorMaskDensity !== undefined)
writeUint8(writer, Math.round(mask.vectorMaskDensity * 0xff));
if (mask.vectorMaskFeather !== undefined)
writeFloat64(writer, mask.vectorMaskFeather);
}
// TODO: handle rest of the fields
writeZeros(writer, 2);
});
}
function writeLayerBlendingRanges(writer, psd) {
writeSection(writer, 1, function () {
writeUint32(writer, 65535);
writeUint32(writer, 65535);
var channels = psd.channels || 0; // TODO: use always 4 instead ?
// channels = 4; // TESTING
for (var i = 0; i < channels; i++) {
writeUint32(writer, 65535);
writeUint32(writer, 65535);
}
});
}
function writeGlobalLayerMaskInfo(writer, info) {
writeSection(writer, 1, function () {
if (info) {
writeUint16(writer, info.overlayColorSpace);
writeUint16(writer, info.colorSpace1);
writeUint16(writer, info.colorSpace2);
writeUint16(writer, info.colorSpace3);
writeUint16(writer, info.colorSpace4);
writeUint16(writer, info.opacity * 0xff);
writeUint8(writer, info.kind);
writeZeros(writer, 3);
}
});
}
function writeAdditionalLayerInfo(writer, target, psd, options) {
var _loop_4 = function (handler) {
var key = handler.key;
if (key === 'Txt2' && options.invalidateTextLayers)
return "continue";
if (key === 'vmsk' && options.psb)
key = 'vsms';
if (handler.has(target)) {
var large = options.psb && largeAdditionalInfoKeys.indexOf(key) !== -1;
writeSignature(writer, large ? '8B64' : '8BIM');
writeSignature(writer, key);
var fourBytes = key === 'Txt2' || key === 'luni' || key === 'vmsk' || key === 'artb' || key === 'artd' ||
key === 'vogk' || key === 'SoLd' || key === 'lnk2' || key === 'vscg' || key === 'vsms' || key === 'GdFl' ||
key === 'lmfx' || key === 'lrFX' || key === 'cinf' || key === 'PlLd' || key === 'Anno';
writeSection(writer, fourBytes ? 4 : 2, function () {
handler.write(writer, target, psd, options);
}, key !== 'Txt2' && key !== 'cinf' && key !== 'extn', large);
}
};
for (var _i = 0, infoHandlers_1 = infoHandlers; _i < infoHandlers_1.length; _i++) {
var handler = infoHandlers_1[_i];
_loop_4(handler);
}
}
function addChildren(layers, children) {
if (!children)
return;
for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
var c = children_1[_i];
if (c.children && c.canvas)
throw new Error("Invalid layer, cannot have both 'canvas' and 'children' properties");
if (c.children && c.imageData)
throw new Error("Invalid layer, cannot have both 'imageData' and 'children' properties");
if (c.children) {
layers.push({
name: '</Layer group>',
sectionDivider: {
type: 3 /* SectionDividerType.BoundingSectionDivider */,
},
// TESTING
// nameSource: 'lset',
// id: [4, 0, 0, 8, 11, 0, 0, 0, 0, 14][layers.length] || 0,
// layerColor: 'none',
// timestamp: [1611346817.349021, 0, 0, 1611346817.349175, 1611346817.3491833, 0, 0, 0, 0, 1611346817.349832][layers.length] || 0,
// protected: {},
// referencePoint: { x: 0, y: 0 },
});
addChildren(layers, c.children);
layers.push(__assign({ sectionDivider: {
type: c.opened === false ? 2 /* SectionDividerType.ClosedFolder */ : 1 /* SectionDividerType.OpenFolder */,
key: fromBlendMode[c.blendMode] || 'pass',
subType: 0,
} }, c));
}
else {
layers.push(__assign({}, c));
}
}
}
function resizeBuffer(writer, size) {
var newLength = writer.buffer.byteLength;
do {
newLength *= 2;
} while (size > newLength);
var newBuffer = new ArrayBuffer(newLength);
var newBytes = new Uint8Array(newBuffer);
var oldBytes = new Uint8Array(writer.buffer);
newBytes.set(oldBytes);
writer.buffer = newBuffer;
writer.view = new DataView(writer.buffer);
}
function ensureSize(writer, size) {
if (size > writer.buffer.byteLength) {
resizeBuffer(writer, size);
}
}
function addSize(writer, size) {
var offset = writer.offset;
ensureSize(writer, writer.offset += size);
return offset;
}
function createThumbnail(psd) {
var canvas = createCanvas(10, 10);
var scale = 1;
if (psd.width > psd.height) {
canvas.width = 160;
canvas.height = Math.floor(psd.height * (canvas.width / psd.width));
scale = canvas.width / psd.width;
}
else {
canvas.height = 160;
canvas.width = Math.floor(psd.width * (canvas.height / psd.height));
scale = canvas.height / psd.height;
}
var context = canvas.getContext('2d');
context.scale(scale, scale);
if (psd.imageData) {
var temp = createCanvas(psd.imageData.width, psd.imageData.height);
temp.getContext('2d').putImageData(psd.imageData, 0, 0);
context.drawImage(temp, 0, 0);
}
else if (psd.canvas) {
context.drawImage(psd.canvas, 0, 0);
}
return canvas;
}
function getChannels(tempBuffer, layer, background, options) {
var layerData = getLayerChannels(tempBuffer, layer, background, options);
var mask = layer.mask;
if (mask) {
var top_2 = mask.top | 0;
var left = mask.left | 0;
var right = mask.right | 0;
var bottom = mask.bottom | 0;
var _a = getLayerDimentions(mask), width = _a.width, height = _a.height;
var imageData = mask.imageData;
if (!imageData && mask.canvas && width && height) {
imageData = mask.canvas.getContext('2d').getImageData(0, 0, width, height);
}
if (width && height && imageData) {
right = left + width;
bottom = top_2 + height;
if (imageData.width !== width || imageData.height !== height) {
throw new Error('Invalid imageData dimentions');
}
var buffer = void 0;
var compression = void 0;
if (RAW_IMAGE_DATA && layer.maskDataRaw) {
// console.log('written raw layer image data');
buffer = layer.maskDataRaw;
compression = 1 /* Compression.RleCompressed */;
}
else if (options.compress) {
buffer = writeDataZipWithoutPrediction(imageData, [0]);
compression = 2 /* Compression.ZipWithoutPrediction */;
}
else {
buffer = writeDataRLE(tempBuffer, imageData, [0], !!options.psb);
compression = 1 /* Compression.RleCompressed */;
}
layerData.mask = { top: top_2, left: left, right: right, bottom: bottom };
layerData.channels.push({ channelId: -2 /* ChannelID.UserMask */, compression: compression, buffer: buffer, length: 2 + buffer.length });
}
else {
layerData.mask = { top: 0, left: 0, right: 0, bottom: 0 };
layerData.channels.push({ channelId: -2 /* ChannelID.UserMask */, compression: 0 /* Compression.RawData */, buffer: new Uint8Array(0), length: 0 });
}
}
return layerData;
}
function getLayerDimentions(_a) {
var canvas = _a.canvas, imageData = _a.imageData;
return imageData || canvas || { width: 0, height: 0 };
}
function cropImageData(data, left, top, width, height) {
var croppedData = createImageData(width, height);
var srcData = data.data;
var dstData = croppedData.data;
for (var y = 0; y < height; y++) {
for (var x = 0; x < width; x++) {
var src = ((x + left) + (y + top) * width) * 4;
var dst = (x + y * width) * 4;
dstData[dst] = srcData[src];
dstData[dst + 1] = srcData[src + 1];
dstData[dst + 2] = srcData[src + 2];
dstData[dst + 3] = srcData[src + 3];
}
}
return croppedData;
}
function getLayerChannels(tempBuffer, layer, background, options) {
var _a;
var top = layer.top | 0;
var left = layer.left | 0;
var right = layer.right | 0;
var bottom = layer.bottom | 0;
var channels = [
{ channelId: -1 /* ChannelID.Transparency */, compression: 0 /* Compression.RawData */, buffer: undefined, length: 2 },
{ channelId: 0 /* ChannelID.Color0 */, compression: 0 /* Compression.RawData */, buffer: undefined, length: 2 },
{ channelId: 1 /* ChannelID.Color1 */, compression: 0 /* Compression.RawData */, buffer: undefined, length: 2 },
{ channelId: 2 /* ChannelID.Color2 */, compression: 0 /* Compression.RawData */, buffer: undefined, length: 2 },
];
var _b = getLayerDimentions(layer), width = _b.width, height = _b.height;
if (!(layer.canvas || layer.imageData) || !width || !height) {
right = left;
bottom = top;
return { layer: layer, top: top, left: left, right: right, bottom: bottom, channels: channels };
}
right = left + width;
bottom = top + height;
var data = layer.imageData || layer.canvas.getContext('2d').getImageData(0, 0, width, height);
if (options.trimImageData) {
var trimmed = trimData(data);
if (trimmed.left !== 0 || trimmed.top !== 0 || trimmed.right !== data.width || trimmed.bottom !== data.height) {
left += trimmed.left;
top += trimmed.top;
right -= (data.width - trimmed.right);
bottom -= (data.height - trimmed.bottom);
width = right - left;
height = bottom - top;
if (!width || !height) {
return { layer: layer, top: top, left: left, right: right, bottom: bottom, channels: channels };
}
if (layer.imageData) {
data = cropImageData(data, trimmed.left, trimmed.top, width, height);
}
else {
data = layer.canvas.getContext('2d').getImageData(trimmed.left, trimmed.top, width, height);
}
}
}
var channelIds = [
0 /* ChannelID.Color0 */,
1 /* ChannelID.Color1 */,
2 /* ChannelID.Color2 */,
];
if (!background || options.noBackground || layer.mask || hasAlpha(data) || (RAW_IMAGE_DATA && ((_a = layer.imageDataRaw) === null || _a === void 0 ? void 0 : _a['-1']))) {
channelIds.unshift(-1 /* ChannelID.Transparency */);
}
channels = channelIds.map(function (channelId) {
var offset = offsetForChannel(channelId, false); // TODO: psd.colorMode === ColorMode.CMYK);
var buffer;
var compression;
if (RAW_IMAGE_DATA && layer.imageDataRaw) {
// console.log('written raw layer image data');
buffer = layer.imageDataRaw[channelId];
compression = 1 /* Compression.RleCompressed */;
}
else if (options.compress) {
buffer = writeDataZipWithoutPrediction(data, [offset]);
compression = 2 /* Compression.ZipWithoutPrediction */;
}
else {
buffer = writeDataRLE(tempBuffer, data, [offset], !!options.psb);
compression = 1 /* Compression.RleCompressed */;
}
return { channelId: channelId, compression: compression, buffer: buffer, length: 2 + buffer.length };
});
return { layer: layer, top: top, left: left, right: right, bottom: bottom, channels: channels };
}
function isRowEmpty(_a, y, left, right) {
var data = _a.data, width = _a.width;
var start = ((y * width + left) * 4 + 3) | 0;
var end = (start + (right - left) * 4) | 0;
for (var i = start; i < end; i = (i + 4) | 0) {
if (data[i] !== 0) {
return false;
}
}
return true;
}
function isColEmpty(_a, x, top, bottom) {
var data = _a.data, width = _a.width;
var stride = (width * 4) | 0;
var start = (top * stride + x * 4 + 3) | 0;
for (var y = top, i = start; y < bottom; y++, i = (i + stride) | 0) {
if (data[i] !== 0) {
return false;
}
}
return true;
}
function trimData(data) {
var top = 0;
var left = 0;
var right = data.width;
var bottom = data.height;
while (top < bottom && isRowEmpty(data, top, left, right))
top++;
while (bottom > top && isRowEmpty(data, bottom - 1, left, right))
bottom--;
while (left < right && isColEmpty(data, left, top, bottom))
left++;
while (right > left && isColEmpty(data, right - 1, top, bottom))
right--;
return { top: top, left: left, right: right, bottom: bottom };
}
export function writeColor(writer, color) {
if (!color) {
writeUint16(writer, 0 /* ColorSpace.RGB */);
writeZeros(writer, 8);
}
else if ('r' in color) {
writeUint16(writer, 0 /* ColorSpace.RGB */);
writeUint16(writer, Math.round(color.r * 257));
writeUint16(writer, Math.round(color.g * 257));
writeUint16(writer, Math.round(color.b * 257));
writeUint16(writer, 0);
}
else if ('fr' in color) {
writeUint16(writer, 0 /* ColorSpace.RGB */);
writeUint16(writer, Math.round(color.fr * 255 * 257));
writeUint16(writer, Math.round(color.fg * 255 * 257));
writeUint16(writer, Math.round(color.fb * 255 * 257));
writeUint16(writer, 0);
}
else if ('l' in color) {
writeUint16(writer, 7 /* ColorSpace.Lab */);
writeInt16(writer, Math.round(color.l * 10000));
writeInt16(writer, Math.round(color.a < 0 ? (color.a * 12800) : (color.a * 12700)));
writeInt16(writer, Math.round(color.b < 0 ? (color.b * 12800) : (color.b * 12700)));
writeUint16(writer, 0);
}
else if ('h' in color) {
writeUint16(writer, 1 /* ColorSpace.HSB */);
writeUint16(writer, Math.round(color.h * 0xffff));
writeUint16(writer, Math.round(color.s * 0xffff));
writeUint16(writer, Math.round(color.b * 0xffff));
writeUint16(writer, 0);
}
else if ('c' in color) {
writeUint16(writer, 2 /* ColorSpace.CMYK */);
writeUint16(writer, Math.round(color.c * 257));
writeUint16(writer, Math.round(color.m * 257));
writeUint16(writer, Math.round(color.y * 257));
writeUint16(writer, Math.round(color.k * 257));
}
else {
writeUint16(writer, 8 /* ColorSpace.Grayscale */);
writeUint16(writer, Math.round(color.k * 10000 / 255));
writeZeros(writer, 6);
}
}
//# sourceMappingURL=psdWriter.js.map

Some files were not shown because too many files have changed in this diff Show More