From 63c090139358622f2a83eb1ead6652fe3cf43fa4 Mon Sep 17 00:00:00 2001 From: yourfriendoss Date: Sat, 27 Sep 2025 18:20:54 +0300 Subject: [PATCH] first commit --- .gitignore | 37 ++++++++ LICENSE | 5 ++ README.md | 5 ++ bun.lock | 156 +++++++++++++++++++++++++++++++++ index.js | 184 +++++++++++++++++++++++++++++++++++++++ lib/image2json.js | 215 ++++++++++++++++++++++++++++++++++++++++++++++ lib/pack.js | 174 +++++++++++++++++++++++++++++++++++++ lib/tiny_lz4.js | 145 +++++++++++++++++++++++++++++++ package.json | 17 ++++ tsconfig.json | 28 ++++++ 10 files changed, 966 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 bun.lock create mode 100644 index.js create mode 100644 lib/image2json.js create mode 100644 lib/pack.js create mode 100644 lib/tiny_lz4.js create mode 100644 package.json create mode 100644 tsconfig.json diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e46cc9d --- /dev/null +++ b/.gitignore @@ -0,0 +1,37 @@ +# dependencies (bun install) +node_modules + +# output +out +dist +*.tgz + +# code coverage +coverage +*.lcov + +# logs +logs +_.log +report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json + +# dotenv environment variable files +.env +.env.development.local +.env.test.local +.env.production.local +.env.local + +# caches +.eslintcache +.cache +*.tsbuildinfo + +# IntelliJ based IDEs +.idea + +# Finder (MacOS) folder config +.DS_Store + +*-cache.json +figura-* diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d43c84e --- /dev/null +++ b/LICENSE @@ -0,0 +1,5 @@ +Copyright © 2025 sad.ovh. All rights reserved. + +Permission is granted to use, copy, and distribute this work for personal or internal use only. Commercial use is not permitted unless explicit written permission is obtained from the author. If you wish to use this work for non-commercial purposes, you may request permission from the author, who may grant a non-commercial license at their discretion. + +THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND. diff --git a/README.md b/README.md new file mode 100644 index 0000000..3f9d1cd --- /dev/null +++ b/README.md @@ -0,0 +1,5 @@ +# figura-tools + +lots of different stuff I (Sophie) use for figura + +code is all ARR, apart from lib/image2json.js which is MIT licensed diff --git a/bun.lock b/bun.lock new file mode 100644 index 0000000..d139218 --- /dev/null +++ b/bun.lock @@ -0,0 +1,156 @@ +{ + "lockfileVersion": 1, + "workspaces": { + "": { + "name": "figura-tools", + "dependencies": { + "@napi-rs/canvas": "^0.1.80", + "dotenv": "^17.2.2", + "figura": "github:fucksophie/figuramc", + }, + "devDependencies": { + "@types/bun": "latest", + }, + "peerDependencies": { + "typescript": "^5", + }, + }, + }, + "packages": { + "@azure/msal-common": ["@azure/msal-common@14.16.1", "", {}, "sha512-nyxsA6NA4SVKh5YyRpbSXiMr7oQbwark7JU9LMeg6tJYTSPyAGkdx61wPT4gyxZfxlSxMMEyAsWaubBlNyIa1w=="], + + "@azure/msal-node": ["@azure/msal-node@2.16.3", "", { "dependencies": { "@azure/msal-common": "14.16.1", "jsonwebtoken": "^9.0.0", "uuid": "^8.3.0" } }, "sha512-CO+SE4weOsfJf+C5LM8argzvotrXw252/ZU6SM2Tz63fEblhH1uuVaaO4ISYFuN4Q6BhTo7I3qIdi8ydUQCqhw=="], + + "@napi-rs/canvas": ["@napi-rs/canvas@0.1.80", "", { "optionalDependencies": { "@napi-rs/canvas-android-arm64": "0.1.80", "@napi-rs/canvas-darwin-arm64": "0.1.80", "@napi-rs/canvas-darwin-x64": "0.1.80", "@napi-rs/canvas-linux-arm-gnueabihf": "0.1.80", "@napi-rs/canvas-linux-arm64-gnu": "0.1.80", "@napi-rs/canvas-linux-arm64-musl": "0.1.80", "@napi-rs/canvas-linux-riscv64-gnu": "0.1.80", "@napi-rs/canvas-linux-x64-gnu": "0.1.80", "@napi-rs/canvas-linux-x64-musl": "0.1.80", "@napi-rs/canvas-win32-x64-msvc": "0.1.80" } }, "sha512-DxuT1ClnIPts1kQx8FBmkk4BQDTfI5kIzywAaMjQSXfNnra5UFU9PwurXrl+Je3bJ6BGsp/zmshVVFbCmyI+ww=="], + + "@napi-rs/canvas-android-arm64": ["@napi-rs/canvas-android-arm64@0.1.80", "", { "os": "android", "cpu": "arm64" }, "sha512-sk7xhN/MoXeuExlggf91pNziBxLPVUqF2CAVnB57KLG/pz7+U5TKG8eXdc3pm0d7Od0WreB6ZKLj37sX9muGOQ=="], + + "@napi-rs/canvas-darwin-arm64": ["@napi-rs/canvas-darwin-arm64@0.1.80", "", { "os": "darwin", "cpu": "arm64" }, "sha512-O64APRTXRUiAz0P8gErkfEr3lipLJgM6pjATwavZ22ebhjYl/SUbpgM0xcWPQBNMP1n29afAC/Us5PX1vg+JNQ=="], + + "@napi-rs/canvas-darwin-x64": ["@napi-rs/canvas-darwin-x64@0.1.80", "", { "os": "darwin", "cpu": "x64" }, "sha512-FqqSU7qFce0Cp3pwnTjVkKjjOtxMqRe6lmINxpIZYaZNnVI0H5FtsaraZJ36SiTHNjZlUB69/HhxNDT1Aaa9vA=="], + + "@napi-rs/canvas-linux-arm-gnueabihf": ["@napi-rs/canvas-linux-arm-gnueabihf@0.1.80", "", { "os": "linux", "cpu": "arm" }, "sha512-eyWz0ddBDQc7/JbAtY4OtZ5SpK8tR4JsCYEZjCE3dI8pqoWUC8oMwYSBGCYfsx2w47cQgQCgMVRVTFiiO38hHQ=="], + + "@napi-rs/canvas-linux-arm64-gnu": ["@napi-rs/canvas-linux-arm64-gnu@0.1.80", "", { "os": "linux", "cpu": "arm64" }, "sha512-qwA63t8A86bnxhuA/GwOkK3jvb+XTQaTiVML0vAWoHyoZYTjNs7BzoOONDgTnNtr8/yHrq64XXzUoLqDzU+Uuw=="], + + "@napi-rs/canvas-linux-arm64-musl": ["@napi-rs/canvas-linux-arm64-musl@0.1.80", "", { "os": "linux", "cpu": "arm64" }, "sha512-1XbCOz/ymhj24lFaIXtWnwv/6eFHXDrjP0jYkc6iHQ9q8oXKzUX1Lc6bu+wuGiLhGh2GS/2JlfORC5ZcXimRcg=="], + + "@napi-rs/canvas-linux-riscv64-gnu": ["@napi-rs/canvas-linux-riscv64-gnu@0.1.80", "", { "os": "linux", "cpu": "none" }, "sha512-XTzR125w5ZMs0lJcxRlS1K3P5RaZ9RmUsPtd1uGt+EfDyYMu4c6SEROYsxyatbbu/2+lPe7MPHOO/0a0x7L/gw=="], + + "@napi-rs/canvas-linux-x64-gnu": ["@napi-rs/canvas-linux-x64-gnu@0.1.80", "", { "os": "linux", "cpu": "x64" }, "sha512-BeXAmhKg1kX3UCrJsYbdQd3hIMDH/K6HnP/pG2LuITaXhXBiNdh//TVVVVCBbJzVQaV5gK/4ZOCMrQW9mvuTqA=="], + + "@napi-rs/canvas-linux-x64-musl": ["@napi-rs/canvas-linux-x64-musl@0.1.80", "", { "os": "linux", "cpu": "x64" }, "sha512-x0XvZWdHbkgdgucJsRxprX/4o4sEed7qo9rCQA9ugiS9qE2QvP0RIiEugtZhfLH3cyI+jIRFJHV4Fuz+1BHHMg=="], + + "@napi-rs/canvas-win32-x64-msvc": ["@napi-rs/canvas-win32-x64-msvc@0.1.80", "", { "os": "win32", "cpu": "x64" }, "sha512-Z8jPsM6df5V8B1HrCHB05+bDiCxjE9QA//3YrkKIdVDEwn5RKaqOxCJDRJkl48cJbylcrJbW4HxZbTte8juuPg=="], + + "@types/bun": ["@types/bun@1.2.22", "", { "dependencies": { "bun-types": "1.2.22" } }, "sha512-5A/KrKos2ZcN0c6ljRSOa1fYIyCKhZfIVYeuyb4snnvomnpFqC0tTsEkdqNxbAgExV384OETQ//WAjl3XbYqQA=="], + + "@types/node": ["@types/node@24.5.2", "", { "dependencies": { "undici-types": "~7.12.0" } }, "sha512-FYxk1I7wPv3K2XBaoyH2cTnocQEu8AOZ60hPbsyukMPLv5/5qr7V1i8PLHdl6Zf87I+xZXFvPCXYjiTFq+YSDQ=="], + + "@types/react": ["@types/react@19.1.14", "", { "dependencies": { "csstype": "^3.0.2" } }, "sha512-ukd93VGzaNPMAUPy0gRDSC57UuQbnH9Kussp7HBjM06YFi9uZTFhOvMSO2OKqXm1rSgzOE+pVx1k1PYHGwlc8Q=="], + + "@xboxreplay/errors": ["@xboxreplay/errors@0.1.0", "", {}, "sha512-Tgz1d/OIPDWPeyOvuL5+aai5VCcqObhPnlI3skQuf80GVF3k1I0lPCnGC+8Cm5PV9aLBT5m8qPcJoIUQ2U4y9g=="], + + "@xboxreplay/xboxlive-auth": ["@xboxreplay/xboxlive-auth@3.3.3", "", { "dependencies": { "@xboxreplay/errors": "^0.1.0", "axios": "^0.21.1" } }, "sha512-j0AU8pW10LM8O68CTZ5QHnvOjSsnPICy0oQcP7zyM7eWkDQ/InkiQiirQKsPn1XRYDl4ccNu0WM582s3UKwcBg=="], + + "abort-controller": ["abort-controller@3.0.0", "", { "dependencies": { "event-target-shim": "^5.0.0" } }, "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg=="], + + "ajv": ["ajv@6.12.6", "", { "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g=="], + + "axios": ["axios@0.21.4", "", { "dependencies": { "follow-redirects": "^1.14.0" } }, "sha512-ut5vewkiu8jjGBdqpM44XxjuCjq9LAKeHVmoVfHVzy8eHgxxq8SbAVQNovDA8mVi05kP0Ea/n/UzcSHcTJQfNg=="], + + "base64-js": ["base64-js@1.5.1", "", {}, "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="], + + "buffer": ["buffer@6.0.3", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.2.1" } }, "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA=="], + + "buffer-equal-constant-time": ["buffer-equal-constant-time@1.0.1", "", {}, "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA=="], + + "bun-types": ["bun-types@1.2.22", "", { "dependencies": { "@types/node": "*" }, "peerDependencies": { "@types/react": "^19" } }, "sha512-hwaAu8tct/Zn6Zft4U9BsZcXkYomzpHJX28ofvx7k0Zz2HNz54n1n+tDgxoWFGB4PcFvJXJQloPhaV2eP3Q6EA=="], + + "csstype": ["csstype@3.1.3", "", {}, "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw=="], + + "debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], + + "dotenv": ["dotenv@17.2.2", "", {}, "sha512-Sf2LSQP+bOlhKWWyhFsn0UsfdK/kCWRv1iuA2gXAwt3dyNabr6QSj00I2V10pidqz69soatm9ZwZvpQMTIOd5Q=="], + + "ecdsa-sig-formatter": ["ecdsa-sig-formatter@1.0.11", "", { "dependencies": { "safe-buffer": "^5.0.1" } }, "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ=="], + + "event-target-shim": ["event-target-shim@5.0.1", "", {}, "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ=="], + + "events": ["events@3.3.0", "", {}, "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q=="], + + "fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="], + + "fast-json-stable-stringify": ["fast-json-stable-stringify@2.1.0", "", {}, "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw=="], + + "figura": ["figura@github:fucksophie/figuramc#db0a77d", { "dependencies": { "luaparse": "^0.3.1", "prismarine-auth": "^2.7.0", "prismarine-nbt": "^2.7.0", "ws": "^8.18.3" } }, "fucksophie-figuramc-db0a77d"], + + "follow-redirects": ["follow-redirects@1.15.11", "", {}, "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ=="], + + "ieee754": ["ieee754@1.2.1", "", {}, "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA=="], + + "json-schema-traverse": ["json-schema-traverse@0.4.1", "", {}, "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg=="], + + "jsonwebtoken": ["jsonwebtoken@9.0.2", "", { "dependencies": { "jws": "^3.2.2", "lodash.includes": "^4.3.0", "lodash.isboolean": "^3.0.3", "lodash.isinteger": "^4.0.4", "lodash.isnumber": "^3.0.3", "lodash.isplainobject": "^4.0.6", "lodash.isstring": "^4.0.1", "lodash.once": "^4.0.0", "ms": "^2.1.1", "semver": "^7.5.4" } }, "sha512-PRp66vJ865SSqOlgqS8hujT5U4AOgMfhrwYIuIhfKaoSCZcirrmASQr8CX7cUg+RMih+hgznrjp99o+W4pJLHQ=="], + + "jwa": ["jwa@1.4.2", "", { "dependencies": { "buffer-equal-constant-time": "^1.0.1", "ecdsa-sig-formatter": "1.0.11", "safe-buffer": "^5.0.1" } }, "sha512-eeH5JO+21J78qMvTIDdBXidBd6nG2kZjg5Ohz/1fpa28Z4CcsWUzJ1ZZyFq/3z3N17aZy+ZuBoHljASbL1WfOw=="], + + "jws": ["jws@3.2.2", "", { "dependencies": { "jwa": "^1.4.1", "safe-buffer": "^5.0.1" } }, "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA=="], + + "lodash.includes": ["lodash.includes@4.3.0", "", {}, "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w=="], + + "lodash.isboolean": ["lodash.isboolean@3.0.3", "", {}, "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg=="], + + "lodash.isinteger": ["lodash.isinteger@4.0.4", "", {}, "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA=="], + + "lodash.isnumber": ["lodash.isnumber@3.0.3", "", {}, "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw=="], + + "lodash.isplainobject": ["lodash.isplainobject@4.0.6", "", {}, "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA=="], + + "lodash.isstring": ["lodash.isstring@4.0.1", "", {}, "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw=="], + + "lodash.once": ["lodash.once@4.1.1", "", {}, "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg=="], + + "lodash.reduce": ["lodash.reduce@4.6.0", "", {}, "sha512-6raRe2vxCYBhpBu+B+TtNGUzah+hQjVdu3E17wfusjyrXBka2nBS8OH/gjVZ5PvHOhWmIZTYri09Z6n/QfnNMw=="], + + "luaparse": ["luaparse@0.3.1", "", { "bin": { "luaparse": "bin/luaparse" } }, "sha512-b21h2bFEbtGXmVqguHogbyrMAA0wOHyp9u/rx+w6Yc9pW1t9YjhGUsp87lYcp7pFRqSWN/PhFkrdIqKEUzRjjQ=="], + + "macaddress": ["macaddress@0.5.3", "", {}, "sha512-vGBKTA+jwM4KgjGZ+S/8/Mkj9rWzePyGY6jManXPGhiWu63RYwW8dKPyk5koP+8qNVhPhHgFa1y/MJ4wrjsNrg=="], + + "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], + + "prismarine-auth": ["prismarine-auth@2.7.0", "", { "dependencies": { "@azure/msal-node": "^2.0.2", "@xboxreplay/xboxlive-auth": "^3.3.3", "debug": "^4.3.3", "smart-buffer": "^4.1.0", "uuid-1345": "^1.0.2" } }, "sha512-L8wTF6sdtnN6hViPNy+Nx39a8iQBwR5iO92AWCiym5cSXp/92pmnuwnTdcmNDWyqq6zY4hbibVGYhgLA1Ox8sQ=="], + + "prismarine-nbt": ["prismarine-nbt@2.7.0", "", { "dependencies": { "protodef": "^1.18.0" } }, "sha512-Du9OLQAcCj3y29YtewOJbbV4ARaSUEJiTguw0PPQbPBy83f+eCyDRkyBpnXTi/KPyEpgYCzsjGzElevLpFoYGQ=="], + + "process": ["process@0.11.10", "", {}, "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A=="], + + "protodef": ["protodef@1.19.0", "", { "dependencies": { "lodash.reduce": "^4.6.0", "protodef-validator": "^1.3.0", "readable-stream": "^4.4.0" } }, "sha512-94f3GR7pk4Qi5YVLaLvWBfTGUIzzO8hyo7vFVICQuu5f5nwKtgGDaeC1uXIu49s5to/49QQhEYeL0aigu1jEGA=="], + + "protodef-validator": ["protodef-validator@1.4.0", "", { "dependencies": { "ajv": "^6.5.4" }, "bin": { "protodef-validator": "cli.js" } }, "sha512-2y2coBolqCEuk5Kc3QwO7ThR+/7TZiOit4FrpAgl+vFMvq8w76nDhh09z08e2NQOdrgPLsN2yzXsvRvtADgUZQ=="], + + "punycode": ["punycode@2.3.1", "", {}, "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg=="], + + "readable-stream": ["readable-stream@4.7.0", "", { "dependencies": { "abort-controller": "^3.0.0", "buffer": "^6.0.3", "events": "^3.3.0", "process": "^0.11.10", "string_decoder": "^1.3.0" } }, "sha512-oIGGmcpTLwPga8Bn6/Z75SVaH1z5dUut2ibSyAMVhmUggWpmDn2dapB0n7f8nwaSiRtepAsfJyfXIO5DCVAODg=="], + + "safe-buffer": ["safe-buffer@5.2.1", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="], + + "semver": ["semver@7.7.2", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA=="], + + "smart-buffer": ["smart-buffer@4.2.0", "", {}, "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg=="], + + "string_decoder": ["string_decoder@1.3.0", "", { "dependencies": { "safe-buffer": "~5.2.0" } }, "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA=="], + + "typescript": ["typescript@5.9.2", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-CWBzXQrc/qOkhidw1OzBTQuYRbfyxDXJMVJ1XNwUHGROVmuaeiEm3OslpZ1RV96d7SKKjZKrSJu3+t/xlw3R9A=="], + + "undici-types": ["undici-types@7.12.0", "", {}, "sha512-goOacqME2GYyOZZfb5Lgtu+1IDmAlAEu5xnD3+xTzS10hT0vzpf0SPjkXwAw9Jm+4n/mQGDP3LO8CPbYROeBfQ=="], + + "uri-js": ["uri-js@4.4.1", "", { "dependencies": { "punycode": "^2.1.0" } }, "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg=="], + + "uuid": ["uuid@8.3.2", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg=="], + + "uuid-1345": ["uuid-1345@1.0.2", "", { "dependencies": { "macaddress": "^0.5.1" } }, "sha512-bA5zYZui+3nwAc0s3VdGQGBfbVsJLVX7Np7ch2aqcEWFi5lsAEcmO3+lx3djM1npgpZI8KY2FITZ2uYTnYUYyw=="], + + "ws": ["ws@8.18.3", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg=="], + } +} diff --git a/index.js b/index.js new file mode 100644 index 0000000..96cd1ce --- /dev/null +++ b/index.js @@ -0,0 +1,184 @@ +import { websocket, http, authenication } from "figura"; +import { createServer } from "http"; +import { pack_image } from "./lib/pack.js"; +import { imageToJson } from "./lib/image2json.js"; + +import "dotenv/config"; + +let [___, token] = await authenication.getToken(); + +if (!(await http.checkAuth(token))) { + await authenication.invalidateCache(); + let [u, t] = await authenication.getToken(); + uuid = u; + token = t; +} + +const ws = new websocket.WebsocketClient("wss://" + http.host + "/ws"); + +ws.addListener("connect", () => { + console.log("[WS] WS connection made"); +}); + +ws.addListener("auth", () => { + console.log("[WS] WS successfully authenticated!"); + + ["21f7143a-45cd-4995-b1e3-6c3c8602ef7c"].forEach((z) => { + ws.sub(z); + }); +}); + +function sendChunkedResponse(url, status, body) { + if (body.length <= 600) { + ws.ping(true, "httpResponse", [{ url, status, body }]); + } else { + const parts = []; + for (let i = 0; i < body.length; i += 600) { + parts.push(body.slice(i, i + 600)); + } + const amount = parts.length; + ws.ping(true, "httpResponse", [{ url, status, body_amount: amount }]); + + parts.forEach((chunk, index) => { + setTimeout( + () => { + ws.ping(true, "httpResponse", [ + { url, status, body_id: index + 1, body_text: chunk }, + ]); + }, + 1600 * (index + 1), + ); + }); + } +} +function sendChunkedImageResponse(url, status, imageBuffer) { + const CHUNK_SIZE = 600; + + if (status !== 200 || !imageBuffer) { + ws.ping(true, "imageResponse", [{ url, status }]); + return; + } + + const totalLength = imageBuffer.length || imageBuffer.byteLength; + if (totalLength <= CHUNK_SIZE) { + ws.ping(true, "imageResponse", [ + { url, status, image: Buffer.from(imageBuffer).toString("base64") }, + ]); + } else { + const parts = []; + for (let i = 0; i < totalLength; i += CHUNK_SIZE) { + const chunk = Buffer.from(imageBuffer).slice(i, i + CHUNK_SIZE); + parts.push(chunk.toString("base64")); + } + const amount = parts.length; + + ws.ping(true, "imageResponse", [{ url, status, image_amount: amount }]); + + parts.forEach((chunk, index) => { + setTimeout( + () => { + ws.ping(true, "imageResponse", [ + { url, status, image_id: index + 1, image_chunk: chunk }, + ]); + }, + 1600 * (index + 1), + ); + }); + } +} +ws.addListener("ping", async (id, uuid, args) => { + try { + if (id === http.hashFiguraString("httpGet")) { + const url = args[0]; + const res = await fetch(url); + const text = await res.text(); + sendChunkedResponse(url, res.status, text); + } + + if (id === http.hashFiguraString("httpPost")) { + const [url, payload] = args; + const res = await fetch(url, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(payload), + }); + const text = await res.text(); + sendChunkedResponse(url, res.status, text); + } + } catch (err) { + ws.ping(true, "httpResponse", [{ error: err.message }]); + } + try { + if (id === http.hashFiguraString("evilAssImageGet")) { + let [url, width, height] = args; + const res = await fetch(url); + if (!res.ok) { + ws.ping(true, "imageResponse", [{ url, status: res.status }]); + return; + } + + const blob = await res.blob(); + + const arrayBuffer = await blob.arrayBuffer(); + + const imageJson = await imageToJson(new Uint8Array(arrayBuffer), { + width: 20, + height: 20, + keepRatio: false, + }); + const packedImage = pack_image(imageJson.json); + sendChunkedImageResponse(url, 200, packedImage.toString("utf8")); + } + } catch (err) { + ws.ping(true, "imageResponse", [{ error: err.toString().slice(0, 256) }]); + } +}); + +ws.connect(); + +const server = createServer(async (req, res) => { + if (req.method === "POST" && req.url === "/data") { + const authHeader = req.headers["authorization"]; + + if (!authHeader || !authHeader.startsWith("Bearer ")) { + res.writeHead(401, { "Content-Type": "application/json" }); + res.end(JSON.stringify({ error: "Missing or invalid auth header" })); + return; + } + + const token = authHeader.substring("Bearer ".length).trim(); + if (token !== process.env.PASSWORD) { + res.writeHead(403, { "Content-Type": "application/json" }); + res.end(JSON.stringify({ error: "Forbidden" })); + return; + } + + let body = ""; + req.on("data", (chunk) => (body += chunk)); + req.on("end", () => { + try { + const json = JSON.parse(body); + + ws.ping(true, "data", [json]); + + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(JSON.stringify({ ok: true })); + } catch { + res.writeHead(400, { "Content-Type": "application/json" }); + res.end(JSON.stringify({ error: "Invalid JSON" })); + } + }); + } else { + res.writeHead(404, { "Content-Type": "application/json" }); + res.end(JSON.stringify({ error: "Not found" })); + } +}); + +server.listen(+process.env.PORT, process.env.HOST, () => { + console.log( + `[HTTP] Listening on http://${process.env.HOST}:${process.env.PORT} (POST /data)`, + ); + console.log( + `[HTTP] Use header: Authorization: Bearer ${process.env.PASSWORD}`, + ); +}); diff --git a/lib/image2json.js b/lib/image2json.js new file mode 100644 index 0000000..44112cf --- /dev/null +++ b/lib/image2json.js @@ -0,0 +1,215 @@ +/* +MIT License + +Copyright (c) 2024 Sol Toder + +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. + +Copy available at https://github.com/AjaxGb/mc-text-image/blob/master/LICENSE +*/ + +import * as fs from "fs"; + +import { createCanvas, loadImage } from "@napi-rs/canvas"; + +const BLOCK_CHAR = "\u2587"; +const SPACE_CHAR = "\u2007"; +const TRAILING_SPACE = new RegExp(SPACE_CHAR + "+$"); +const FONT_RATIO = 1.8; + +function parseSize(text) { + const parsed = parseInt(text); + return parsed > 0 ? parsed : 0; +} + +function calcSize(origW, origH, width, height, keepRatio, pixelShape) { + let w = width || origW; + let h = height || origH; + + if (keepRatio) { + const originRatio = origW / origH; + const currRatio = w / h; + + if (currRatio > originRatio || (origH && !origW)) { + w = (h * origW) / origH; + } else { + h = (w * origH) / origW; + } + } + + const pixelRatio = pixelShape === "font" ? FONT_RATIO : 1.0; + + return { + w: Math.round(w), + h: Math.round(h / pixelRatio), + unscaledH: Math.round(h), + origW, + origH, + }; +} + +function hexNibble(value) { + return value.toString(16).padStart(2, "0"); +} + +function makeHexColor(pixels, offset, cutoff) { + const a = pixels[offset + 3]; + if (a < cutoff) { + pixels[offset + 3] = 0; + return null; + } else { + pixels[offset + 3] = 255; + const r = pixels[offset + 0]; + const g = pixels[offset + 1]; + const b = pixels[offset + 2]; + return "#" + hexNibble(r) + hexNibble(g) + hexNibble(b); + } +} +export async function imageToJson(imageBuffer, options = {}) { + const { + width = null, + height = null, + keepRatio = true, + pixelShape = "square", + smoothing = null, + transparencyCutoff = 0, + stripSpace = false, + } = options; + + if (!imageBuffer || !(imageBuffer instanceof Uint8Array)) { + console.error("imageToJson: Invalid imageBuffer provided."); + throw new Error(`Input must be a Buffer containing image data`); + } + + let image; + try { + image = await loadImage(imageBuffer); + } catch (err) { + console.error("imageToJson: Failed to load image from buffer.", err); + throw err; + } + if (!image || !image.width || !image.height) { + console.error( + "imageToJson: Loaded image is invalid or missing dimensions.", + ); + throw new Error("Loaded image is invalid or missing dimensions."); + } + const origW = image.width; + const origH = image.height; + + let sizeObj; + try { + sizeObj = calcSize(origW, origH, width, height, keepRatio, pixelShape); + } catch (err) { + console.error("imageToJson: Failed to calculate target size.", err); + throw err; + } + const { w, h } = sizeObj; + + let canvas, ctx; + try { + canvas = createCanvas(w, h); + ctx = canvas.getContext("2d"); + } catch (err) { + console.error("imageToJson: Failed to create canvas or context.", err); + throw err; + } + + try { + if (smoothing) { + ctx.imageSmoothingEnabled = true; + ctx.imageSmoothingQuality = smoothing; + } else { + ctx.imageSmoothingEnabled = false; + } + } catch (err) { + console.error("imageToJson: Failed to set image smoothing.", err); + throw err; + } + + try { + ctx.clearRect(0, 0, w, h); + ctx.drawImage(image, 0, 0, w, h); + } catch (err) { + console.error("imageToJson: Failed to draw image on canvas.", err); + throw err; + } + + let cutoff, imageData, pixels; + try { + cutoff = parseInt(transparencyCutoff) || 0; + imageData = ctx.getImageData(0, 0, w, h); + pixels = imageData.data; + } catch (err) { + console.error("imageToJson: Failed to get image data from canvas.", err); + throw err; + } + const json = []; + let currColor = null; + let currText = ""; + + const totalPixels = pixels.length / 4; + + for (let x = 0, i = 0; i < pixels.length; x++, i += 4) { + if (x >= w) { + if (stripSpace) { + currText = currText.replace(TRAILING_SPACE, ""); + } + currText += "\n"; + x = 0; + } + + let newColor; + try { + newColor = makeHexColor(pixels, i, cutoff); + } catch (err) { + console.error(`imageToJson: Error processing pixel at index ${i}.`, err); + throw err; + } + if (currColor && newColor && currColor != newColor) { + json.push({ text: currText, color: currColor }); + currText = ""; + } + + if (newColor) { + currColor = newColor; + currText += BLOCK_CHAR; + } else { + currText += SPACE_CHAR; + } + } + + if (stripSpace) { + currText = currText.replace(TRAILING_SPACE, ""); + } + + if (currText && currColor) { + json.push({ text: currText, color: currColor }); + } + + return { + json: json, + dimensions: { + width: w, + height: h, + originalWidth: origW, + originalHeight: origH, + }, + }; +} diff --git a/lib/pack.js b/lib/pack.js new file mode 100644 index 0000000..8dd63ac --- /dev/null +++ b/lib/pack.js @@ -0,0 +1,174 @@ +function hexToRgb(hex) { + hex = hex.replace(/^#/, ""); + if (hex.length === 3) { + hex = hex + .split("") + .map(function (x) { + return x + x; + }) + .join(""); + } + var num = parseInt(hex, 16); + return [(num >> 16) & 255, (num >> 8) & 255, num & 255]; +} + +function colorDistance(rgb1, rgb2) { + return Math.sqrt( + Math.pow(rgb1[0] - rgb2[0], 2) + + Math.pow(rgb1[1] - rgb2[1], 2) + + Math.pow(rgb1[2] - rgb2[2], 2), + ); +} + +function closestColor(targetHex, colorList) { + var targetRgb = hexToRgb(targetHex); + var minDist = Infinity; + var closest = null; + for (var i = 0; i < colorList.length; i++) { + var rgb = hexToRgb(colorList[i]); + var dist = colorDistance(targetRgb, rgb); + if (dist < minDist) { + minDist = dist; + closest = colorList[i]; + } + } + return closest; +} + +function middleColorsAndApproximations(colorList, count) { + if (!Array.isArray(colorList) || colorList.length === 0 || count < 1) { + return { + middleColors: [], + approximations: {}, + }; + } + + var rgbs = colorList.map(hexToRgb); + + var avg = [0, 0, 0]; + for (var i = 0; i < rgbs.length; i++) { + avg[0] += rgbs[i][0]; + avg[1] += rgbs[i][1]; + avg[2] += rgbs[i][2]; + } + avg[0] = Math.round(avg[0] / rgbs.length); + avg[1] = Math.round(avg[1] / rgbs.length); + avg[2] = Math.round(avg[2] / rgbs.length); + + if (count >= colorList.length) { + return { + middleColors: colorList.slice(), + approximations: Object.fromEntries(colorList.map((c) => [c, c])), + }; + } + + var colorDistances = colorList.map(function (hex, idx) { + return { + hex: hex, + dist: colorDistance(hexToRgb(hex), avg), + }; + }); + + colorDistances.sort(function (a, b) { + return a.dist - b.dist; + }); + + var middleColors = colorDistances.slice(0, count).map(function (obj) { + return obj.hex; + }); + + var approximations = {}; + for (var i = 0; i < colorList.length; i++) { + var hex = colorList[i]; + if (middleColors.indexOf(hex) !== -1) { + approximations[hex] = hex; + } else { + approximations[hex] = closestColor(hex, middleColors); + } + } + + return { + middleColors: middleColors, + approximations: approximations, + }; +} + +import * as fs from "fs/promises"; +import { compress } from "./tiny_lz4.js"; + +export function pack_image(blocks) { + const colors = middleColorsAndApproximations( + blocks.map((z) => z.color), + 300, + ); + const header = new Uint8Array(300 * 3 + 1 + 2); + const dv = new DataView(header.buffer); + dv.setUint16(0, blocks.length); + let idx = 2; + + colors.middleColors.forEach((z, i) => { + const [r, g, b] = hexToRgb(z); + dv.setUint8(idx + 1, r); + dv.setUint8(idx + 2, g); + dv.setUint8(idx + 3, b); + + idx += 3; + }); + + function pack_block(text, paletteIdx) { + let raw_bytes = []; + + text + .replaceAll("\n", "?") + .split("") + .forEach((z, i) => { + let id = i % 8; + if (id == 0) { + raw_bytes.push([]); + } + + raw_bytes.at(-1).push(z == "▇" ? 0 : 1); + }); + + let bytes = raw_bytes.map((z) => + z.reduce((acc, bit, i) => acc | (bit << (7 - i)), 0), + ); + + const final = new Uint8Array(3 + bytes.length); + const dv = new DataView(final.buffer); + + dv.setUint16(0, paletteIdx); + dv.setUint8(2, (bytes.length << 4) | ((8 - raw_bytes.at(-1).length) & 0xf)); + bytes.forEach((z, i) => { + dv.setUint8(i + 3, z); + }); + return final; + } + + const byte_blocks = []; + + blocks.forEach((z) => { + byte_blocks.push( + pack_block( + z.text, + colors.middleColors.indexOf(colors.approximations[z.color]), + ), + ); + }); + + const totalBlockBytes = byte_blocks + .map((z) => z.length) + .reduce((a, b) => a + b, 0); + const final = new Uint8Array(header.length + totalBlockBytes); + + final.set(header, 0); + + let offset = header.length; + byte_blocks.forEach((block) => { + final.set(block, offset); + offset += block.length; + }); + + const compressed = compress(final); + return compressed; +} diff --git a/lib/tiny_lz4.js b/lib/tiny_lz4.js new file mode 100644 index 0000000..edf85e6 --- /dev/null +++ b/lib/tiny_lz4.js @@ -0,0 +1,145 @@ +const MIN_MATCH = 3; +const MAX_OFFSET = 0xffff; + +function writeExtLen(out, n) { + while (n >= 255) { + out.push(255); + n -= 255; + } + out.push(n); +} + +function readExtLen(input, pos, base) { + let add = 0; + while (true) { + let b = input[pos++]; + add += b; + if (b < 255) break; + } + return [base + add, pos]; +} + +function findLongestMatch(data, pos, window) { + let n = data.length; + let max_off = Math.min(window, pos); + let best_len = 0; + let best_off = 0; + let max_match_len = n - pos; + if (max_match_len < MIN_MATCH) return [0, 0]; + + let start = pos - max_off; + for (let j = start; j < pos; j++) { + if (data[j] === data[pos]) { + let k = 0; + while (k < max_match_len && data[j + k] === data[pos + k]) { + k++; + } + if (k >= MIN_MATCH && k > best_len) { + best_len = k; + best_off = pos - j; + if (best_len >= 255 + MIN_MATCH) break; + } + } + } + return [best_off, best_len]; +} + +export function compress(input) { + if (!(input instanceof Uint8Array)) + throw new Error("compress expects Uint8Array"); + + let n = input.length; + let i = 0; + let anchor = 0; + let out = []; + let window = MAX_OFFSET; + + while (i < n) { + let [off, match_len] = findLongestMatch(input, i, window); + + if (match_len >= MIN_MATCH) { + let lit_len = i - anchor; + let lit_nibble = Math.min(lit_len, 15); + let match_nibble = Math.min(match_len - MIN_MATCH, 15); + let token = lit_nibble * 16 + match_nibble; + out.push(token); + + if (lit_len >= 15) { + writeExtLen(out, lit_len - 15); + } + + for (let k = anchor; k < i; k++) out.push(input[k]); + + out.push(off & 0xff, (off >> 8) & 0xff); + + let rem = match_len - MIN_MATCH; + if (rem >= 15) { + writeExtLen(out, rem - 15); + } + + i += match_len; + anchor = i; + } else { + i++; + } + } + + let final_lit = n - anchor; + let tok_lit = Math.min(final_lit, 15); + let token = tok_lit * 16; + out.push(token); + if (final_lit >= 15) { + writeExtLen(out, final_lit - 15); + } + for (let k = anchor; k < n; k++) out.push(input[k]); + + return Uint8Array.from(out); +} + +export function decompress(input) { + if (!(input instanceof Uint8Array)) + throw new Error("decompress expects Uint8Array"); + + let pos = 0; + let n = input.length; + let out = []; + + while (pos < n) { + let token = input[pos++]; + if (token === undefined) break; + + let lit_nibble = token >> 4; + let match_nibble = token & 0xf; + + let lit_len = lit_nibble; + if (lit_len === 15) { + [lit_len, pos] = readExtLen(input, pos, 15); + } + + for (let k = 0; k < lit_len; k++) { + out.push(input[pos++]); + } + + if (pos >= n) break; + + let off = input[pos] | (input[pos + 1] << 8); + pos += 2; + + let match_len = match_nibble + MIN_MATCH; + if (match_nibble === 15) { + let extra; + [extra, pos] = readExtLen(input, pos, 0); + match_len += extra; + } + + let sofarLen = out.length; + let match_start = sofarLen - off; + if (match_start < 0) throw new Error("Invalid offset"); + + for (let k = 0; k < match_len; k++) { + out.push(out[match_start + k]); + } + } + + return Uint8Array.from(out); +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..3216978 --- /dev/null +++ b/package.json @@ -0,0 +1,17 @@ +{ + "name": "figura-tools", + "module": "index.ts", + "type": "module", + "private": true, + "dependencies": { + "@napi-rs/canvas": "^0.1.80", + "dotenv": "^17.2.2", + "figura": "github:fucksophie/figuramc" + }, + "devDependencies": { + "@types/bun": "latest" + }, + "peerDependencies": { + "typescript": "^5" + } +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..9c62f74 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + // Environment setup & latest features + "lib": ["ESNext"], + "target": "ESNext", + "module": "ESNext", + "moduleDetection": "force", + "jsx": "react-jsx", + "allowJs": true, + + // Bundler mode + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "verbatimModuleSyntax": true, + "noEmit": true, + + // Best practices + "strict": true, + "skipLibCheck": true, + "noFallthroughCasesInSwitch": true, + "noUncheckedIndexedAccess": true, + + // Some stricter flags (disabled by default) + "noUnusedLocals": false, + "noUnusedParameters": false, + "noPropertyAccessFromIndexSignature": false + } +}