diff --git a/backend/email.js b/backend/email.js new file mode 100644 index 0000000..4f57c17 --- /dev/null +++ b/backend/email.js @@ -0,0 +1,45 @@ +const nodemailer = require("nodemailer"); +const fs = require("fs"); +const path = require("path"); +require("dotenv").config(); + +/* ---------- TRANSPORTER ---------- */ +const transporter = nodemailer.createTransport({ + host: process.env.SMTP_HOST, + port: process.env.SMTP_PORT, + secure: false, + auth: { + user: process.env.SMTP_USER, + pass: process.env.SMTP_PASS, + }, +}); + +/* ---------- SEND EMAIL ---------- */ +async function sendConfirmationEmail(to, teamName) { + try { + const templatePath = path.join( + __dirname, + "templates", + "email.html" + ); + + let html = fs.readFileSync(templatePath, "utf-8"); + + // Replace placeholders + html = html.replace(/{{TEAM_NAME}}/g, teamName); + + await transporter.sendMail({ + from: `"Hackathon Team" <${process.env.SMTP_USER}>`, + to, + subject: "Hackathon Registration Confirmation", + html, + }); + + console.log("✔ Confirmation email sent to:", to); + } catch (err) { + console.error("❌ Email sending failed:", err); + throw err; + } +} + +module.exports = { sendConfirmationEmail }; diff --git a/backend/node_modules/.package-lock.json b/backend/node_modules/.package-lock.json new file mode 100644 index 0000000..29b48a8 --- /dev/null +++ b/backend/node_modules/.package-lock.json @@ -0,0 +1,1000 @@ +{ + "name": "backend", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/@supabase/auth-js": { + "version": "2.87.1", + "resolved": "https://registry.npmjs.org/@supabase/auth-js/-/auth-js-2.87.1.tgz", + "integrity": "sha512-6RDeOf5TVoaXFtEstN188ykp3pXLZaU9qoAWfx8dc50FFAAqt+kcFJ96V0IvSmcpb4mDAWcpTJ7BegmVDn/WIw==", + "license": "MIT", + "dependencies": { + "tslib": "2.8.1" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@supabase/functions-js": { + "version": "2.87.1", + "resolved": "https://registry.npmjs.org/@supabase/functions-js/-/functions-js-2.87.1.tgz", + "integrity": "sha512-rWmYo4gRD0XAjMhYDlz7IH67bp4TIQ1UE4VqwIQtl1gGPwtLDq6wcRnu7jLKlXx0Gtrknw/eoiHYG9//XrCTzQ==", + "license": "MIT", + "dependencies": { + "tslib": "2.8.1" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@supabase/postgrest-js": { + "version": "2.87.1", + "resolved": "https://registry.npmjs.org/@supabase/postgrest-js/-/postgrest-js-2.87.1.tgz", + "integrity": "sha512-Yzu5eL3iGmZW0C/8x+vEojAOou63FI9oVw8HI8YOq63+5yM8g8aGh7Y1E2vbXFb7+gHGsPqLnaC6dPhrYt7qBA==", + "license": "MIT", + "dependencies": { + "tslib": "2.8.1" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@supabase/realtime-js": { + "version": "2.87.1", + "resolved": "https://registry.npmjs.org/@supabase/realtime-js/-/realtime-js-2.87.1.tgz", + "integrity": "sha512-XvLtEznxmYZXA7LYuy5zbSXpSYjDLJq2wQeRh3MzON2OR4U8Kq+RtPz2E2Wi8HEzvBfsc+nNu1TG8LQ9+3DRkA==", + "license": "MIT", + "dependencies": { + "@types/phoenix": "^1.6.6", + "@types/ws": "^8.18.1", + "tslib": "2.8.1", + "ws": "^8.18.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@supabase/storage-js": { + "version": "2.87.1", + "resolved": "https://registry.npmjs.org/@supabase/storage-js/-/storage-js-2.87.1.tgz", + "integrity": "sha512-0Uc8tNV4yzkNNmp1inpXru0RB4a7ECq05G2S6BDvSpMxTxJrDVJ4vVDwyhqB8ZZ+O9+8prHaQYoByQeuDnwpFQ==", + "license": "MIT", + "dependencies": { + "iceberg-js": "^0.8.1", + "tslib": "2.8.1" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@supabase/supabase-js": { + "version": "2.87.1", + "resolved": "https://registry.npmjs.org/@supabase/supabase-js/-/supabase-js-2.87.1.tgz", + "integrity": "sha512-tVgqZqnHZVum584KuUKSQZgcy6ZkhVd6gG8QWg2QfIXH9HmXdamauxdVsLXwaNPJxEdOyfAfwIyi5XUsiVYWtg==", + "license": "MIT", + "dependencies": { + "@supabase/auth-js": "2.87.1", + "@supabase/functions-js": "2.87.1", + "@supabase/postgrest-js": "2.87.1", + "@supabase/realtime-js": "2.87.1", + "@supabase/storage-js": "2.87.1" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@types/node": { + "version": "25.0.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-25.0.0.tgz", + "integrity": "sha512-rl78HwuZlaDIUSeUKkmogkhebA+8K1Hy7tddZuJ3D0xV8pZSfsYGTsliGUol1JPzu9EKnTxPC4L1fiWouStRew==", + "license": "MIT", + "dependencies": { + "undici-types": "~7.16.0" + } + }, + "node_modules/@types/phoenix": { + "version": "1.6.7", + "resolved": "https://registry.npmjs.org/@types/phoenix/-/phoenix-1.6.7.tgz", + "integrity": "sha512-oN9ive//QSBkf19rfDv45M7eZPi0eEXylht2OLEXicu5b4KoQ1OzXIw+xDSGWxSxe1JmepRR/ZH283vsu518/Q==", + "license": "MIT" + }, + "node_modules/@types/ws": { + "version": "8.18.1", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz", + "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/body-parser": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.1.tgz", + "integrity": "sha512-nfDwkulwiZYQIGwxdy0RUmowMhKcFVcYXUU7m4QlKYim1rUtg83xm2yjZ40QjDuc291AJjjeSc9b++AWHSgSHw==", + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^1.0.5", + "debug": "^4.4.3", + "http-errors": "^2.0.0", + "iconv-lite": "^0.7.0", + "on-finished": "^2.4.1", + "qs": "^6.14.0", + "raw-body": "^3.0.1", + "type-is": "^2.0.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/content-disposition": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.1.tgz", + "integrity": "sha512-oIXISMynqSqm241k6kcQ5UwttDILMK4BiurCfGEREw6+X9jkkpEe5T9FZaApyLGGOnFuyMWZpdolTXMtvEJ08Q==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/cors": { + "version": "2.8.5", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", + "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/dotenv": { + "version": "17.2.3", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.2.3.tgz", + "integrity": "sha512-JVUnt+DUIzu87TABbhPmNfVdBDt18BLOWjMUFJMSi/Qqg7NTYtabbvSNJGOJ7afbRuv9D/lngizHtP7QyLQ+9w==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz", + "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==", + "license": "MIT", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.2.1", + "content-disposition": "^1.0.0", + "content-type": "^1.0.5", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "depd": "^2.0.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.7", + "qs": "^6.14.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.0.1", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/finalhandler": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", + "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/iceberg-js": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/iceberg-js/-/iceberg-js-0.8.1.tgz", + "integrity": "sha512-1dhVQZXhcHje7798IVM+xoo/1ZdVfzOMIc8/rgVSijRK38EDqOJoGula9N/8ZI5RD8QTxNQtK/Gozpr+qUqRRA==", + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/iconv-lite": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.1.tgz", + "integrity": "sha512-2Tth85cXwGFHfvRgZWszZSvdo+0Xsqmw8k8ZwxScfcBneNUraK+dxRxRm24nszx80Y0TVio8kKLt5sLE7ZCLlw==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "license": "MIT" + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz", + "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", + "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/nodemailer": { + "version": "7.0.11", + "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-7.0.11.tgz", + "integrity": "sha512-gnXhNRE0FNhD7wPSCGhdNh46Hs6nm+uTyg+Kq0cZukNQiYdnCsoQjodNP9BQVG9XrcK/v6/MgpAPBUFyzh9pvw==", + "license": "MIT-0", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.3.0.tgz", + "integrity": "sha512-7jdwVIRtsP8MYpdXSwOS0YdD0Du+qOoF/AEPIt88PcCFrZCzx41oxku1jD88hZBwbNUIEfpqvuhjFaMAqMTWnA==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/qs": { + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.0.tgz", + "integrity": "sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", + "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/router": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/send": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.0.tgz", + "integrity": "sha512-uaW0WwXKpL9blXE2o0bRhoL2EGXIrZxQ2ZQ4mgcfoBxdFmQold+qWsD2jLrfZ0trjKL6vOw0j//eAwcALFjKSw==", + "license": "MIT", + "dependencies": { + "debug": "^4.3.5", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "mime-types": "^3.0.1", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/serve-static": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.0.tgz", + "integrity": "sha512-61g9pCh0Vnh7IutZjtLGGpTA355+OPn2TyDv/6ivP2h/AdAVX9azsoxmg2/M6nZeQZNYBEwIcsne1mJd9oQItQ==", + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", + "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD" + }, + "node_modules/type-is": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.1.tgz", + "integrity": "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==", + "license": "MIT", + "dependencies": { + "content-type": "^1.0.5", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/undici-types": { + "version": "7.16.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz", + "integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==", + "license": "MIT" + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + }, + "node_modules/ws": { + "version": "8.18.3", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz", + "integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + } + } +} diff --git a/backend/node_modules/@supabase/auth-js/LICENSE b/backend/node_modules/@supabase/auth-js/LICENSE new file mode 100644 index 0000000..ddeba6a --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Supabase + +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. diff --git a/backend/node_modules/@supabase/auth-js/README.md b/backend/node_modules/@supabase/auth-js/README.md new file mode 100644 index 0000000..d23aee3 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/README.md @@ -0,0 +1,166 @@ +
+

+ + + + + Supabase Logo + + + +

Supabase Auth JS SDK

+ +

An isomorphic JavaScript SDK for the Supabase Auth API.

+ +

+ Guides + · + Reference Docs + · + TypeDoc +

+

+ +
+ +[![Build](https://github.com/supabase/supabase-js/workflows/CI/badge.svg)](https://github.com/supabase/supabase-js/actions?query=branch%3Amaster) +[![Package](https://img.shields.io/npm/v/@supabase/auth-js)](https://www.npmjs.com/package/@supabase/auth-js) +[![License: MIT](https://img.shields.io/npm/l/@supabase/supabase-js)](#license) +[![pkg.pr.new](https://pkg.pr.new/badge/supabase/auth-js)](https://pkg.pr.new/~/supabase/auth-js) + +
+ +## Requirements + +- **Node.js 20 or later** (Node.js 18 support dropped as of October 31, 2025) +- For browser support, all modern browsers are supported + +> ⚠️ **Node.js 18 Deprecation Notice** +> +> Node.js 18 reached end-of-life on April 30, 2025. As announced in [our deprecation notice](https://github.com/orgs/supabase/discussions/37217), support for Node.js 18 was dropped on October 31, 2025. + +## Quick start + +Install + +```bash +npm install --save @supabase/auth-js +``` + +Usage + +```js +import { AuthClient } from '@supabase/auth-js' + +const GOTRUE_URL = 'http://localhost:9999' + +const auth = new AuthClient({ url: GOTRUE_URL }) +``` + +- `signUp()`: https://supabase.com/docs/reference/javascript/auth-signup +- `signIn()`: https://supabase.com/docs/reference/javascript/auth-signin +- `signOut()`: https://supabase.com/docs/reference/javascript/auth-signout + +### Custom `fetch` implementation + +`auth-js` uses the [`cross-fetch`](https://www.npmjs.com/package/cross-fetch) library to make HTTP requests, but an alternative `fetch` implementation can be provided as an option. This is most useful in environments where `cross-fetch` is not compatible, for instance Cloudflare Workers: + +```js +import { AuthClient } from '@supabase/auth-js' + +const AUTH_URL = 'http://localhost:9999' + +const auth = new AuthClient({ url: AUTH_URL, fetch: fetch }) +``` + +## Development + +This package is part of the [Supabase JavaScript monorepo](https://github.com/supabase/supabase-js). To work on this package: + +### Building + +```bash +# Complete build (from monorepo root) +npx nx build auth-js + +# Build with watch mode for development +npx nx build auth-js --watch + +# Individual build targets +npx nx build:main auth-js # CommonJS build (dist/main/) +npx nx build:module auth-js # ES Modules build (dist/module/) + +# Other useful commands +npx nx lint auth-js # Run ESLint +npx nx typecheck auth-js # TypeScript type checking +npx nx docs auth-js # Generate documentation +``` + +#### Build Outputs + +- **CommonJS (`dist/main/`)** - For Node.js environments +- **ES Modules (`dist/module/`)** - For modern bundlers (Webpack, Vite, Rollup) +- **TypeScript definitions (`dist/module/index.d.ts`)** - Type definitions for TypeScript projects + +### Testing + +**Docker Required!** The auth-js tests require a local Supabase Auth server (GoTrue) running in Docker. + +```bash +# Run complete test suite (from monorepo root) +npx nx test:auth auth-js +``` + +This command automatically: + +1. Stops any existing test containers +2. Starts a Supabase Auth server (GoTrue) and PostgreSQL database in Docker +3. Waits for services to be ready (30 seconds) +4. Runs the test suite +5. Cleans up Docker containers after tests complete + +#### Individual Test Commands + +```bash +# Run just the test suite (requires infrastructure to be running) +npx nx test:suite auth-js + +# Manually manage test infrastructure +npx nx test:infra auth-js # Start Docker containers +npx nx test:clean auth-js # Stop and remove containers +``` + +#### Development Testing + +For actively developing and debugging tests: + +```bash +# Start infrastructure once +npx nx test:infra auth-js + +# Run tests multiple times (faster since containers stay up) +npx nx test:suite auth-js + +# Clean up when done +npx nx test:clean auth-js +``` + +#### Test Infrastructure + +The Docker setup includes: + +- **Supabase Auth (GoTrue)** - The authentication server +- **PostgreSQL** - Database for auth data +- Pre-configured with test users and settings + +#### Prerequisites + +- **Docker** must be installed and running +- Ports used by test infrastructure (check `infra/docker-compose.yml`) +- No full Supabase instance needed - just the Auth server + +### Contributing + +We welcome contributions! Please see our [Contributing Guide](../../../CONTRIBUTING.md) for details on how to get started. + +For major changes or if you're unsure about something, please open an issue first to discuss your proposed changes. diff --git a/backend/node_modules/@supabase/auth-js/dist/main/AuthAdminApi.d.ts b/backend/node_modules/@supabase/auth-js/dist/main/AuthAdminApi.d.ts new file mode 100644 index 0000000..aacb97d --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/AuthAdminApi.d.ts @@ -0,0 +1,4 @@ +import GoTrueAdminApi from './GoTrueAdminApi'; +declare const AuthAdminApi: typeof GoTrueAdminApi; +export default AuthAdminApi; +//# sourceMappingURL=AuthAdminApi.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/AuthAdminApi.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/main/AuthAdminApi.d.ts.map new file mode 100644 index 0000000..5c6efa8 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/AuthAdminApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"AuthAdminApi.d.ts","sourceRoot":"","sources":["../../src/AuthAdminApi.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,kBAAkB,CAAA;AAE7C,QAAA,MAAM,YAAY,uBAAiB,CAAA;AAEnC,eAAe,YAAY,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/AuthAdminApi.js b/backend/node_modules/@supabase/auth-js/dist/main/AuthAdminApi.js new file mode 100644 index 0000000..0fed974 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/AuthAdminApi.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = require("tslib"); +const GoTrueAdminApi_1 = tslib_1.__importDefault(require("./GoTrueAdminApi")); +const AuthAdminApi = GoTrueAdminApi_1.default; +exports.default = AuthAdminApi; +//# sourceMappingURL=AuthAdminApi.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/AuthAdminApi.js.map b/backend/node_modules/@supabase/auth-js/dist/main/AuthAdminApi.js.map new file mode 100644 index 0000000..6e77d09 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/AuthAdminApi.js.map @@ -0,0 +1 @@ +{"version":3,"file":"AuthAdminApi.js","sourceRoot":"","sources":["../../src/AuthAdminApi.ts"],"names":[],"mappings":";;;AAAA,8EAA6C;AAE7C,MAAM,YAAY,GAAG,wBAAc,CAAA;AAEnC,kBAAe,YAAY,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/AuthClient.d.ts b/backend/node_modules/@supabase/auth-js/dist/main/AuthClient.d.ts new file mode 100644 index 0000000..596eec9 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/AuthClient.d.ts @@ -0,0 +1,4 @@ +import GoTrueClient from './GoTrueClient'; +declare const AuthClient: typeof GoTrueClient; +export default AuthClient; +//# sourceMappingURL=AuthClient.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/AuthClient.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/main/AuthClient.d.ts.map new file mode 100644 index 0000000..503d802 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/AuthClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"AuthClient.d.ts","sourceRoot":"","sources":["../../src/AuthClient.ts"],"names":[],"mappings":"AAAA,OAAO,YAAY,MAAM,gBAAgB,CAAA;AAEzC,QAAA,MAAM,UAAU,qBAAe,CAAA;AAE/B,eAAe,UAAU,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/AuthClient.js b/backend/node_modules/@supabase/auth-js/dist/main/AuthClient.js new file mode 100644 index 0000000..d6e667d --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/AuthClient.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = require("tslib"); +const GoTrueClient_1 = tslib_1.__importDefault(require("./GoTrueClient")); +const AuthClient = GoTrueClient_1.default; +exports.default = AuthClient; +//# sourceMappingURL=AuthClient.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/AuthClient.js.map b/backend/node_modules/@supabase/auth-js/dist/main/AuthClient.js.map new file mode 100644 index 0000000..176c212 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/AuthClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"AuthClient.js","sourceRoot":"","sources":["../../src/AuthClient.ts"],"names":[],"mappings":";;;AAAA,0EAAyC;AAEzC,MAAM,UAAU,GAAG,sBAAY,CAAA;AAE/B,kBAAe,UAAU,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/GoTrueAdminApi.d.ts b/backend/node_modules/@supabase/auth-js/dist/main/GoTrueAdminApi.d.ts new file mode 100644 index 0000000..036f90b --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/GoTrueAdminApi.d.ts @@ -0,0 +1,159 @@ +import { Fetch } from './lib/fetch'; +import { AdminUserAttributes, GenerateLinkParams, GenerateLinkResponse, Pagination, User, UserResponse, GoTrueAdminMFAApi, PageParams, SignOutScope, GoTrueAdminOAuthApi } from './lib/types'; +import { AuthError } from './lib/errors'; +export default class GoTrueAdminApi { + /** Contains all MFA administration methods. */ + mfa: GoTrueAdminMFAApi; + /** + * Contains all OAuth client administration methods. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ + oauth: GoTrueAdminOAuthApi; + protected url: string; + protected headers: { + [key: string]: string; + }; + protected fetch: Fetch; + /** + * Creates an admin API client that can be used to manage users and OAuth clients. + * + * @example + * ```ts + * import { GoTrueAdminApi } from '@supabase/auth-js' + * + * const admin = new GoTrueAdminApi({ + * url: 'https://xyzcompany.supabase.co/auth/v1', + * headers: { Authorization: `Bearer ${process.env.SUPABASE_SERVICE_ROLE_KEY}` }, + * }) + * ``` + */ + constructor({ url, headers, fetch, }: { + url: string; + headers?: { + [key: string]: string; + }; + fetch?: Fetch; + }); + /** + * Removes a logged-in session. + * @param jwt A valid, logged-in JWT. + * @param scope The logout sope. + */ + signOut(jwt: string, scope?: SignOutScope): Promise<{ + data: null; + error: AuthError | null; + }>; + /** + * Sends an invite link to an email address. + * @param email The email address of the user. + * @param options Additional options to be included when inviting. + */ + inviteUserByEmail(email: string, options?: { + /** A custom data object to store additional metadata about the user. This maps to the `auth.users.user_metadata` column. */ + data?: object; + /** The URL which will be appended to the email link sent to the user's email address. Once clicked the user will end up on this URL. */ + redirectTo?: string; + }): Promise; + /** + * Generates email links and OTPs to be sent via a custom email provider. + * @param email The user's email. + * @param options.password User password. For signup only. + * @param options.data Optional user metadata. For signup only. + * @param options.redirectTo The redirect url which should be appended to the generated link + */ + generateLink(params: GenerateLinkParams): Promise; + /** + * Creates a new user. + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + createUser(attributes: AdminUserAttributes): Promise; + /** + * Get a list of users. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + * @param params An object which supports `page` and `perPage` as numbers, to alter the paginated results. + */ + listUsers(params?: PageParams): Promise<{ + data: { + users: User[]; + aud: string; + } & Pagination; + error: null; + } | { + data: { + users: []; + }; + error: AuthError; + }>; + /** + * Get user by id. + * + * @param uid The user's unique identifier + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + getUserById(uid: string): Promise; + /** + * Updates the user data. + * + * @param attributes The data you want to update. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + updateUserById(uid: string, attributes: AdminUserAttributes): Promise; + /** + * Delete a user. Requires a `service_role` key. + * + * @param id The user id you want to remove. + * @param shouldSoftDelete If true, then the user will be soft-deleted from the auth schema. Soft deletion allows user identification from the hashed user ID but is not reversible. + * Defaults to false for backward compatibility. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + deleteUser(id: string, shouldSoftDelete?: boolean): Promise; + private _listFactors; + private _deleteFactor; + /** + * Lists all OAuth clients with optional pagination. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + private _listOAuthClients; + /** + * Creates a new OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + private _createOAuthClient; + /** + * Gets details of a specific OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + private _getOAuthClient; + /** + * Updates an existing OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + private _updateOAuthClient; + /** + * Deletes an OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + private _deleteOAuthClient; + /** + * Regenerates the secret for an OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + private _regenerateOAuthClientSecret; +} +//# sourceMappingURL=GoTrueAdminApi.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/GoTrueAdminApi.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/main/GoTrueAdminApi.d.ts.map new file mode 100644 index 0000000..88941da --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/GoTrueAdminApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"GoTrueAdminApi.d.ts","sourceRoot":"","sources":["../../src/GoTrueAdminApi.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,EAKN,MAAM,aAAa,CAAA;AAEpB,OAAO,EACL,mBAAmB,EACnB,kBAAkB,EAClB,oBAAoB,EACpB,UAAU,EACV,IAAI,EACJ,YAAY,EACZ,iBAAiB,EAKjB,UAAU,EAEV,YAAY,EACZ,mBAAmB,EAKpB,MAAM,aAAa,CAAA;AACpB,OAAO,EAAE,SAAS,EAAe,MAAM,cAAc,CAAA;AAErD,MAAM,CAAC,OAAO,OAAO,cAAc;IACjC,+CAA+C;IAC/C,GAAG,EAAE,iBAAiB,CAAA;IAEtB;;;OAGG;IACH,KAAK,EAAE,mBAAmB,CAAA;IAE1B,SAAS,CAAC,GAAG,EAAE,MAAM,CAAA;IACrB,SAAS,CAAC,OAAO,EAAE;QACjB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KACtB,CAAA;IACD,SAAS,CAAC,KAAK,EAAE,KAAK,CAAA;IAEtB;;;;;;;;;;;;OAYG;gBACS,EACV,GAAQ,EACR,OAAY,EACZ,KAAK,GACN,EAAE;QACD,GAAG,EA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;;;;;OAQG;IACG,UAAU,CAAC,EAAE,EAAE,MAAM,EAAE,gBAAgB,UAAQ,GAAG,OAAO,CAAC,YAAY,CAAC;YAoB/D,YAAY;YA2BZ,aAAa;IA0B3B;;;;;OAKG;YACW,iBAAiB;IAmC/B;;;;;OAKG;YACW,kBAAkB;IAkBhC;;;;;OAKG;YACW,eAAe;IAiB7B;;;;;OAKG;YACW,kBAAkB;IAqBhC;;;;;OAKG;YACW,kBAAkB;IAkBhC;;;;;OAKG;YACW,4BAA4B;CAqB3C"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/GoTrueAdminApi.js b/backend/node_modules/@supabase/auth-js/dist/main/GoTrueAdminApi.js new file mode 100644 index 0000000..5e7e5fa --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/GoTrueAdminApi.js @@ -0,0 +1,441 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = require("tslib"); +const fetch_1 = require("./lib/fetch"); +const helpers_1 = require("./lib/helpers"); +const types_1 = require("./lib/types"); +const errors_1 = require("./lib/errors"); +class GoTrueAdminApi { + /** + * Creates an admin API client that can be used to manage users and OAuth clients. + * + * @example + * ```ts + * import { GoTrueAdminApi } from '@supabase/auth-js' + * + * const admin = new GoTrueAdminApi({ + * url: 'https://xyzcompany.supabase.co/auth/v1', + * headers: { Authorization: `Bearer ${process.env.SUPABASE_SERVICE_ROLE_KEY}` }, + * }) + * ``` + */ + constructor({ url = '', headers = {}, fetch, }) { + this.url = url; + this.headers = headers; + this.fetch = (0, helpers_1.resolveFetch)(fetch); + this.mfa = { + listFactors: this._listFactors.bind(this), + deleteFactor: this._deleteFactor.bind(this), + }; + this.oauth = { + listClients: this._listOAuthClients.bind(this), + createClient: this._createOAuthClient.bind(this), + getClient: this._getOAuthClient.bind(this), + updateClient: this._updateOAuthClient.bind(this), + deleteClient: this._deleteOAuthClient.bind(this), + regenerateClientSecret: this._regenerateOAuthClientSecret.bind(this), + }; + } + /** + * Removes a logged-in session. + * @param jwt A valid, logged-in JWT. + * @param scope The logout sope. + */ + async signOut(jwt, scope = types_1.SIGN_OUT_SCOPES[0]) { + if (types_1.SIGN_OUT_SCOPES.indexOf(scope) < 0) { + throw new Error(`@supabase/auth-js: Parameter scope must be one of ${types_1.SIGN_OUT_SCOPES.join(', ')}`); + } + try { + await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/logout?scope=${scope}`, { + headers: this.headers, + jwt, + noResolveJson: true, + }); + return { data: null, error: null }; + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Sends an invite link to an email address. + * @param email The email address of the user. + * @param options Additional options to be included when inviting. + */ + async inviteUserByEmail(email, options = {}) { + try { + return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/invite`, { + body: { email, data: options.data }, + headers: this.headers, + redirectTo: options.redirectTo, + xform: fetch_1._userResponse, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + /** + * Generates email links and OTPs to be sent via a custom email provider. + * @param email The user's email. + * @param options.password User password. For signup only. + * @param options.data Optional user metadata. For signup only. + * @param options.redirectTo The redirect url which should be appended to the generated link + */ + async generateLink(params) { + try { + const { options } = params, rest = tslib_1.__rest(params, ["options"]); + const body = Object.assign(Object.assign({}, rest), options); + if ('newEmail' in rest) { + // replace newEmail with new_email in request body + body.new_email = rest === null || rest === void 0 ? void 0 : rest.newEmail; + delete body['newEmail']; + } + return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/admin/generate_link`, { + body: body, + headers: this.headers, + xform: fetch_1._generateLinkResponse, + redirectTo: options === null || options === void 0 ? void 0 : options.redirectTo, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { + data: { + properties: null, + user: null, + }, + error, + }; + } + throw error; + } + } + // User Admin API + /** + * Creates a new user. + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async createUser(attributes) { + try { + return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/admin/users`, { + body: attributes, + headers: this.headers, + xform: fetch_1._userResponse, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + /** + * Get a list of users. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + * @param params An object which supports `page` and `perPage` as numbers, to alter the paginated results. + */ + async listUsers(params) { + var _a, _b, _c, _d, _e, _f, _g; + try { + const pagination = { nextPage: null, lastPage: 0, total: 0 }; + const response = await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/users`, { + headers: this.headers, + noResolveJson: true, + query: { + page: (_b = (_a = params === null || params === void 0 ? void 0 : params.page) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : '', + per_page: (_d = (_c = params === null || params === void 0 ? void 0 : params.perPage) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : '', + }, + xform: fetch_1._noResolveJsonResponse, + }); + if (response.error) + throw response.error; + const users = await response.json(); + const total = (_e = response.headers.get('x-total-count')) !== null && _e !== void 0 ? _e : 0; + const links = (_g = (_f = response.headers.get('link')) === null || _f === void 0 ? void 0 : _f.split(',')) !== null && _g !== void 0 ? _g : []; + if (links.length > 0) { + links.forEach((link) => { + const page = parseInt(link.split(';')[0].split('=')[1].substring(0, 1)); + const rel = JSON.parse(link.split(';')[1].split('=')[1]); + pagination[`${rel}Page`] = page; + }); + pagination.total = parseInt(total); + } + return { data: Object.assign(Object.assign({}, users), pagination), error: null }; + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { users: [] }, error }; + } + throw error; + } + } + /** + * Get user by id. + * + * @param uid The user's unique identifier + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async getUserById(uid) { + (0, helpers_1.validateUUID)(uid); + try { + return await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/users/${uid}`, { + headers: this.headers, + xform: fetch_1._userResponse, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + /** + * Updates the user data. + * + * @param attributes The data you want to update. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async updateUserById(uid, attributes) { + (0, helpers_1.validateUUID)(uid); + try { + return await (0, fetch_1._request)(this.fetch, 'PUT', `${this.url}/admin/users/${uid}`, { + body: attributes, + headers: this.headers, + xform: fetch_1._userResponse, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + /** + * Delete a user. Requires a `service_role` key. + * + * @param id The user id you want to remove. + * @param shouldSoftDelete If true, then the user will be soft-deleted from the auth schema. Soft deletion allows user identification from the hashed user ID but is not reversible. + * Defaults to false for backward compatibility. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async deleteUser(id, shouldSoftDelete = false) { + (0, helpers_1.validateUUID)(id); + try { + return await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/admin/users/${id}`, { + headers: this.headers, + body: { + should_soft_delete: shouldSoftDelete, + }, + xform: fetch_1._userResponse, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + async _listFactors(params) { + (0, helpers_1.validateUUID)(params.userId); + try { + const { data, error } = await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/users/${params.userId}/factors`, { + headers: this.headers, + xform: (factors) => { + return { data: { factors }, error: null }; + }, + }); + return { data, error }; + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } + async _deleteFactor(params) { + (0, helpers_1.validateUUID)(params.userId); + (0, helpers_1.validateUUID)(params.id); + try { + const data = await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/admin/users/${params.userId}/factors/${params.id}`, { + headers: this.headers, + }); + return { data, error: null }; + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Lists all OAuth clients with optional pagination. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async _listOAuthClients(params) { + var _a, _b, _c, _d, _e, _f, _g; + try { + const pagination = { nextPage: null, lastPage: 0, total: 0 }; + const response = await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/oauth/clients`, { + headers: this.headers, + noResolveJson: true, + query: { + page: (_b = (_a = params === null || params === void 0 ? void 0 : params.page) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : '', + per_page: (_d = (_c = params === null || params === void 0 ? void 0 : params.perPage) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : '', + }, + xform: fetch_1._noResolveJsonResponse, + }); + if (response.error) + throw response.error; + const clients = await response.json(); + const total = (_e = response.headers.get('x-total-count')) !== null && _e !== void 0 ? _e : 0; + const links = (_g = (_f = response.headers.get('link')) === null || _f === void 0 ? void 0 : _f.split(',')) !== null && _g !== void 0 ? _g : []; + if (links.length > 0) { + links.forEach((link) => { + const page = parseInt(link.split(';')[0].split('=')[1].substring(0, 1)); + const rel = JSON.parse(link.split(';')[1].split('=')[1]); + pagination[`${rel}Page`] = page; + }); + pagination.total = parseInt(total); + } + return { data: Object.assign(Object.assign({}, clients), pagination), error: null }; + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { clients: [] }, error }; + } + throw error; + } + } + /** + * Creates a new OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async _createOAuthClient(params) { + try { + return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/admin/oauth/clients`, { + body: params, + headers: this.headers, + xform: (client) => { + return { data: client, error: null }; + }, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Gets details of a specific OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async _getOAuthClient(clientId) { + try { + return await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/oauth/clients/${clientId}`, { + headers: this.headers, + xform: (client) => { + return { data: client, error: null }; + }, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Updates an existing OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async _updateOAuthClient(clientId, params) { + try { + return await (0, fetch_1._request)(this.fetch, 'PUT', `${this.url}/admin/oauth/clients/${clientId}`, { + body: params, + headers: this.headers, + xform: (client) => { + return { data: client, error: null }; + }, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Deletes an OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async _deleteOAuthClient(clientId) { + try { + await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/admin/oauth/clients/${clientId}`, { + headers: this.headers, + noResolveJson: true, + }); + return { data: null, error: null }; + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Regenerates the secret for an OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async _regenerateOAuthClientSecret(clientId) { + try { + return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/admin/oauth/clients/${clientId}/regenerate_secret`, { + headers: this.headers, + xform: (client) => { + return { data: client, error: null }; + }, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } +} +exports.default = GoTrueAdminApi; +//# sourceMappingURL=GoTrueAdminApi.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/GoTrueAdminApi.js.map b/backend/node_modules/@supabase/auth-js/dist/main/GoTrueAdminApi.js.map new file mode 100644 index 0000000..b56731d --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/GoTrueAdminApi.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GoTrueAdminApi.js","sourceRoot":"","sources":["../../src/GoTrueAdminApi.ts"],"names":[],"mappings":";;;AAAA,uCAMoB;AACpB,2CAA0D;AAC1D,uCAoBoB;AACpB,yCAAqD;AAErD,MAAqB,cAAc;IAgBjC;;;;;;;;;;;;OAYG;IACH,YAAY,EACV,GAAG,GAAG,EAAE,EACR,OAAO,GAAG,EAAE,EACZ,KAAK,GAON;QACC,IAAI,CAAC,GAAG,GAAG,GAAG,CAAA;QACd,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;QACtB,IAAI,CAAC,KAAK,GAAG,IAAA,sBAAY,EAAC,KAAK,CAAC,CAAA;QAChC,IAAI,CAAC,GAAG,GAAG;YACT,WAAW,EAAE,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC;YACzC,YAAY,EAAE,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC;SAC5C,CAAA;QACD,IAAI,CAAC,KAAK,GAAG;YACX,WAAW,EAAE,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,IAAI,CAAC;YAC9C,YAAY,EAAE,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,IAAI,CAAC;YAChD,SAAS,EAAE,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,IAAI,CAAC;YAC1C,YAAY,EAAE,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,IAAI,CAAC;YAChD,YAAY,EAAE,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,IAAI,CAAC;YAChD,sBAAsB,EAAE,IAAI,CAAC,4BAA4B,CAAC,IAAI,CAAC,IAAI,CAAC;SACrE,CAAA;IACH,CAAC;IAED;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AAI,IAAA,oBAAW,EAAC,KAAK,CAAC,EAAE,CAAC;gBACvB,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,CAAA;YAC9B,CAAC;YAED,MAAM,KAAK,CAAA;QACb,CAAC;IACH,CAAC;IAED;;;;;OAKG;IACK,KAAK,CAAC,4BAA4B,CAAC,QAAgB;QACzD,IAAI,CAAC;YACH,OAAO,MAAM,IAAA,gBAAQ,EACnB,IAAI,CAAC,KAAK,EACV,MAAM,EACN,GAAG,IAAI,CAAC,GAAG,wBAAwB,QAAQ,oBAAoB,EAC/D;gBACE,OAAO,EAAE,IAAI,CAAC,OAAO;gBACrB,KAAK,EAAE,CAAC,MAAW,EAAE,EAAE;oBACrB,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,CAAA;gBACtC,CAAC;aACF,CACF,CAAA;QACH,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,IAAA,oBAAW,EAAC,KAAK,CAAC,EAAE,CAAC;gBACvB,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,CAAA;YAC9B,CAAC;YAED,MAAM,KAAK,CAAA;QACb,CAAC;IACH,CAAC;CACF;AAvgBD,iCAugBC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/GoTrueClient.d.ts b/backend/node_modules/@supabase/auth-js/dist/main/GoTrueClient.d.ts new file mode 100644 index 0000000..86030f0 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/GoTrueClient.d.ts @@ -0,0 +1,608 @@ +import GoTrueAdminApi from './GoTrueAdminApi'; +import { AuthError } from './lib/errors'; +import { Fetch } from './lib/fetch'; +import { Deferred } from './lib/helpers'; +import type { AuthChangeEvent, AuthFlowType, AuthOtpResponse, AuthResponse, AuthTokenResponse, AuthTokenResponsePassword, CallRefreshTokenResult, GoTrueClientOptions, GoTrueMFAApi, InitializeResult, JWK, JwtHeader, JwtPayload, LockFunc, OAuthResponse, AuthOAuthServerApi, ResendParams, Session, SignInAnonymouslyCredentials, SignInWithIdTokenCredentials, SignInWithOAuthCredentials, SignInWithPasswordCredentials, SignInWithPasswordlessCredentials, SignInWithSSO, SignOut, SignUpWithPasswordCredentials, SSOResponse, Subscription, SupportedStorage, User, UserAttributes, UserIdentity, UserResponse, VerifyOtpParams, Web3Credentials } from './lib/types'; +export default class GoTrueClient { + private static nextInstanceID; + private instanceID; + /** + * Namespace for the GoTrue admin methods. + * These methods should only be used in a trusted server-side environment. + */ + admin: GoTrueAdminApi; + /** + * Namespace for the MFA methods. + */ + mfa: GoTrueMFAApi; + /** + * Namespace for the OAuth 2.1 authorization server methods. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * Used to implement the authorization code flow on the consent page. + */ + oauth: AuthOAuthServerApi; + /** + * The storage key used to identify the values saved in localStorage + */ + protected storageKey: string; + protected flowType: AuthFlowType; + /** + * The JWKS used for verifying asymmetric JWTs + */ + protected get jwks(): { + keys: JWK[]; + }; + protected set jwks(value: { + keys: JWK[]; + }); + protected get jwks_cached_at(): number; + protected set jwks_cached_at(value: number); + protected autoRefreshToken: boolean; + protected persistSession: boolean; + protected storage: SupportedStorage; + /** + * @experimental + */ + protected userStorage: SupportedStorage | null; + protected memoryStorage: { + [key: string]: string; + } | null; + protected stateChangeEmitters: Map; + protected autoRefreshTicker: ReturnType | null; + protected visibilityChangedCallback: (() => Promise) | null; + protected refreshingDeferred: Deferred | null; + /** + * Keeps track of the async client initialization. + * When null or not yet resolved the auth state is `unknown` + * Once resolved the auth state is known and it's safe to call any further client methods. + * Keep extra care to never reject or throw uncaught errors + */ + protected initializePromise: Promise | null; + protected detectSessionInUrl: boolean; + protected url: string; + protected headers: { + [key: string]: string; + }; + protected hasCustomAuthorizationHeader: boolean; + protected suppressGetSessionWarning: boolean; + protected fetch: Fetch; + protected lock: LockFunc; + protected lockAcquired: boolean; + protected pendingInLock: Promise[]; + protected throwOnError: boolean; + /** + * Used to broadcast state change events to other tabs listening. + */ + protected broadcastChannel: BroadcastChannel | null; + protected logDebugMessages: boolean; + protected logger: (message: string, ...args: any[]) => void; + /** + * Create a new client for use in the browser. + * + * @example + * ```ts + * import { GoTrueClient } from '@supabase/auth-js' + * + * const auth = new GoTrueClient({ + * url: 'https://xyzcompany.supabase.co/auth/v1', + * headers: { apikey: 'public-anon-key' }, + * storageKey: 'supabase-auth', + * }) + * ``` + */ + constructor(options: GoTrueClientOptions); + /** + * Returns whether error throwing mode is enabled for this client. + */ + isThrowOnErrorEnabled(): boolean; + /** + * Centralizes return handling with optional error throwing. When `throwOnError` is enabled + * and the provided result contains a non-nullish error, the error is thrown instead of + * being returned. This ensures consistent behavior across all public API methods. + */ + private _returnResult; + private _logPrefix; + private _debug; + /** + * Initializes the client session either from the url or from storage. + * This method is automatically called when instantiating the client, but should also be called + * manually when checking for an error from an auth redirect (oauth, magiclink, password recovery, etc). + */ + initialize(): Promise; + /** + * IMPORTANT: + * 1. Never throw in this method, as it is called from the constructor + * 2. Never return a session from this method as it would be cached over + * the whole lifetime of the client + */ + private _initialize; + /** + * Creates a new anonymous user. + * + * @returns A session where the is_anonymous claim in the access token JWT set to true + */ + signInAnonymously(credentials?: SignInAnonymouslyCredentials): Promise; + /** + * Creates a new user. + * + * Be aware that if a user account exists in the system you may get back an + * error message that attempts to hide this information from the user. + * This method has support for PKCE via email signups. The PKCE flow cannot be used when autoconfirm is enabled. + * + * @returns A logged-in session if the server has "autoconfirm" ON + * @returns A user if the server has "autoconfirm" OFF + */ + signUp(credentials: SignUpWithPasswordCredentials): Promise; + /** + * Log in an existing user with an email and password or phone and password. + * + * Be aware that you may get back an error message that will not distinguish + * between the cases where the account does not exist or that the + * email/phone and password combination is wrong or that the account can only + * be accessed via social login. + */ + signInWithPassword(credentials: SignInWithPasswordCredentials): Promise; + /** + * Log in an existing user via a third-party provider. + * This method supports the PKCE flow. + */ + signInWithOAuth(credentials: SignInWithOAuthCredentials): Promise; + /** + * Log in an existing user by exchanging an Auth Code issued during the PKCE flow. + */ + exchangeCodeForSession(authCode: string): Promise; + /** + * Signs in a user by verifying a message signed by the user's private key. + * Supports Ethereum (via Sign-In-With-Ethereum) & Solana (Sign-In-With-Solana) standards, + * both of which derive from the EIP-4361 standard + * With slight variation on Solana's side. + * @reference https://eips.ethereum.org/EIPS/eip-4361 + */ + signInWithWeb3(credentials: Web3Credentials): Promise<{ + data: { + session: Session; + user: User; + }; + error: null; + } | { + data: { + session: null; + user: null; + }; + error: AuthError; + }>; + private signInWithEthereum; + private signInWithSolana; + private _exchangeCodeForSession; + /** + * Allows signing in with an OIDC ID token. The authentication provider used + * should be enabled and configured. + */ + signInWithIdToken(credentials: SignInWithIdTokenCredentials): Promise; + /** + * Log in a user using magiclink or a one-time password (OTP). + * + * If the `{{ .ConfirmationURL }}` variable is specified in the email template, a magiclink will be sent. + * If the `{{ .Token }}` variable is specified in the email template, an OTP will be sent. + * If you're using phone sign-ins, only an OTP will be sent. You won't be able to send a magiclink for phone sign-ins. + * + * Be aware that you may get back an error message that will not distinguish + * between the cases where the account does not exist or, that the account + * can only be accessed via social login. + * + * Do note that you will need to configure a Whatsapp sender on Twilio + * if you are using phone sign in with the 'whatsapp' channel. The whatsapp + * channel is not supported on other providers + * at this time. + * This method supports PKCE when an email is passed. + */ + signInWithOtp(credentials: SignInWithPasswordlessCredentials): Promise; + /** + * Log in a user given a User supplied OTP or TokenHash received through mobile or email. + */ + verifyOtp(params: VerifyOtpParams): Promise; + /** + * Attempts a single-sign on using an enterprise Identity Provider. A + * successful SSO attempt will redirect the current page to the identity + * provider authorization page. The redirect URL is implementation and SSO + * protocol specific. + * + * You can use it by providing a SSO domain. Typically you can extract this + * domain by asking users for their email address. If this domain is + * registered on the Auth instance the redirect will use that organization's + * currently active SSO Identity Provider for the login. + * + * If you have built an organization-specific login page, you can use the + * organization's SSO Identity Provider UUID directly instead. + */ + signInWithSSO(params: SignInWithSSO): Promise; + /** + * Sends a reauthentication OTP to the user's email or phone number. + * Requires the user to be signed-in. + */ + reauthenticate(): Promise; + private _reauthenticate; + /** + * Resends an existing signup confirmation email, email change email, SMS OTP or phone change OTP. + */ + resend(credentials: ResendParams): Promise; + /** + * Returns the session, refreshing it if necessary. + * + * The session returned can be null if the session is not detected which can happen in the event a user is not signed-in or has logged out. + * + * **IMPORTANT:** This method loads values directly from the storage attached + * to the client. If that storage is based on request cookies for example, + * the values in it may not be authentic and therefore it's strongly advised + * against using this method and its results in such circumstances. A warning + * will be emitted if this is detected. Use {@link #getUser()} instead. + */ + getSession(): Promise<{ + data: { + session: Session; + }; + error: null; + } | { + data: { + session: null; + }; + error: AuthError; + } | { + data: { + session: null; + }; + error: null; + }>; + /** + * Acquires a global lock based on the storage key. + */ + private _acquireLock; + /** + * Use instead of {@link #getSession} inside the library. It is + * semantically usually what you want, as getting a session involves some + * processing afterwards that requires only one client operating on the + * session at once across multiple tabs or processes. + */ + private _useSession; + /** + * NEVER USE DIRECTLY! + * + * Always use {@link #_useSession}. + */ + private __loadSession; + /** + * Gets the current user details if there is an existing session. This method + * performs a network request to the Supabase Auth server, so the returned + * value is authentic and can be used to base authorization rules on. + * + * @param jwt Takes in an optional access token JWT. If no JWT is provided, the JWT from the current session is used. + */ + getUser(jwt?: string): Promise; + private _getUser; + /** + * Updates user data for a logged in user. + */ + updateUser(attributes: UserAttributes, options?: { + emailRedirectTo?: string | undefined; + }): Promise; + protected _updateUser(attributes: UserAttributes, options?: { + emailRedirectTo?: string | undefined; + }): Promise; + /** + * Sets the session data from the current session. If the current session is expired, setSession will take care of refreshing it to obtain a new session. + * If the refresh token or access token in the current session is invalid, an error will be thrown. + * @param currentSession The current session that minimally contains an access token and refresh token. + */ + setSession(currentSession: { + access_token: string; + refresh_token: string; + }): Promise; + protected _setSession(currentSession: { + access_token: string; + refresh_token: string; + }): Promise; + /** + * Returns a new session, regardless of expiry status. + * Takes in an optional current session. If not passed in, then refreshSession() will attempt to retrieve it from getSession(). + * If the current session's refresh token is invalid, an error will be thrown. + * @param currentSession The current session. If passed in, it must contain a refresh token. + */ + refreshSession(currentSession?: { + refresh_token: string; + }): Promise; + protected _refreshSession(currentSession?: { + refresh_token: string; + }): Promise; + /** + * Gets the session data from a URL string + */ + private _getSessionFromURL; + /** + * Checks if the current URL contains parameters given by an implicit oauth grant flow (https://www.rfc-editor.org/rfc/rfc6749.html#section-4.2) + */ + private _isImplicitGrantCallback; + /** + * Checks if the current URL and backing storage contain parameters given by a PKCE flow + */ + private _isPKCECallback; + /** + * Inside a browser context, `signOut()` will remove the logged in user from the browser session and log them out - removing all items from localstorage and then trigger a `"SIGNED_OUT"` event. + * + * For server-side management, you can revoke all refresh tokens for a user by passing a user's JWT through to `auth.api.signOut(JWT: string)`. + * There is no way to revoke a user's access token jwt until it expires. It is recommended to set a shorter expiry on the jwt for this reason. + * + * If using `others` scope, no `SIGNED_OUT` event is fired! + */ + signOut(options?: SignOut): Promise<{ + error: AuthError | null; + }>; + protected _signOut({ scope }?: SignOut): Promise<{ + error: AuthError | null; + }>; + /** + * Receive a notification every time an auth event happens. + * Safe to use without an async function as callback. + * + * @param callback A callback function to be invoked when an auth event happens. + */ + onAuthStateChange(callback: (event: AuthChangeEvent, session: Session | null) => void): { + data: { + subscription: Subscription; + }; + }; + /** + * Avoid using an async function inside `onAuthStateChange` as you might end + * up with a deadlock. The callback function runs inside an exclusive lock, + * so calling other Supabase Client APIs that also try to acquire the + * exclusive lock, might cause a deadlock. This behavior is observable across + * tabs. In the next major library version, this behavior will not be supported. + * + * Receive a notification every time an auth event happens. + * + * @param callback A callback function to be invoked when an auth event happens. + * @deprecated Due to the possibility of deadlocks with async functions as callbacks, use the version without an async function. + */ + onAuthStateChange(callback: (event: AuthChangeEvent, session: Session | null) => Promise): { + data: { + subscription: Subscription; + }; + }; + private _emitInitialSession; + /** + * Sends a password reset request to an email address. This method supports the PKCE flow. + * + * @param email The email address of the user. + * @param options.redirectTo The URL to send the user to after they click the password reset link. + * @param options.captchaToken Verification token received when the user completes the captcha on the site. + */ + resetPasswordForEmail(email: string, options?: { + redirectTo?: string; + captchaToken?: string; + }): Promise<{ + data: {}; + error: null; + } | { + data: null; + error: AuthError; + }>; + /** + * Gets all the identities linked to a user. + */ + getUserIdentities(): Promise<{ + data: { + identities: UserIdentity[]; + }; + error: null; + } | { + data: null; + error: AuthError; + }>; + /** + * Links an oauth identity to an existing user. + * This method supports the PKCE flow. + */ + linkIdentity(credentials: SignInWithOAuthCredentials): Promise; + /** + * Links an OIDC identity to an existing user. + */ + linkIdentity(credentials: SignInWithIdTokenCredentials): Promise; + private linkIdentityOAuth; + private linkIdentityIdToken; + /** + * Unlinks an identity from a user by deleting it. The user will no longer be able to sign in with that identity once it's unlinked. + */ + unlinkIdentity(identity: UserIdentity): Promise<{ + data: {}; + error: null; + } | { + data: null; + error: AuthError; + }>; + /** + * Generates a new JWT. + * @param refreshToken A valid refresh token that was returned on login. + */ + private _refreshAccessToken; + private _isValidSession; + private _handleProviderSignIn; + /** + * Recovers the session from LocalStorage and refreshes the token + * Note: this method is async to accommodate for AsyncStorage e.g. in React native. + */ + private _recoverAndRefresh; + private _callRefreshToken; + private _notifyAllSubscribers; + /** + * set currentSession and currentUser + * process to _startAutoRefreshToken if possible + */ + private _saveSession; + private _removeSession; + /** + * Removes any registered visibilitychange callback. + * + * {@see #startAutoRefresh} + * {@see #stopAutoRefresh} + */ + private _removeVisibilityChangedCallback; + /** + * This is the private implementation of {@link #startAutoRefresh}. Use this + * within the library. + */ + private _startAutoRefresh; + /** + * This is the private implementation of {@link #stopAutoRefresh}. Use this + * within the library. + */ + private _stopAutoRefresh; + /** + * Starts an auto-refresh process in the background. The session is checked + * every few seconds. Close to the time of expiration a process is started to + * refresh the session. If refreshing fails it will be retried for as long as + * necessary. + * + * If you set the {@link GoTrueClientOptions#autoRefreshToken} you don't need + * to call this function, it will be called for you. + * + * On browsers the refresh process works only when the tab/window is in the + * foreground to conserve resources as well as prevent race conditions and + * flooding auth with requests. If you call this method any managed + * visibility change callback will be removed and you must manage visibility + * changes on your own. + * + * On non-browser platforms the refresh process works *continuously* in the + * background, which may not be desirable. You should hook into your + * platform's foreground indication mechanism and call these methods + * appropriately to conserve resources. + * + * {@see #stopAutoRefresh} + */ + startAutoRefresh(): Promise; + /** + * Stops an active auto refresh process running in the background (if any). + * + * If you call this method any managed visibility change callback will be + * removed and you must manage visibility changes on your own. + * + * See {@link #startAutoRefresh} for more details. + */ + stopAutoRefresh(): Promise; + /** + * Runs the auto refresh token tick. + */ + private _autoRefreshTokenTick; + /** + * Registers callbacks on the browser / platform, which in-turn run + * algorithms when the browser window/tab are in foreground. On non-browser + * platforms it assumes always foreground. + */ + private _handleVisibilityChange; + /** + * Callback registered with `window.addEventListener('visibilitychange')`. + */ + private _onVisibilityChanged; + /** + * Generates the relevant login URL for a third-party provider. + * @param options.redirectTo A URL or mobile address to send the user to after they are confirmed. + * @param options.scopes A space-separated list of scopes granted to the OAuth application. + * @param options.queryParams An object of key-value pairs containing query parameters granted to the OAuth application. + */ + private _getUrlForProvider; + private _unenroll; + /** + * {@see GoTrueMFAApi#enroll} + */ + private _enroll; + /** + * {@see GoTrueMFAApi#verify} + */ + private _verify; + /** + * {@see GoTrueMFAApi#challenge} + */ + private _challenge; + /** + * {@see GoTrueMFAApi#challengeAndVerify} + */ + private _challengeAndVerify; + /** + * {@see GoTrueMFAApi#listFactors} + */ + private _listFactors; + /** + * {@see GoTrueMFAApi#getAuthenticatorAssuranceLevel} + */ + private _getAuthenticatorAssuranceLevel; + /** + * Retrieves details about an OAuth authorization request. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * Returns authorization details including client info, scopes, and user information. + * If the API returns a redirect_uri, it means consent was already given - the caller + * should handle the redirect manually if needed. + */ + private _getAuthorizationDetails; + /** + * Approves an OAuth authorization request. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ + private _approveAuthorization; + /** + * Denies an OAuth authorization request. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ + private _denyAuthorization; + /** + * Lists all OAuth grants that the authenticated user has authorized. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ + private _listOAuthGrants; + /** + * Revokes a user's OAuth grant for a specific client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ + private _revokeOAuthGrant; + private fetchJwk; + /** + * Extracts the JWT claims present in the access token by first verifying the + * JWT against the server's JSON Web Key Set endpoint + * `/.well-known/jwks.json` which is often cached, resulting in significantly + * faster responses. Prefer this method over {@link #getUser} which always + * sends a request to the Auth server for each JWT. + * + * If the project is not using an asymmetric JWT signing key (like ECC or + * RSA) it always sends a request to the Auth server (similar to {@link + * #getUser}) to verify the JWT. + * + * @param jwt An optional specific JWT you wish to verify, not the one you + * can obtain from {@link #getSession}. + * @param options Various additional options that allow you to customize the + * behavior of this method. + */ + getClaims(jwt?: string, options?: { + /** + * @deprecated Please use options.jwks instead. + */ + keys?: JWK[]; + /** If set to `true` the `exp` claim will not be validated against the current time. */ + allowExpired?: boolean; + /** If set, this JSON Web Key Set is going to have precedence over the cached value available on the server. */ + jwks?: { + keys: JWK[]; + }; + }): Promise<{ + data: { + claims: JwtPayload; + header: JwtHeader; + signature: Uint8Array; + }; + error: null; + } | { + data: null; + error: AuthError; + } | { + data: null; + error: null; + }>; +} +//# sourceMappingURL=GoTrueClient.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/GoTrueClient.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/main/GoTrueClient.d.ts.map new file mode 100644 index 0000000..f01c185 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/GoTrueClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"GoTrueClient.d.ts","sourceRoot":"","sources":["../../src/GoTrueClient.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,kBAAkB,CAAA;AAU7C,OAAO,EACL,SAAS,EAaV,MAAM,cAAc,CAAA;AACrB,OAAO,EACL,KAAK,EAMN,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TrueClient.js b/backend/node_modules/@supabase/auth-js/dist/main/GoTrueClient.js new file mode 100644 index 0000000..1dac21e --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/GoTrueClient.js @@ -0,0 +1,2789 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = require("tslib"); +const GoTrueAdminApi_1 = tslib_1.__importDefault(require("./GoTrueAdminApi")); +const constants_1 = require("./lib/constants"); +const errors_1 = require("./lib/errors"); +const fetch_1 = require("./lib/fetch"); +const helpers_1 = require("./lib/helpers"); +const local_storage_1 = require("./lib/local-storage"); +const locks_1 = require("./lib/locks"); +const polyfills_1 = require("./lib/polyfills"); +const version_1 = require("./lib/version"); +const base64url_1 = require("./lib/base64url"); +const ethereum_1 = require("./lib/web3/ethereum"); +const webauthn_1 = require("./lib/webauthn"); +(0, polyfills_1.polyfillGlobalThis)(); // Make "globalThis" available +const DEFAULT_OPTIONS = { + url: constants_1.GOTRUE_URL, + storageKey: constants_1.STORAGE_KEY, + autoRefreshToken: true, + persistSession: true, + detectSessionInUrl: true, + headers: constants_1.DEFAULT_HEADERS, + flowType: 'implicit', + debug: false, + hasCustomAuthorizationHeader: false, + throwOnError: false, +}; +async function lockNoOp(name, acquireTimeout, fn) { + return await fn(); +} +/** + * Caches JWKS values for all clients created in the same environment. This is + * especially useful for shared-memory execution environments such as Vercel's + * Fluid Compute, AWS Lambda or Supabase's Edge Functions. Regardless of how + * many clients are created, if they share the same storage key they will use + * the same JWKS cache, significantly speeding up getClaims() with asymmetric + * JWTs. + */ +const GLOBAL_JWKS = {}; +class GoTrueClient { + /** + * The JWKS used for verifying asymmetric JWTs + */ + get jwks() { + var _a, _b; + return (_b = (_a = GLOBAL_JWKS[this.storageKey]) === null || _a === void 0 ? void 0 : _a.jwks) !== null && _b !== void 0 ? _b : { keys: [] }; + } + set jwks(value) { + GLOBAL_JWKS[this.storageKey] = Object.assign(Object.assign({}, GLOBAL_JWKS[this.storageKey]), { jwks: value }); + } + get jwks_cached_at() { + var _a, _b; + return (_b = (_a = GLOBAL_JWKS[this.storageKey]) === null || _a === void 0 ? void 0 : _a.cachedAt) !== null && _b !== void 0 ? _b : Number.MIN_SAFE_INTEGER; + } + set jwks_cached_at(value) { + GLOBAL_JWKS[this.storageKey] = Object.assign(Object.assign({}, GLOBAL_JWKS[this.storageKey]), { cachedAt: value }); + } + /** + * Create a new client for use in the browser. + * + * @example + * ```ts + * import { GoTrueClient } from '@supabase/auth-js' + * + * const auth = new GoTrueClient({ + * url: 'https://xyzcompany.supabase.co/auth/v1', + * headers: { apikey: 'public-anon-key' }, + * storageKey: 'supabase-auth', + * }) + * ``` + */ + constructor(options) { + var _a, _b, _c; + /** + * @experimental + */ + this.userStorage = null; + this.memoryStorage = null; + this.stateChangeEmitters = new Map(); + this.autoRefreshTicker = null; + this.visibilityChangedCallback = null; + this.refreshingDeferred = null; + /** + * Keeps track of the async client initialization. + * When null or not yet resolved the auth state is `unknown` + * Once resolved the auth state is known and it's safe to call any further client methods. + * Keep extra care to never reject or throw uncaught errors + */ + this.initializePromise = null; + this.detectSessionInUrl = true; + this.hasCustomAuthorizationHeader = false; + this.suppressGetSessionWarning = false; + this.lockAcquired = false; + this.pendingInLock = []; + /** + * Used to broadcast state change events to other tabs listening. + */ + this.broadcastChannel = null; + this.logger = console.log; + const settings = Object.assign(Object.assign({}, DEFAULT_OPTIONS), options); + this.storageKey = settings.storageKey; + this.instanceID = (_a = GoTrueClient.nextInstanceID[this.storageKey]) !== null && _a !== void 0 ? _a : 0; + GoTrueClient.nextInstanceID[this.storageKey] = this.instanceID + 1; + this.logDebugMessages = !!settings.debug; + if (typeof settings.debug === 'function') { + this.logger = settings.debug; + } + if (this.instanceID > 0 && (0, helpers_1.isBrowser)()) { + const message = `${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`; + console.warn(message); + if (this.logDebugMessages) { + console.trace(message); + } + } + this.persistSession = settings.persistSession; + this.autoRefreshToken = settings.autoRefreshToken; + this.admin = new GoTrueAdminApi_1.default({ + url: settings.url, + headers: settings.headers, + fetch: settings.fetch, + }); + this.url = settings.url; + this.headers = settings.headers; + this.fetch = (0, helpers_1.resolveFetch)(settings.fetch); + this.lock = settings.lock || lockNoOp; + this.detectSessionInUrl = settings.detectSessionInUrl; + this.flowType = settings.flowType; + this.hasCustomAuthorizationHeader = settings.hasCustomAuthorizationHeader; + this.throwOnError = settings.throwOnError; + if (settings.lock) { + this.lock = settings.lock; + } + else if (this.persistSession && (0, helpers_1.isBrowser)() && ((_b = globalThis === null || globalThis === void 0 ? void 0 : globalThis.navigator) === null || _b === void 0 ? void 0 : _b.locks)) { + this.lock = locks_1.navigatorLock; + } + else { + this.lock = lockNoOp; + } + if (!this.jwks) { + this.jwks = { keys: [] }; + this.jwks_cached_at = Number.MIN_SAFE_INTEGER; + } + this.mfa = { + verify: this._verify.bind(this), + enroll: this._enroll.bind(this), + unenroll: this._unenroll.bind(this), + challenge: this._challenge.bind(this), + listFactors: this._listFactors.bind(this), + challengeAndVerify: this._challengeAndVerify.bind(this), + getAuthenticatorAssuranceLevel: this._getAuthenticatorAssuranceLevel.bind(this), + webauthn: new webauthn_1.WebAuthnApi(this), + }; + this.oauth = { + getAuthorizationDetails: this._getAuthorizationDetails.bind(this), + approveAuthorization: this._approveAuthorization.bind(this), + denyAuthorization: this._denyAuthorization.bind(this), + listGrants: this._listOAuthGrants.bind(this), + revokeGrant: this._revokeOAuthGrant.bind(this), + }; + if (this.persistSession) { + if (settings.storage) { + this.storage = settings.storage; + } + else { + if ((0, helpers_1.supportsLocalStorage)()) { + this.storage = globalThis.localStorage; + } + else { + this.memoryStorage = {}; + this.storage = (0, local_storage_1.memoryLocalStorageAdapter)(this.memoryStorage); + } + } + if (settings.userStorage) { + this.userStorage = settings.userStorage; + } + } + else { + this.memoryStorage = {}; + this.storage = (0, local_storage_1.memoryLocalStorageAdapter)(this.memoryStorage); + } + if ((0, helpers_1.isBrowser)() && globalThis.BroadcastChannel && this.persistSession && this.storageKey) { + try { + this.broadcastChannel = new globalThis.BroadcastChannel(this.storageKey); + } + catch (e) { + console.error('Failed to create a new BroadcastChannel, multi-tab state changes will not be available', e); + } + (_c = this.broadcastChannel) === null || _c === void 0 ? void 0 : _c.addEventListener('message', async (event) => { + this._debug('received broadcast notification from other tab or client', event); + await this._notifyAllSubscribers(event.data.event, event.data.session, false); // broadcast = false so we don't get an endless loop of messages + }); + } + this.initialize(); + } + /** + * Returns whether error throwing mode is enabled for this client. + */ + isThrowOnErrorEnabled() { + return this.throwOnError; + } + /** + * Centralizes return handling with optional error throwing. When `throwOnError` is enabled + * and the provided result contains a non-nullish error, the error is thrown instead of + * being returned. This ensures consistent behavior across all public API methods. + */ + _returnResult(result) { + if (this.throwOnError && result && result.error) { + throw result.error; + } + return result; + } + _logPrefix() { + return ('GoTrueClient@' + + `${this.storageKey}:${this.instanceID} (${version_1.version}) ${new Date().toISOString()}`); + } + _debug(...args) { + if (this.logDebugMessages) { + this.logger(this._logPrefix(), ...args); + } + return this; + } + /** + * Initializes the client session either from the url or from storage. + * This method is automatically called when instantiating the client, but should also be called + * manually when checking for an error from an auth redirect (oauth, magiclink, password recovery, etc). + */ + async initialize() { + if (this.initializePromise) { + return await this.initializePromise; + } + this.initializePromise = (async () => { + return await this._acquireLock(-1, async () => { + return await this._initialize(); + }); + })(); + return await this.initializePromise; + } + /** + * IMPORTANT: + * 1. Never throw in this method, as it is called from the constructor + * 2. Never return a session from this method as it would be cached over + * the whole lifetime of the client + */ + async _initialize() { + var _a; + try { + let params = {}; + let callbackUrlType = 'none'; + if ((0, helpers_1.isBrowser)()) { + params = (0, helpers_1.parseParametersFromURL)(window.location.href); + if (this._isImplicitGrantCallback(params)) { + callbackUrlType = 'implicit'; + } + else if (await this._isPKCECallback(params)) { + callbackUrlType = 'pkce'; + } + } + /** + * Attempt to get the session from the URL only if these conditions are fulfilled + * + * Note: If the URL isn't one of the callback url types (implicit or pkce), + * then there could be an existing session so we don't want to prematurely remove it + */ + if ((0, helpers_1.isBrowser)() && this.detectSessionInUrl && callbackUrlType !== 'none') { + const { data, error } = await this._getSessionFromURL(params, callbackUrlType); + if (error) { + this._debug('#_initialize()', 'error detecting session from URL', error); + if ((0, errors_1.isAuthImplicitGrantRedirectError)(error)) { + const errorCode = (_a = error.details) === null || _a === void 0 ? void 0 : _a.code; + if (errorCode === 'identity_already_exists' || + errorCode === 'identity_not_found' || + errorCode === 'single_identity_not_deletable') { + return { error }; + } + } + // failed login attempt via url, + // remove old session as in verifyOtp, signUp and signInWith* + await this._removeSession(); + return { error }; + } + const { session, redirectType } = data; + this._debug('#_initialize()', 'detected session in URL', session, 'redirect type', redirectType); + await this._saveSession(session); + setTimeout(async () => { + if (redirectType === 'recovery') { + await this._notifyAllSubscribers('PASSWORD_RECOVERY', session); + } + else { + await this._notifyAllSubscribers('SIGNED_IN', session); + } + }, 0); + return { error: null }; + } + // no login attempt via callback url try to recover session from storage + await this._recoverAndRefresh(); + return { error: null }; + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ error }); + } + return this._returnResult({ + error: new errors_1.AuthUnknownError('Unexpected error during initialization', error), + }); + } + finally { + await this._handleVisibilityChange(); + this._debug('#_initialize()', 'end'); + } + } + /** + * Creates a new anonymous user. + * + * @returns A session where the is_anonymous claim in the access token JWT set to true + */ + async signInAnonymously(credentials) { + var _a, _b, _c; + try { + const res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/signup`, { + headers: this.headers, + body: { + data: (_b = (_a = credentials === null || credentials === void 0 ? void 0 : credentials.options) === null || _a === void 0 ? void 0 : _a.data) !== null && _b !== void 0 ? _b : {}, + gotrue_meta_security: { captcha_token: (_c = credentials === null || credentials === void 0 ? void 0 : credentials.options) === null || _c === void 0 ? void 0 : _c.captchaToken }, + }, + xform: fetch_1._sessionResponse, + }); + const { data, error } = res; + if (error || !data) { + return this._returnResult({ data: { user: null, session: null }, error: error }); + } + const session = data.session; + const user = data.user; + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', session); + } + return this._returnResult({ data: { user, session }, error: null }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + /** + * Creates a new user. + * + * Be aware that if a user account exists in the system you may get back an + * error message that attempts to hide this information from the user. + * This method has support for PKCE via email signups. The PKCE flow cannot be used when autoconfirm is enabled. + * + * @returns A logged-in session if the server has "autoconfirm" ON + * @returns A user if the server has "autoconfirm" OFF + */ + async signUp(credentials) { + var _a, _b, _c; + try { + let res; + if ('email' in credentials) { + const { email, password, options } = credentials; + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === 'pkce') { + ; + [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey); + } + res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/signup`, { + headers: this.headers, + redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, + body: { + email, + password, + data: (_a = options === null || options === void 0 ? void 0 : options.data) !== null && _a !== void 0 ? _a : {}, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + code_challenge: codeChallenge, + code_challenge_method: codeChallengeMethod, + }, + xform: fetch_1._sessionResponse, + }); + } + else if ('phone' in credentials) { + const { phone, password, options } = credentials; + res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/signup`, { + headers: this.headers, + body: { + phone, + password, + data: (_b = options === null || options === void 0 ? void 0 : options.data) !== null && _b !== void 0 ? _b : {}, + channel: (_c = options === null || options === void 0 ? void 0 : options.channel) !== null && _c !== void 0 ? _c : 'sms', + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + xform: fetch_1._sessionResponse, + }); + } + else { + throw new errors_1.AuthInvalidCredentialsError('You must provide either an email or phone number and a password'); + } + const { data, error } = res; + if (error || !data) { + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + return this._returnResult({ data: { user: null, session: null }, error: error }); + } + const session = data.session; + const user = data.user; + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', session); + } + return this._returnResult({ data: { user, session }, error: null }); + } + catch (error) { + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + /** + * Log in an existing user with an email and password or phone and password. + * + * Be aware that you may get back an error message that will not distinguish + * between the cases where the account does not exist or that the + * email/phone and password combination is wrong or that the account can only + * be accessed via social login. + */ + async signInWithPassword(credentials) { + try { + let res; + if ('email' in credentials) { + const { email, password, options } = credentials; + res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=password`, { + headers: this.headers, + body: { + email, + password, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + xform: fetch_1._sessionResponsePassword, + }); + } + else if ('phone' in credentials) { + const { phone, password, options } = credentials; + res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=password`, { + headers: this.headers, + body: { + phone, + password, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + xform: fetch_1._sessionResponsePassword, + }); + } + else { + throw new errors_1.AuthInvalidCredentialsError('You must provide either an email or phone number and a password'); + } + const { data, error } = res; + if (error) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + else if (!data || !data.session || !data.user) { + const invalidTokenError = new errors_1.AuthInvalidTokenResponseError(); + return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError }); + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', data.session); + } + return this._returnResult({ + data: Object.assign({ user: data.user, session: data.session }, (data.weak_password ? { weakPassword: data.weak_password } : null)), + error, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + /** + * Log in an existing user via a third-party provider. + * This method supports the PKCE flow. + */ + async signInWithOAuth(credentials) { + var _a, _b, _c, _d; + return await this._handleProviderSignIn(credentials.provider, { + redirectTo: (_a = credentials.options) === null || _a === void 0 ? void 0 : _a.redirectTo, + scopes: (_b = credentials.options) === null || _b === void 0 ? void 0 : _b.scopes, + queryParams: (_c = credentials.options) === null || _c === void 0 ? void 0 : _c.queryParams, + skipBrowserRedirect: (_d = credentials.options) === null || _d === void 0 ? void 0 : _d.skipBrowserRedirect, + }); + } + /** + * Log in an existing user by exchanging an Auth Code issued during the PKCE flow. + */ + async exchangeCodeForSession(authCode) { + await this.initializePromise; + return this._acquireLock(-1, async () => { + return this._exchangeCodeForSession(authCode); + }); + } + /** + * Signs in a user by verifying a message signed by the user's private key. + * Supports Ethereum (via Sign-In-With-Ethereum) & Solana (Sign-In-With-Solana) standards, + * both of which derive from the EIP-4361 standard + * With slight variation on Solana's side. + * @reference https://eips.ethereum.org/EIPS/eip-4361 + */ + async signInWithWeb3(credentials) { + const { chain } = credentials; + switch (chain) { + case 'ethereum': + return await this.signInWithEthereum(credentials); + case 'solana': + return await this.signInWithSolana(credentials); + default: + throw new Error(`@supabase/auth-js: Unsupported chain "${chain}"`); + } + } + async signInWithEthereum(credentials) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l; + // TODO: flatten type + let message; + let signature; + if ('message' in credentials) { + message = credentials.message; + signature = credentials.signature; + } + else { + const { chain, wallet, statement, options } = credentials; + let resolvedWallet; + if (!(0, helpers_1.isBrowser)()) { + if (typeof wallet !== 'object' || !(options === null || options === void 0 ? void 0 : options.url)) { + throw new Error('@supabase/auth-js: Both wallet and url must be specified in non-browser environments.'); + } + resolvedWallet = wallet; + } + else if (typeof wallet === 'object') { + resolvedWallet = wallet; + } + else { + const windowAny = window; + if ('ethereum' in windowAny && + typeof windowAny.ethereum === 'object' && + 'request' in windowAny.ethereum && + typeof windowAny.ethereum.request === 'function') { + resolvedWallet = windowAny.ethereum; + } + else { + throw new Error(`@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.`); + } + } + const url = new URL((_a = options === null || options === void 0 ? void 0 : options.url) !== null && _a !== void 0 ? _a : window.location.href); + const accounts = await resolvedWallet + .request({ + method: 'eth_requestAccounts', + }) + .then((accs) => accs) + .catch(() => { + throw new Error(`@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid`); + }); + if (!accounts || accounts.length === 0) { + throw new Error(`@supabase/auth-js: No accounts available. Please ensure the wallet is connected.`); + } + const address = (0, ethereum_1.getAddress)(accounts[0]); + let chainId = (_b = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _b === void 0 ? void 0 : _b.chainId; + if (!chainId) { + const chainIdHex = await resolvedWallet.request({ + method: 'eth_chainId', + }); + chainId = (0, ethereum_1.fromHex)(chainIdHex); + } + const siweMessage = { + domain: url.host, + address: address, + statement: statement, + uri: url.href, + version: '1', + chainId: chainId, + nonce: (_c = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _c === void 0 ? void 0 : _c.nonce, + issuedAt: (_e = (_d = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _d === void 0 ? void 0 : _d.issuedAt) !== null && _e !== void 0 ? _e : new Date(), + expirationTime: (_f = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _f === void 0 ? void 0 : _f.expirationTime, + notBefore: (_g = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _g === void 0 ? void 0 : _g.notBefore, + requestId: (_h = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _h === void 0 ? void 0 : _h.requestId, + resources: (_j = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _j === void 0 ? void 0 : _j.resources, + }; + message = (0, ethereum_1.createSiweMessage)(siweMessage); + // Sign message + signature = (await resolvedWallet.request({ + method: 'personal_sign', + params: [(0, ethereum_1.toHex)(message), address], + })); + } + try { + const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=web3`, { + headers: this.headers, + body: Object.assign({ chain: 'ethereum', message, + signature }, (((_k = credentials.options) === null || _k === void 0 ? void 0 : _k.captchaToken) + ? { gotrue_meta_security: { captcha_token: (_l = credentials.options) === null || _l === void 0 ? void 0 : _l.captchaToken } } + : null)), + xform: fetch_1._sessionResponse, + }); + if (error) { + throw error; + } + if (!data || !data.session || !data.user) { + const invalidTokenError = new errors_1.AuthInvalidTokenResponseError(); + return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError }); + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', data.session); + } + return this._returnResult({ data: Object.assign({}, data), error }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + async signInWithSolana(credentials) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m; + let message; + let signature; + if ('message' in credentials) { + message = credentials.message; + signature = credentials.signature; + } + else { + const { chain, wallet, statement, options } = credentials; + let resolvedWallet; + if (!(0, helpers_1.isBrowser)()) { + if (typeof wallet !== 'object' || !(options === null || options === void 0 ? void 0 : options.url)) { + throw new Error('@supabase/auth-js: Both wallet and url must be specified in non-browser environments.'); + } + resolvedWallet = wallet; + } + else if (typeof wallet === 'object') { + resolvedWallet = wallet; + } + else { + const windowAny = window; + if ('solana' in windowAny && + typeof windowAny.solana === 'object' && + (('signIn' in windowAny.solana && typeof windowAny.solana.signIn === 'function') || + ('signMessage' in windowAny.solana && + typeof windowAny.solana.signMessage === 'function'))) { + resolvedWallet = windowAny.solana; + } + else { + throw new Error(`@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.`); + } + } + const url = new URL((_a = options === null || options === void 0 ? void 0 : options.url) !== null && _a !== void 0 ? _a : window.location.href); + if ('signIn' in resolvedWallet && resolvedWallet.signIn) { + const output = await resolvedWallet.signIn(Object.assign(Object.assign(Object.assign({ issuedAt: new Date().toISOString() }, options === null || options === void 0 ? void 0 : options.signInWithSolana), { + // non-overridable properties + version: '1', domain: url.host, uri: url.href }), (statement ? { statement } : null))); + let outputToProcess; + if (Array.isArray(output) && output[0] && typeof output[0] === 'object') { + outputToProcess = output[0]; + } + else if (output && + typeof output === 'object' && + 'signedMessage' in output && + 'signature' in output) { + outputToProcess = output; + } + else { + throw new Error('@supabase/auth-js: Wallet method signIn() returned unrecognized value'); + } + if ('signedMessage' in outputToProcess && + 'signature' in outputToProcess && + (typeof outputToProcess.signedMessage === 'string' || + outputToProcess.signedMessage instanceof Uint8Array) && + outputToProcess.signature instanceof Uint8Array) { + message = + typeof outputToProcess.signedMessage === 'string' + ? outputToProcess.signedMessage + : new TextDecoder().decode(outputToProcess.signedMessage); + signature = outputToProcess.signature; + } + else { + throw new Error('@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields'); + } + } + else { + if (!('signMessage' in resolvedWallet) || + typeof resolvedWallet.signMessage !== 'function' || + !('publicKey' in resolvedWallet) || + typeof resolvedWallet !== 'object' || + !resolvedWallet.publicKey || + !('toBase58' in resolvedWallet.publicKey) || + typeof resolvedWallet.publicKey.toBase58 !== 'function') { + throw new Error('@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API'); + } + message = [ + `${url.host} wants you to sign in with your Solana account:`, + resolvedWallet.publicKey.toBase58(), + ...(statement ? ['', statement, ''] : ['']), + 'Version: 1', + `URI: ${url.href}`, + `Issued At: ${(_c = (_b = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _b === void 0 ? void 0 : _b.issuedAt) !== null && _c !== void 0 ? _c : new Date().toISOString()}`, + ...(((_d = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _d === void 0 ? void 0 : _d.notBefore) + ? [`Not Before: ${options.signInWithSolana.notBefore}`] + : []), + ...(((_e = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _e === void 0 ? void 0 : _e.expirationTime) + ? [`Expiration Time: ${options.signInWithSolana.expirationTime}`] + : []), + ...(((_f = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _f === void 0 ? void 0 : _f.chainId) + ? [`Chain ID: ${options.signInWithSolana.chainId}`] + : []), + ...(((_g = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _g === void 0 ? void 0 : _g.nonce) ? [`Nonce: ${options.signInWithSolana.nonce}`] : []), + ...(((_h = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _h === void 0 ? void 0 : _h.requestId) + ? [`Request ID: ${options.signInWithSolana.requestId}`] + : []), + ...(((_k = (_j = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _j === void 0 ? void 0 : _j.resources) === null || _k === void 0 ? void 0 : _k.length) + ? [ + 'Resources', + ...options.signInWithSolana.resources.map((resource) => `- ${resource}`), + ] + : []), + ].join('\n'); + const maybeSignature = await resolvedWallet.signMessage(new TextEncoder().encode(message), 'utf8'); + if (!maybeSignature || !(maybeSignature instanceof Uint8Array)) { + throw new Error('@supabase/auth-js: Wallet signMessage() API returned an recognized value'); + } + signature = maybeSignature; + } + } + try { + const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=web3`, { + headers: this.headers, + body: Object.assign({ chain: 'solana', message, signature: (0, base64url_1.bytesToBase64URL)(signature) }, (((_l = credentials.options) === null || _l === void 0 ? void 0 : _l.captchaToken) + ? { gotrue_meta_security: { captcha_token: (_m = credentials.options) === null || _m === void 0 ? void 0 : _m.captchaToken } } + : null)), + xform: fetch_1._sessionResponse, + }); + if (error) { + throw error; + } + if (!data || !data.session || !data.user) { + const invalidTokenError = new errors_1.AuthInvalidTokenResponseError(); + return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError }); + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', data.session); + } + return this._returnResult({ data: Object.assign({}, data), error }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + async _exchangeCodeForSession(authCode) { + const storageItem = await (0, helpers_1.getItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + const [codeVerifier, redirectType] = (storageItem !== null && storageItem !== void 0 ? storageItem : '').split('/'); + try { + const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=pkce`, { + headers: this.headers, + body: { + auth_code: authCode, + code_verifier: codeVerifier, + }, + xform: fetch_1._sessionResponse, + }); + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + if (error) { + throw error; + } + if (!data || !data.session || !data.user) { + const invalidTokenError = new errors_1.AuthInvalidTokenResponseError(); + return this._returnResult({ + data: { user: null, session: null, redirectType: null }, + error: invalidTokenError, + }); + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', data.session); + } + return this._returnResult({ data: Object.assign(Object.assign({}, data), { redirectType: redirectType !== null && redirectType !== void 0 ? redirectType : null }), error }); + } + catch (error) { + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ + data: { user: null, session: null, redirectType: null }, + error, + }); + } + throw error; + } + } + /** + * Allows signing in with an OIDC ID token. The authentication provider used + * should be enabled and configured. + */ + async signInWithIdToken(credentials) { + try { + const { options, provider, token, access_token, nonce } = credentials; + const res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=id_token`, { + headers: this.headers, + body: { + provider, + id_token: token, + access_token, + nonce, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + xform: fetch_1._sessionResponse, + }); + const { data, error } = res; + if (error) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + else if (!data || !data.session || !data.user) { + const invalidTokenError = new errors_1.AuthInvalidTokenResponseError(); + return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError }); + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', data.session); + } + return this._returnResult({ data, error }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + /** + * Log in a user using magiclink or a one-time password (OTP). + * + * If the `{{ .ConfirmationURL }}` variable is specified in the email template, a magiclink will be sent. + * If the `{{ .Token }}` variable is specified in the email template, an OTP will be sent. + * If you're using phone sign-ins, only an OTP will be sent. You won't be able to send a magiclink for phone sign-ins. + * + * Be aware that you may get back an error message that will not distinguish + * between the cases where the account does not exist or, that the account + * can only be accessed via social login. + * + * Do note that you will need to configure a Whatsapp sender on Twilio + * if you are using phone sign in with the 'whatsapp' channel. The whatsapp + * channel is not supported on other providers + * at this time. + * This method supports PKCE when an email is passed. + */ + async signInWithOtp(credentials) { + var _a, _b, _c, _d, _e; + try { + if ('email' in credentials) { + const { email, options } = credentials; + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === 'pkce') { + ; + [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey); + } + const { error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/otp`, { + headers: this.headers, + body: { + email, + data: (_a = options === null || options === void 0 ? void 0 : options.data) !== null && _a !== void 0 ? _a : {}, + create_user: (_b = options === null || options === void 0 ? void 0 : options.shouldCreateUser) !== null && _b !== void 0 ? _b : true, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + code_challenge: codeChallenge, + code_challenge_method: codeChallengeMethod, + }, + redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, + }); + return this._returnResult({ data: { user: null, session: null }, error }); + } + if ('phone' in credentials) { + const { phone, options } = credentials; + const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/otp`, { + headers: this.headers, + body: { + phone, + data: (_c = options === null || options === void 0 ? void 0 : options.data) !== null && _c !== void 0 ? _c : {}, + create_user: (_d = options === null || options === void 0 ? void 0 : options.shouldCreateUser) !== null && _d !== void 0 ? _d : true, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + channel: (_e = options === null || options === void 0 ? void 0 : options.channel) !== null && _e !== void 0 ? _e : 'sms', + }, + }); + return this._returnResult({ + data: { user: null, session: null, messageId: data === null || data === void 0 ? void 0 : data.message_id }, + error, + }); + } + throw new errors_1.AuthInvalidCredentialsError('You must provide either an email or phone number.'); + } + catch (error) { + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + /** + * Log in a user given a User supplied OTP or TokenHash received through mobile or email. + */ + async verifyOtp(params) { + var _a, _b; + try { + let redirectTo = undefined; + let captchaToken = undefined; + if ('options' in params) { + redirectTo = (_a = params.options) === null || _a === void 0 ? void 0 : _a.redirectTo; + captchaToken = (_b = params.options) === null || _b === void 0 ? void 0 : _b.captchaToken; + } + const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/verify`, { + headers: this.headers, + body: Object.assign(Object.assign({}, params), { gotrue_meta_security: { captcha_token: captchaToken } }), + redirectTo, + xform: fetch_1._sessionResponse, + }); + if (error) { + throw error; + } + if (!data) { + const tokenVerificationError = new Error('An error occurred on token verification.'); + throw tokenVerificationError; + } + const session = data.session; + const user = data.user; + if (session === null || session === void 0 ? void 0 : session.access_token) { + await this._saveSession(session); + await this._notifyAllSubscribers(params.type == 'recovery' ? 'PASSWORD_RECOVERY' : 'SIGNED_IN', session); + } + return this._returnResult({ data: { user, session }, error: null }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + /** + * Attempts a single-sign on using an enterprise Identity Provider. A + * successful SSO attempt will redirect the current page to the identity + * provider authorization page. The redirect URL is implementation and SSO + * protocol specific. + * + * You can use it by providing a SSO domain. Typically you can extract this + * domain by asking users for their email address. If this domain is + * registered on the Auth instance the redirect will use that organization's + * currently active SSO Identity Provider for the login. + * + * If you have built an organization-specific login page, you can use the + * organization's SSO Identity Provider UUID directly instead. + */ + async signInWithSSO(params) { + var _a, _b, _c, _d, _e; + try { + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === 'pkce') { + ; + [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey); + } + const result = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/sso`, { + body: Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, ('providerId' in params ? { provider_id: params.providerId } : null)), ('domain' in params ? { domain: params.domain } : null)), { redirect_to: (_b = (_a = params.options) === null || _a === void 0 ? void 0 : _a.redirectTo) !== null && _b !== void 0 ? _b : undefined }), (((_c = params === null || params === void 0 ? void 0 : params.options) === null || _c === void 0 ? void 0 : _c.captchaToken) + ? { gotrue_meta_security: { captcha_token: params.options.captchaToken } } + : null)), { skip_http_redirect: true, code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod }), + headers: this.headers, + xform: fetch_1._ssoResponse, + }); + // Automatically redirect in browser unless skipBrowserRedirect is true + if (((_d = result.data) === null || _d === void 0 ? void 0 : _d.url) && (0, helpers_1.isBrowser)() && !((_e = params.options) === null || _e === void 0 ? void 0 : _e.skipBrowserRedirect)) { + window.location.assign(result.data.url); + } + return this._returnResult(result); + } + catch (error) { + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + /** + * Sends a reauthentication OTP to the user's email or phone number. + * Requires the user to be signed-in. + */ + async reauthenticate() { + await this.initializePromise; + return await this._acquireLock(-1, async () => { + return await this._reauthenticate(); + }); + } + async _reauthenticate() { + try { + return await this._useSession(async (result) => { + const { data: { session }, error: sessionError, } = result; + if (sessionError) + throw sessionError; + if (!session) + throw new errors_1.AuthSessionMissingError(); + const { error } = await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/reauthenticate`, { + headers: this.headers, + jwt: session.access_token, + }); + return this._returnResult({ data: { user: null, session: null }, error }); + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + /** + * Resends an existing signup confirmation email, email change email, SMS OTP or phone change OTP. + */ + async resend(credentials) { + try { + const endpoint = `${this.url}/resend`; + if ('email' in credentials) { + const { email, type, options } = credentials; + const { error } = await (0, fetch_1._request)(this.fetch, 'POST', endpoint, { + headers: this.headers, + body: { + email, + type, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, + }); + return this._returnResult({ data: { user: null, session: null }, error }); + } + else if ('phone' in credentials) { + const { phone, type, options } = credentials; + const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', endpoint, { + headers: this.headers, + body: { + phone, + type, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + }); + return this._returnResult({ + data: { user: null, session: null, messageId: data === null || data === void 0 ? void 0 : data.message_id }, + error, + }); + } + throw new errors_1.AuthInvalidCredentialsError('You must provide either an email or phone number and a type'); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + /** + * Returns the session, refreshing it if necessary. + * + * The session returned can be null if the session is not detected which can happen in the event a user is not signed-in or has logged out. + * + * **IMPORTANT:** This method loads values directly from the storage attached + * to the client. If that storage is based on request cookies for example, + * the values in it may not be authentic and therefore it's strongly advised + * against using this method and its results in such circumstances. A warning + * will be emitted if this is detected. Use {@link #getUser()} instead. + */ + async getSession() { + await this.initializePromise; + const result = await this._acquireLock(-1, async () => { + return this._useSession(async (result) => { + return result; + }); + }); + return result; + } + /** + * Acquires a global lock based on the storage key. + */ + async _acquireLock(acquireTimeout, fn) { + this._debug('#_acquireLock', 'begin', acquireTimeout); + try { + if (this.lockAcquired) { + const last = this.pendingInLock.length + ? this.pendingInLock[this.pendingInLock.length - 1] + : Promise.resolve(); + const result = (async () => { + await last; + return await fn(); + })(); + this.pendingInLock.push((async () => { + try { + await result; + } + catch (e) { + // we just care if it finished + } + })()); + return result; + } + return await this.lock(`lock:${this.storageKey}`, acquireTimeout, async () => { + this._debug('#_acquireLock', 'lock acquired for storage key', this.storageKey); + try { + this.lockAcquired = true; + const result = fn(); + this.pendingInLock.push((async () => { + try { + await result; + } + catch (e) { + // we just care if it finished + } + })()); + await result; + // keep draining the queue until there's nothing to wait on + while (this.pendingInLock.length) { + const waitOn = [...this.pendingInLock]; + await Promise.all(waitOn); + this.pendingInLock.splice(0, waitOn.length); + } + return await result; + } + finally { + this._debug('#_acquireLock', 'lock released for storage key', this.storageKey); + this.lockAcquired = false; + } + }); + } + finally { + this._debug('#_acquireLock', 'end'); + } + } + /** + * Use instead of {@link #getSession} inside the library. It is + * semantically usually what you want, as getting a session involves some + * processing afterwards that requires only one client operating on the + * session at once across multiple tabs or processes. + */ + async _useSession(fn) { + this._debug('#_useSession', 'begin'); + try { + // the use of __loadSession here is the only correct use of the function! + const result = await this.__loadSession(); + return await fn(result); + } + finally { + this._debug('#_useSession', 'end'); + } + } + /** + * NEVER USE DIRECTLY! + * + * Always use {@link #_useSession}. + */ + async __loadSession() { + this._debug('#__loadSession()', 'begin'); + if (!this.lockAcquired) { + this._debug('#__loadSession()', 'used outside of an acquired lock!', new Error().stack); + } + try { + let currentSession = null; + const maybeSession = await (0, helpers_1.getItemAsync)(this.storage, this.storageKey); + this._debug('#getSession()', 'session from storage', maybeSession); + if (maybeSession !== null) { + if (this._isValidSession(maybeSession)) { + currentSession = maybeSession; + } + else { + this._debug('#getSession()', 'session from storage is not valid'); + await this._removeSession(); + } + } + if (!currentSession) { + return { data: { session: null }, error: null }; + } + // A session is considered expired before the access token _actually_ + // expires. When the autoRefreshToken option is off (or when the tab is + // in the background), very eager users of getSession() -- like + // realtime-js -- might send a valid JWT which will expire by the time it + // reaches the server. + const hasExpired = currentSession.expires_at + ? currentSession.expires_at * 1000 - Date.now() < constants_1.EXPIRY_MARGIN_MS + : false; + this._debug('#__loadSession()', `session has${hasExpired ? '' : ' not'} expired`, 'expires_at', currentSession.expires_at); + if (!hasExpired) { + if (this.userStorage) { + const maybeUser = (await (0, helpers_1.getItemAsync)(this.userStorage, this.storageKey + '-user')); + if (maybeUser === null || maybeUser === void 0 ? void 0 : maybeUser.user) { + currentSession.user = maybeUser.user; + } + else { + currentSession.user = (0, helpers_1.userNotAvailableProxy)(); + } + } + // Wrap the user object with a warning proxy on the server + // This warns when properties of the user are accessed, not when session.user itself is accessed + if (this.storage.isServer && + currentSession.user && + !currentSession.user.__isUserNotAvailableProxy) { + const suppressWarningRef = { value: this.suppressGetSessionWarning }; + currentSession.user = (0, helpers_1.insecureUserWarningProxy)(currentSession.user, suppressWarningRef); + // Update the client-level suppression flag when the proxy suppresses the warning + if (suppressWarningRef.value) { + this.suppressGetSessionWarning = true; + } + } + return { data: { session: currentSession }, error: null }; + } + const { data: session, error } = await this._callRefreshToken(currentSession.refresh_token); + if (error) { + return this._returnResult({ data: { session: null }, error }); + } + return this._returnResult({ data: { session }, error: null }); + } + finally { + this._debug('#__loadSession()', 'end'); + } + } + /** + * Gets the current user details if there is an existing session. This method + * performs a network request to the Supabase Auth server, so the returned + * value is authentic and can be used to base authorization rules on. + * + * @param jwt Takes in an optional access token JWT. If no JWT is provided, the JWT from the current session is used. + */ + async getUser(jwt) { + if (jwt) { + return await this._getUser(jwt); + } + await this.initializePromise; + const result = await this._acquireLock(-1, async () => { + return await this._getUser(); + }); + if (result.data.user) { + this.suppressGetSessionWarning = true; + } + return result; + } + async _getUser(jwt) { + try { + if (jwt) { + return await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/user`, { + headers: this.headers, + jwt: jwt, + xform: fetch_1._userResponse, + }); + } + return await this._useSession(async (result) => { + var _a, _b, _c; + const { data, error } = result; + if (error) { + throw error; + } + // returns an error if there is no access_token or custom authorization header + if (!((_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) && !this.hasCustomAuthorizationHeader) { + return { data: { user: null }, error: new errors_1.AuthSessionMissingError() }; + } + return await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/user`, { + headers: this.headers, + jwt: (_c = (_b = data.session) === null || _b === void 0 ? void 0 : _b.access_token) !== null && _c !== void 0 ? _c : undefined, + xform: fetch_1._userResponse, + }); + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + if ((0, errors_1.isAuthSessionMissingError)(error)) { + // JWT contains a `session_id` which does not correspond to an active + // session in the database, indicating the user is signed out. + await this._removeSession(); + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + } + return this._returnResult({ data: { user: null }, error }); + } + throw error; + } + } + /** + * Updates user data for a logged in user. + */ + async updateUser(attributes, options = {}) { + await this.initializePromise; + return await this._acquireLock(-1, async () => { + return await this._updateUser(attributes, options); + }); + } + async _updateUser(attributes, options = {}) { + try { + return await this._useSession(async (result) => { + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + throw sessionError; + } + if (!sessionData.session) { + throw new errors_1.AuthSessionMissingError(); + } + const session = sessionData.session; + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === 'pkce' && attributes.email != null) { + ; + [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey); + } + const { data, error: userError } = await (0, fetch_1._request)(this.fetch, 'PUT', `${this.url}/user`, { + headers: this.headers, + redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, + body: Object.assign(Object.assign({}, attributes), { code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod }), + jwt: session.access_token, + xform: fetch_1._userResponse, + }); + if (userError) { + throw userError; + } + session.user = data.user; + await this._saveSession(session); + await this._notifyAllSubscribers('USER_UPDATED', session); + return this._returnResult({ data: { user: session.user }, error: null }); + }); + } + catch (error) { + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null }, error }); + } + throw error; + } + } + /** + * Sets the session data from the current session. If the current session is expired, setSession will take care of refreshing it to obtain a new session. + * If the refresh token or access token in the current session is invalid, an error will be thrown. + * @param currentSession The current session that minimally contains an access token and refresh token. + */ + async setSession(currentSession) { + await this.initializePromise; + return await this._acquireLock(-1, async () => { + return await this._setSession(currentSession); + }); + } + async _setSession(currentSession) { + try { + if (!currentSession.access_token || !currentSession.refresh_token) { + throw new errors_1.AuthSessionMissingError(); + } + const timeNow = Date.now() / 1000; + let expiresAt = timeNow; + let hasExpired = true; + let session = null; + const { payload } = (0, helpers_1.decodeJWT)(currentSession.access_token); + if (payload.exp) { + expiresAt = payload.exp; + hasExpired = expiresAt <= timeNow; + } + if (hasExpired) { + const { data: refreshedSession, error } = await this._callRefreshToken(currentSession.refresh_token); + if (error) { + return this._returnResult({ data: { user: null, session: null }, error: error }); + } + if (!refreshedSession) { + return { data: { user: null, session: null }, error: null }; + } + session = refreshedSession; + } + else { + const { data, error } = await this._getUser(currentSession.access_token); + if (error) { + throw error; + } + session = { + access_token: currentSession.access_token, + refresh_token: currentSession.refresh_token, + user: data.user, + token_type: 'bearer', + expires_in: expiresAt - timeNow, + expires_at: expiresAt, + }; + await this._saveSession(session); + await this._notifyAllSubscribers('SIGNED_IN', session); + } + return this._returnResult({ data: { user: session.user, session }, error: null }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { session: null, user: null }, error }); + } + throw error; + } + } + /** + * Returns a new session, regardless of expiry status. + * Takes in an optional current session. If not passed in, then refreshSession() will attempt to retrieve it from getSession(). + * If the current session's refresh token is invalid, an error will be thrown. + * @param currentSession The current session. If passed in, it must contain a refresh token. + */ + async refreshSession(currentSession) { + await this.initializePromise; + return await this._acquireLock(-1, async () => { + return await this._refreshSession(currentSession); + }); + } + async _refreshSession(currentSession) { + try { + return await this._useSession(async (result) => { + var _a; + if (!currentSession) { + const { data, error } = result; + if (error) { + throw error; + } + currentSession = (_a = data.session) !== null && _a !== void 0 ? _a : undefined; + } + if (!(currentSession === null || currentSession === void 0 ? void 0 : currentSession.refresh_token)) { + throw new errors_1.AuthSessionMissingError(); + } + const { data: session, error } = await this._callRefreshToken(currentSession.refresh_token); + if (error) { + return this._returnResult({ data: { user: null, session: null }, error: error }); + } + if (!session) { + return this._returnResult({ data: { user: null, session: null }, error: null }); + } + return this._returnResult({ data: { user: session.user, session }, error: null }); + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + /** + * Gets the session data from a URL string + */ + async _getSessionFromURL(params, callbackUrlType) { + try { + if (!(0, helpers_1.isBrowser)()) + throw new errors_1.AuthImplicitGrantRedirectError('No browser detected.'); + // If there's an error in the URL, it doesn't matter what flow it is, we just return the error. + if (params.error || params.error_description || params.error_code) { + // The error class returned implies that the redirect is from an implicit grant flow + // but it could also be from a redirect error from a PKCE flow. + throw new errors_1.AuthImplicitGrantRedirectError(params.error_description || 'Error in URL with unspecified error_description', { + error: params.error || 'unspecified_error', + code: params.error_code || 'unspecified_code', + }); + } + // Checks for mismatches between the flowType initialised in the client and the URL parameters + switch (callbackUrlType) { + case 'implicit': + if (this.flowType === 'pkce') { + throw new errors_1.AuthPKCEGrantCodeExchangeError('Not a valid PKCE flow url.'); + } + break; + case 'pkce': + if (this.flowType === 'implicit') { + throw new errors_1.AuthImplicitGrantRedirectError('Not a valid implicit grant flow url.'); + } + break; + default: + // there's no mismatch so we continue + } + // Since this is a redirect for PKCE, we attempt to retrieve the code from the URL for the code exchange + if (callbackUrlType === 'pkce') { + this._debug('#_initialize()', 'begin', 'is PKCE flow', true); + if (!params.code) + throw new errors_1.AuthPKCEGrantCodeExchangeError('No code detected.'); + const { data, error } = await this._exchangeCodeForSession(params.code); + if (error) + throw error; + const url = new URL(window.location.href); + url.searchParams.delete('code'); + window.history.replaceState(window.history.state, '', url.toString()); + return { data: { session: data.session, redirectType: null }, error: null }; + } + const { provider_token, provider_refresh_token, access_token, refresh_token, expires_in, expires_at, token_type, } = params; + if (!access_token || !expires_in || !refresh_token || !token_type) { + throw new errors_1.AuthImplicitGrantRedirectError('No session defined in URL'); + } + const timeNow = Math.round(Date.now() / 1000); + const expiresIn = parseInt(expires_in); + let expiresAt = timeNow + expiresIn; + if (expires_at) { + expiresAt = parseInt(expires_at); + } + const actuallyExpiresIn = expiresAt - timeNow; + if (actuallyExpiresIn * 1000 <= constants_1.AUTO_REFRESH_TICK_DURATION_MS) { + console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${actuallyExpiresIn}s, should have been closer to ${expiresIn}s`); + } + const issuedAt = expiresAt - expiresIn; + if (timeNow - issuedAt >= 120) { + console.warn('@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale', issuedAt, expiresAt, timeNow); + } + else if (timeNow - issuedAt < 0) { + console.warn('@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew', issuedAt, expiresAt, timeNow); + } + const { data, error } = await this._getUser(access_token); + if (error) + throw error; + const session = { + provider_token, + provider_refresh_token, + access_token, + expires_in: expiresIn, + expires_at: expiresAt, + refresh_token, + token_type: token_type, + user: data.user, + }; + // Remove tokens from URL + window.location.hash = ''; + this._debug('#_getSessionFromURL()', 'clearing window.location.hash'); + return this._returnResult({ data: { session, redirectType: params.type }, error: null }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { session: null, redirectType: null }, error }); + } + throw error; + } + } + /** + * Checks if the current URL contains parameters given by an implicit oauth grant flow (https://www.rfc-editor.org/rfc/rfc6749.html#section-4.2) + */ + _isImplicitGrantCallback(params) { + return Boolean(params.access_token || params.error_description); + } + /** + * Checks if the current URL and backing storage contain parameters given by a PKCE flow + */ + async _isPKCECallback(params) { + const currentStorageContent = await (0, helpers_1.getItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + return !!(params.code && currentStorageContent); + } + /** + * Inside a browser context, `signOut()` will remove the logged in user from the browser session and log them out - removing all items from localstorage and then trigger a `"SIGNED_OUT"` event. + * + * For server-side management, you can revoke all refresh tokens for a user by passing a user's JWT through to `auth.api.signOut(JWT: string)`. + * There is no way to revoke a user's access token jwt until it expires. It is recommended to set a shorter expiry on the jwt for this reason. + * + * If using `others` scope, no `SIGNED_OUT` event is fired! + */ + async signOut(options = { scope: 'global' }) { + await this.initializePromise; + return await this._acquireLock(-1, async () => { + return await this._signOut(options); + }); + } + async _signOut({ scope } = { scope: 'global' }) { + return await this._useSession(async (result) => { + var _a; + const { data, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ error: sessionError }); + } + const accessToken = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token; + if (accessToken) { + const { error } = await this.admin.signOut(accessToken, scope); + if (error) { + // ignore 404s since user might not exist anymore + // ignore 401s since an invalid or expired JWT should sign out the current session + if (!((0, errors_1.isAuthApiError)(error) && + (error.status === 404 || error.status === 401 || error.status === 403))) { + return this._returnResult({ error }); + } + } + } + if (scope !== 'others') { + await this._removeSession(); + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + } + return this._returnResult({ error: null }); + }); + } + onAuthStateChange(callback) { + const id = (0, helpers_1.generateCallbackId)(); + const subscription = { + id, + callback, + unsubscribe: () => { + this._debug('#unsubscribe()', 'state change callback with id removed', id); + this.stateChangeEmitters.delete(id); + }, + }; + this._debug('#onAuthStateChange()', 'registered callback with id', id); + this.stateChangeEmitters.set(id, subscription); + (async () => { + await this.initializePromise; + await this._acquireLock(-1, async () => { + this._emitInitialSession(id); + }); + })(); + return { data: { subscription } }; + } + async _emitInitialSession(id) { + return await this._useSession(async (result) => { + var _a, _b; + try { + const { data: { session }, error, } = result; + if (error) + throw error; + await ((_a = this.stateChangeEmitters.get(id)) === null || _a === void 0 ? void 0 : _a.callback('INITIAL_SESSION', session)); + this._debug('INITIAL_SESSION', 'callback id', id, 'session', session); + } + catch (err) { + await ((_b = this.stateChangeEmitters.get(id)) === null || _b === void 0 ? void 0 : _b.callback('INITIAL_SESSION', null)); + this._debug('INITIAL_SESSION', 'callback id', id, 'error', err); + console.error(err); + } + }); + } + /** + * Sends a password reset request to an email address. This method supports the PKCE flow. + * + * @param email The email address of the user. + * @param options.redirectTo The URL to send the user to after they click the password reset link. + * @param options.captchaToken Verification token received when the user completes the captcha on the site. + */ + async resetPasswordForEmail(email, options = {}) { + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === 'pkce') { + ; + [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey, true // isPasswordRecovery + ); + } + try { + return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/recover`, { + body: { + email, + code_challenge: codeChallenge, + code_challenge_method: codeChallengeMethod, + gotrue_meta_security: { captcha_token: options.captchaToken }, + }, + headers: this.headers, + redirectTo: options.redirectTo, + }); + } + catch (error) { + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + /** + * Gets all the identities linked to a user. + */ + async getUserIdentities() { + var _a; + try { + const { data, error } = await this.getUser(); + if (error) + throw error; + return this._returnResult({ data: { identities: (_a = data.user.identities) !== null && _a !== void 0 ? _a : [] }, error: null }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + async linkIdentity(credentials) { + if ('token' in credentials) { + return this.linkIdentityIdToken(credentials); + } + return this.linkIdentityOAuth(credentials); + } + async linkIdentityOAuth(credentials) { + var _a; + try { + const { data, error } = await this._useSession(async (result) => { + var _a, _b, _c, _d, _e; + const { data, error } = result; + if (error) + throw error; + const url = await this._getUrlForProvider(`${this.url}/user/identities/authorize`, credentials.provider, { + redirectTo: (_a = credentials.options) === null || _a === void 0 ? void 0 : _a.redirectTo, + scopes: (_b = credentials.options) === null || _b === void 0 ? void 0 : _b.scopes, + queryParams: (_c = credentials.options) === null || _c === void 0 ? void 0 : _c.queryParams, + skipBrowserRedirect: true, + }); + return await (0, fetch_1._request)(this.fetch, 'GET', url, { + headers: this.headers, + jwt: (_e = (_d = data.session) === null || _d === void 0 ? void 0 : _d.access_token) !== null && _e !== void 0 ? _e : undefined, + }); + }); + if (error) + throw error; + if ((0, helpers_1.isBrowser)() && !((_a = credentials.options) === null || _a === void 0 ? void 0 : _a.skipBrowserRedirect)) { + window.location.assign(data === null || data === void 0 ? void 0 : data.url); + } + return this._returnResult({ + data: { provider: credentials.provider, url: data === null || data === void 0 ? void 0 : data.url }, + error: null, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { provider: credentials.provider, url: null }, error }); + } + throw error; + } + } + async linkIdentityIdToken(credentials) { + return await this._useSession(async (result) => { + var _a; + try { + const { error: sessionError, data: { session }, } = result; + if (sessionError) + throw sessionError; + const { options, provider, token, access_token, nonce } = credentials; + const res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=id_token`, { + headers: this.headers, + jwt: (_a = session === null || session === void 0 ? void 0 : session.access_token) !== null && _a !== void 0 ? _a : undefined, + body: { + provider, + id_token: token, + access_token, + nonce, + link_identity: true, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + xform: fetch_1._sessionResponse, + }); + const { data, error } = res; + if (error) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + else if (!data || !data.session || !data.user) { + return this._returnResult({ + data: { user: null, session: null }, + error: new errors_1.AuthInvalidTokenResponseError(), + }); + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('USER_UPDATED', data.session); + } + return this._returnResult({ data, error }); + } + catch (error) { + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + }); + } + /** + * Unlinks an identity from a user by deleting it. The user will no longer be able to sign in with that identity once it's unlinked. + */ + async unlinkIdentity(identity) { + try { + return await this._useSession(async (result) => { + var _a, _b; + const { data, error } = result; + if (error) { + throw error; + } + return await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/user/identities/${identity.identity_id}`, { + headers: this.headers, + jwt: (_b = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) !== null && _b !== void 0 ? _b : undefined, + }); + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + /** + * Generates a new JWT. + * @param refreshToken A valid refresh token that was returned on login. + */ + async _refreshAccessToken(refreshToken) { + const debugName = `#_refreshAccessToken(${refreshToken.substring(0, 5)}...)`; + this._debug(debugName, 'begin'); + try { + const startedAt = Date.now(); + // will attempt to refresh the token with exponential backoff + return await (0, helpers_1.retryable)(async (attempt) => { + if (attempt > 0) { + await (0, helpers_1.sleep)(200 * Math.pow(2, attempt - 1)); // 200, 400, 800, ... + } + this._debug(debugName, 'refreshing attempt', attempt); + return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=refresh_token`, { + body: { refresh_token: refreshToken }, + headers: this.headers, + xform: fetch_1._sessionResponse, + }); + }, (attempt, error) => { + const nextBackOffInterval = 200 * Math.pow(2, attempt); + return (error && + (0, errors_1.isAuthRetryableFetchError)(error) && + // retryable only if the request can be sent before the backoff overflows the tick duration + Date.now() + nextBackOffInterval - startedAt < constants_1.AUTO_REFRESH_TICK_DURATION_MS); + }); + } + catch (error) { + this._debug(debugName, 'error', error); + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { session: null, user: null }, error }); + } + throw error; + } + finally { + this._debug(debugName, 'end'); + } + } + _isValidSession(maybeSession) { + const isValidSession = typeof maybeSession === 'object' && + maybeSession !== null && + 'access_token' in maybeSession && + 'refresh_token' in maybeSession && + 'expires_at' in maybeSession; + return isValidSession; + } + async _handleProviderSignIn(provider, options) { + const url = await this._getUrlForProvider(`${this.url}/authorize`, provider, { + redirectTo: options.redirectTo, + scopes: options.scopes, + queryParams: options.queryParams, + }); + this._debug('#_handleProviderSignIn()', 'provider', provider, 'options', options, 'url', url); + // try to open on the browser + if ((0, helpers_1.isBrowser)() && !options.skipBrowserRedirect) { + window.location.assign(url); + } + return { data: { provider, url }, error: null }; + } + /** + * Recovers the session from LocalStorage and refreshes the token + * Note: this method is async to accommodate for AsyncStorage e.g. in React native. + */ + async _recoverAndRefresh() { + var _a, _b; + const debugName = '#_recoverAndRefresh()'; + this._debug(debugName, 'begin'); + try { + const currentSession = (await (0, helpers_1.getItemAsync)(this.storage, this.storageKey)); + if (currentSession && this.userStorage) { + let maybeUser = (await (0, helpers_1.getItemAsync)(this.userStorage, this.storageKey + '-user')); + if (!this.storage.isServer && Object.is(this.storage, this.userStorage) && !maybeUser) { + // storage and userStorage are the same storage medium, for example + // window.localStorage if userStorage does not have the user from + // storage stored, store it first thereby migrating the user object + // from storage -> userStorage + maybeUser = { user: currentSession.user }; + await (0, helpers_1.setItemAsync)(this.userStorage, this.storageKey + '-user', maybeUser); + } + currentSession.user = (_a = maybeUser === null || maybeUser === void 0 ? void 0 : maybeUser.user) !== null && _a !== void 0 ? _a : (0, helpers_1.userNotAvailableProxy)(); + } + else if (currentSession && !currentSession.user) { + // user storage is not set, let's check if it was previously enabled so + // we bring back the storage as it should be + if (!currentSession.user) { + // test if userStorage was previously enabled and the storage medium was the same, to move the user back under the same key + const separateUser = (await (0, helpers_1.getItemAsync)(this.storage, this.storageKey + '-user')); + if (separateUser && (separateUser === null || separateUser === void 0 ? void 0 : separateUser.user)) { + currentSession.user = separateUser.user; + await (0, helpers_1.removeItemAsync)(this.storage, this.storageKey + '-user'); + await (0, helpers_1.setItemAsync)(this.storage, this.storageKey, currentSession); + } + else { + currentSession.user = (0, helpers_1.userNotAvailableProxy)(); + } + } + } + this._debug(debugName, 'session from storage', currentSession); + if (!this._isValidSession(currentSession)) { + this._debug(debugName, 'session is not valid'); + if (currentSession !== null) { + await this._removeSession(); + } + return; + } + const expiresWithMargin = ((_b = currentSession.expires_at) !== null && _b !== void 0 ? _b : Infinity) * 1000 - Date.now() < constants_1.EXPIRY_MARGIN_MS; + this._debug(debugName, `session has${expiresWithMargin ? '' : ' not'} expired with margin of ${constants_1.EXPIRY_MARGIN_MS}s`); + if (expiresWithMargin) { + if (this.autoRefreshToken && currentSession.refresh_token) { + const { error } = await this._callRefreshToken(currentSession.refresh_token); + if (error) { + console.error(error); + if (!(0, errors_1.isAuthRetryableFetchError)(error)) { + this._debug(debugName, 'refresh failed with a non-retryable error, removing the session', error); + await this._removeSession(); + } + } + } + } + else if (currentSession.user && + currentSession.user.__isUserNotAvailableProxy === true) { + // If we have a proxy user, try to get the real user data + try { + const { data, error: userError } = await this._getUser(currentSession.access_token); + if (!userError && (data === null || data === void 0 ? void 0 : data.user)) { + currentSession.user = data.user; + await this._saveSession(currentSession); + await this._notifyAllSubscribers('SIGNED_IN', currentSession); + } + else { + this._debug(debugName, 'could not get user data, skipping SIGNED_IN notification'); + } + } + catch (getUserError) { + console.error('Error getting user data:', getUserError); + this._debug(debugName, 'error getting user data, skipping SIGNED_IN notification', getUserError); + } + } + else { + // no need to persist currentSession again, as we just loaded it from + // local storage; persisting it again may overwrite a value saved by + // another client with access to the same local storage + await this._notifyAllSubscribers('SIGNED_IN', currentSession); + } + } + catch (err) { + this._debug(debugName, 'error', err); + console.error(err); + return; + } + finally { + this._debug(debugName, 'end'); + } + } + async _callRefreshToken(refreshToken) { + var _a, _b; + if (!refreshToken) { + throw new errors_1.AuthSessionMissingError(); + } + // refreshing is already in progress + if (this.refreshingDeferred) { + return this.refreshingDeferred.promise; + } + const debugName = `#_callRefreshToken(${refreshToken.substring(0, 5)}...)`; + this._debug(debugName, 'begin'); + try { + this.refreshingDeferred = new helpers_1.Deferred(); + const { data, error } = await this._refreshAccessToken(refreshToken); + if (error) + throw error; + if (!data.session) + throw new errors_1.AuthSessionMissingError(); + await this._saveSession(data.session); + await this._notifyAllSubscribers('TOKEN_REFRESHED', data.session); + const result = { data: data.session, error: null }; + this.refreshingDeferred.resolve(result); + return result; + } + catch (error) { + this._debug(debugName, 'error', error); + if ((0, errors_1.isAuthError)(error)) { + const result = { data: null, error }; + if (!(0, errors_1.isAuthRetryableFetchError)(error)) { + await this._removeSession(); + } + (_a = this.refreshingDeferred) === null || _a === void 0 ? void 0 : _a.resolve(result); + return result; + } + (_b = this.refreshingDeferred) === null || _b === void 0 ? void 0 : _b.reject(error); + throw error; + } + finally { + this.refreshingDeferred = null; + this._debug(debugName, 'end'); + } + } + async _notifyAllSubscribers(event, session, broadcast = true) { + const debugName = `#_notifyAllSubscribers(${event})`; + this._debug(debugName, 'begin', session, `broadcast = ${broadcast}`); + try { + if (this.broadcastChannel && broadcast) { + this.broadcastChannel.postMessage({ event, session }); + } + const errors = []; + const promises = Array.from(this.stateChangeEmitters.values()).map(async (x) => { + try { + await x.callback(event, session); + } + catch (e) { + errors.push(e); + } + }); + await Promise.all(promises); + if (errors.length > 0) { + for (let i = 0; i < errors.length; i += 1) { + console.error(errors[i]); + } + throw errors[0]; + } + } + finally { + this._debug(debugName, 'end'); + } + } + /** + * set currentSession and currentUser + * process to _startAutoRefreshToken if possible + */ + async _saveSession(session) { + this._debug('#_saveSession()', session); + // _saveSession is always called whenever a new session has been acquired + // so we can safely suppress the warning returned by future getSession calls + this.suppressGetSessionWarning = true; + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + // Create a shallow copy to work with, to avoid mutating the original session object if it's used elsewhere + const sessionToProcess = Object.assign({}, session); + const userIsProxy = sessionToProcess.user && sessionToProcess.user.__isUserNotAvailableProxy === true; + if (this.userStorage) { + if (!userIsProxy && sessionToProcess.user) { + // If it's a real user object, save it to userStorage. + await (0, helpers_1.setItemAsync)(this.userStorage, this.storageKey + '-user', { + user: sessionToProcess.user, + }); + } + else if (userIsProxy) { + // If it's the proxy, it means user was not found in userStorage. + // We should ensure no stale user data for this key exists in userStorage if we were to save null, + // or simply not save the proxy. For now, we don't save the proxy here. + // If there's a need to clear userStorage if user becomes proxy, that logic would go here. + } + // Prepare the main session data for primary storage: remove the user property before cloning + // This is important because the original session.user might be the proxy + const mainSessionData = Object.assign({}, sessionToProcess); + delete mainSessionData.user; // Remove user (real or proxy) before cloning for main storage + const clonedMainSessionData = (0, helpers_1.deepClone)(mainSessionData); + await (0, helpers_1.setItemAsync)(this.storage, this.storageKey, clonedMainSessionData); + } + else { + // No userStorage is configured. + // In this case, session.user should ideally not be a proxy. + // If it were, structuredClone would fail. This implies an issue elsewhere if user is a proxy here + const clonedSession = (0, helpers_1.deepClone)(sessionToProcess); // sessionToProcess still has its original user property + await (0, helpers_1.setItemAsync)(this.storage, this.storageKey, clonedSession); + } + } + async _removeSession() { + this._debug('#_removeSession()'); + this.suppressGetSessionWarning = false; + await (0, helpers_1.removeItemAsync)(this.storage, this.storageKey); + await (0, helpers_1.removeItemAsync)(this.storage, this.storageKey + '-code-verifier'); + await (0, helpers_1.removeItemAsync)(this.storage, this.storageKey + '-user'); + if (this.userStorage) { + await (0, helpers_1.removeItemAsync)(this.userStorage, this.storageKey + '-user'); + } + await this._notifyAllSubscribers('SIGNED_OUT', null); + } + /** + * Removes any registered visibilitychange callback. + * + * {@see #startAutoRefresh} + * {@see #stopAutoRefresh} + */ + _removeVisibilityChangedCallback() { + this._debug('#_removeVisibilityChangedCallback()'); + const callback = this.visibilityChangedCallback; + this.visibilityChangedCallback = null; + try { + if (callback && (0, helpers_1.isBrowser)() && (window === null || window === void 0 ? void 0 : window.removeEventListener)) { + window.removeEventListener('visibilitychange', callback); + } + } + catch (e) { + console.error('removing visibilitychange callback failed', e); + } + } + /** + * This is the private implementation of {@link #startAutoRefresh}. Use this + * within the library. + */ + async _startAutoRefresh() { + await this._stopAutoRefresh(); + this._debug('#_startAutoRefresh()'); + const ticker = setInterval(() => this._autoRefreshTokenTick(), constants_1.AUTO_REFRESH_TICK_DURATION_MS); + this.autoRefreshTicker = ticker; + if (ticker && typeof ticker === 'object' && typeof ticker.unref === 'function') { + // ticker is a NodeJS Timeout object that has an `unref` method + // https://nodejs.org/api/timers.html#timeoutunref + // When auto refresh is used in NodeJS (like for testing) the + // `setInterval` is preventing the process from being marked as + // finished and tests run endlessly. This can be prevented by calling + // `unref()` on the returned object. + ticker.unref(); + // @ts-expect-error TS has no context of Deno + } + else if (typeof Deno !== 'undefined' && typeof Deno.unrefTimer === 'function') { + // similar like for NodeJS, but with the Deno API + // https://deno.land/api@latest?unstable&s=Deno.unrefTimer + // @ts-expect-error TS has no context of Deno + Deno.unrefTimer(ticker); + } + // run the tick immediately, but in the next pass of the event loop so that + // #_initialize can be allowed to complete without recursively waiting on + // itself + setTimeout(async () => { + await this.initializePromise; + await this._autoRefreshTokenTick(); + }, 0); + } + /** + * This is the private implementation of {@link #stopAutoRefresh}. Use this + * within the library. + */ + async _stopAutoRefresh() { + this._debug('#_stopAutoRefresh()'); + const ticker = this.autoRefreshTicker; + this.autoRefreshTicker = null; + if (ticker) { + clearInterval(ticker); + } + } + /** + * Starts an auto-refresh process in the background. The session is checked + * every few seconds. Close to the time of expiration a process is started to + * refresh the session. If refreshing fails it will be retried for as long as + * necessary. + * + * If you set the {@link GoTrueClientOptions#autoRefreshToken} you don't need + * to call this function, it will be called for you. + * + * On browsers the refresh process works only when the tab/window is in the + * foreground to conserve resources as well as prevent race conditions and + * flooding auth with requests. If you call this method any managed + * visibility change callback will be removed and you must manage visibility + * changes on your own. + * + * On non-browser platforms the refresh process works *continuously* in the + * background, which may not be desirable. You should hook into your + * platform's foreground indication mechanism and call these methods + * appropriately to conserve resources. + * + * {@see #stopAutoRefresh} + */ + async startAutoRefresh() { + this._removeVisibilityChangedCallback(); + await this._startAutoRefresh(); + } + /** + * Stops an active auto refresh process running in the background (if any). + * + * If you call this method any managed visibility change callback will be + * removed and you must manage visibility changes on your own. + * + * See {@link #startAutoRefresh} for more details. + */ + async stopAutoRefresh() { + this._removeVisibilityChangedCallback(); + await this._stopAutoRefresh(); + } + /** + * Runs the auto refresh token tick. + */ + async _autoRefreshTokenTick() { + this._debug('#_autoRefreshTokenTick()', 'begin'); + try { + await this._acquireLock(0, async () => { + try { + const now = Date.now(); + try { + return await this._useSession(async (result) => { + const { data: { session }, } = result; + if (!session || !session.refresh_token || !session.expires_at) { + this._debug('#_autoRefreshTokenTick()', 'no session'); + return; + } + // session will expire in this many ticks (or has already expired if <= 0) + const expiresInTicks = Math.floor((session.expires_at * 1000 - now) / constants_1.AUTO_REFRESH_TICK_DURATION_MS); + this._debug('#_autoRefreshTokenTick()', `access token expires in ${expiresInTicks} ticks, a tick lasts ${constants_1.AUTO_REFRESH_TICK_DURATION_MS}ms, refresh threshold is ${constants_1.AUTO_REFRESH_TICK_THRESHOLD} ticks`); + if (expiresInTicks <= constants_1.AUTO_REFRESH_TICK_THRESHOLD) { + await this._callRefreshToken(session.refresh_token); + } + }); + } + catch (e) { + console.error('Auto refresh tick failed with error. This is likely a transient error.', e); + } + } + finally { + this._debug('#_autoRefreshTokenTick()', 'end'); + } + }); + } + catch (e) { + if (e.isAcquireTimeout || e instanceof locks_1.LockAcquireTimeoutError) { + this._debug('auto refresh token tick lock not available'); + } + else { + throw e; + } + } + } + /** + * Registers callbacks on the browser / platform, which in-turn run + * algorithms when the browser window/tab are in foreground. On non-browser + * platforms it assumes always foreground. + */ + async _handleVisibilityChange() { + this._debug('#_handleVisibilityChange()'); + if (!(0, helpers_1.isBrowser)() || !(window === null || window === void 0 ? void 0 : window.addEventListener)) { + if (this.autoRefreshToken) { + // in non-browser environments the refresh token ticker runs always + this.startAutoRefresh(); + } + return false; + } + try { + this.visibilityChangedCallback = async () => await this._onVisibilityChanged(false); + window === null || window === void 0 ? void 0 : window.addEventListener('visibilitychange', this.visibilityChangedCallback); + // now immediately call the visbility changed callback to setup with the + // current visbility state + await this._onVisibilityChanged(true); // initial call + } + catch (error) { + console.error('_handleVisibilityChange', error); + } + } + /** + * Callback registered with `window.addEventListener('visibilitychange')`. + */ + async _onVisibilityChanged(calledFromInitialize) { + const methodName = `#_onVisibilityChanged(${calledFromInitialize})`; + this._debug(methodName, 'visibilityState', document.visibilityState); + if (document.visibilityState === 'visible') { + if (this.autoRefreshToken) { + // in browser environments the refresh token ticker runs only on focused tabs + // which prevents race conditions + this._startAutoRefresh(); + } + if (!calledFromInitialize) { + // called when the visibility has changed, i.e. the browser + // transitioned from hidden -> visible so we need to see if the session + // should be recovered immediately... but to do that we need to acquire + // the lock first asynchronously + await this.initializePromise; + await this._acquireLock(-1, async () => { + if (document.visibilityState !== 'visible') { + this._debug(methodName, 'acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting'); + // visibility has changed while waiting for the lock, abort + return; + } + // recover the session + await this._recoverAndRefresh(); + }); + } + } + else if (document.visibilityState === 'hidden') { + if (this.autoRefreshToken) { + this._stopAutoRefresh(); + } + } + } + /** + * Generates the relevant login URL for a third-party provider. + * @param options.redirectTo A URL or mobile address to send the user to after they are confirmed. + * @param options.scopes A space-separated list of scopes granted to the OAuth application. + * @param options.queryParams An object of key-value pairs containing query parameters granted to the OAuth application. + */ + async _getUrlForProvider(url, provider, options) { + const urlParams = [`provider=${encodeURIComponent(provider)}`]; + if (options === null || options === void 0 ? void 0 : options.redirectTo) { + urlParams.push(`redirect_to=${encodeURIComponent(options.redirectTo)}`); + } + if (options === null || options === void 0 ? void 0 : options.scopes) { + urlParams.push(`scopes=${encodeURIComponent(options.scopes)}`); + } + if (this.flowType === 'pkce') { + const [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey); + const flowParams = new URLSearchParams({ + code_challenge: `${encodeURIComponent(codeChallenge)}`, + code_challenge_method: `${encodeURIComponent(codeChallengeMethod)}`, + }); + urlParams.push(flowParams.toString()); + } + if (options === null || options === void 0 ? void 0 : options.queryParams) { + const query = new URLSearchParams(options.queryParams); + urlParams.push(query.toString()); + } + if (options === null || options === void 0 ? void 0 : options.skipBrowserRedirect) { + urlParams.push(`skip_http_redirect=${options.skipBrowserRedirect}`); + } + return `${url}?${urlParams.join('&')}`; + } + async _unenroll(params) { + try { + return await this._useSession(async (result) => { + var _a; + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + return await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/factors/${params.factorId}`, { + headers: this.headers, + jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, + }); + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + async _enroll(params) { + try { + return await this._useSession(async (result) => { + var _a, _b; + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + const body = Object.assign({ friendly_name: params.friendlyName, factor_type: params.factorType }, (params.factorType === 'phone' + ? { phone: params.phone } + : params.factorType === 'totp' + ? { issuer: params.issuer } + : {})); + const { data, error } = (await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/factors`, { + body, + headers: this.headers, + jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, + })); + if (error) { + return this._returnResult({ data: null, error }); + } + if (params.factorType === 'totp' && data.type === 'totp' && ((_b = data === null || data === void 0 ? void 0 : data.totp) === null || _b === void 0 ? void 0 : _b.qr_code)) { + data.totp.qr_code = `data:image/svg+xml;utf-8,${data.totp.qr_code}`; + } + return this._returnResult({ data, error: null }); + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + async _verify(params) { + return this._acquireLock(-1, async () => { + try { + return await this._useSession(async (result) => { + var _a; + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + const body = Object.assign({ challenge_id: params.challengeId }, ('webauthn' in params + ? { + webauthn: Object.assign(Object.assign({}, params.webauthn), { credential_response: params.webauthn.type === 'create' + ? (0, webauthn_1.serializeCredentialCreationResponse)(params.webauthn.credential_response) + : (0, webauthn_1.serializeCredentialRequestResponse)(params.webauthn.credential_response) }), + } + : { code: params.code })); + const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/factors/${params.factorId}/verify`, { + body, + headers: this.headers, + jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, + }); + if (error) { + return this._returnResult({ data: null, error }); + } + await this._saveSession(Object.assign({ expires_at: Math.round(Date.now() / 1000) + data.expires_in }, data)); + await this._notifyAllSubscribers('MFA_CHALLENGE_VERIFIED', data); + return this._returnResult({ data, error }); + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + }); + } + async _challenge(params) { + return this._acquireLock(-1, async () => { + try { + return await this._useSession(async (result) => { + var _a; + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + const response = (await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/factors/${params.factorId}/challenge`, { + body: params, + headers: this.headers, + jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, + })); + if (response.error) { + return response; + } + const { data } = response; + if (data.type !== 'webauthn') { + return { data, error: null }; + } + switch (data.webauthn.type) { + case 'create': + return { + data: Object.assign(Object.assign({}, data), { webauthn: Object.assign(Object.assign({}, data.webauthn), { credential_options: Object.assign(Object.assign({}, data.webauthn.credential_options), { publicKey: (0, webauthn_1.deserializeCredentialCreationOptions)(data.webauthn.credential_options.publicKey) }) }) }), + error: null, + }; + case 'request': + return { + data: Object.assign(Object.assign({}, data), { webauthn: Object.assign(Object.assign({}, data.webauthn), { credential_options: Object.assign(Object.assign({}, data.webauthn.credential_options), { publicKey: (0, webauthn_1.deserializeCredentialRequestOptions)(data.webauthn.credential_options.publicKey) }) }) }), + error: null, + }; + } + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + }); + } + /** + * {@see GoTrueMFAApi#challengeAndVerify} + */ + async _challengeAndVerify(params) { + // both _challenge and _verify independently acquire the lock, so no need + // to acquire it here + const { data: challengeData, error: challengeError } = await this._challenge({ + factorId: params.factorId, + }); + if (challengeError) { + return this._returnResult({ data: null, error: challengeError }); + } + return await this._verify({ + factorId: params.factorId, + challengeId: challengeData.id, + code: params.code, + }); + } + /** + * {@see GoTrueMFAApi#listFactors} + */ + async _listFactors() { + var _a; + // use #getUser instead of #_getUser as the former acquires a lock + const { data: { user }, error: userError, } = await this.getUser(); + if (userError) { + return { data: null, error: userError }; + } + const data = { + all: [], + phone: [], + totp: [], + webauthn: [], + }; + // loop over the factors ONCE + for (const factor of (_a = user === null || user === void 0 ? void 0 : user.factors) !== null && _a !== void 0 ? _a : []) { + data.all.push(factor); + if (factor.status === 'verified') { + ; + data[factor.factor_type].push(factor); + } + } + return { + data, + error: null, + }; + } + /** + * {@see GoTrueMFAApi#getAuthenticatorAssuranceLevel} + */ + async _getAuthenticatorAssuranceLevel() { + var _a, _b; + const { data: { session }, error: sessionError, } = await this.getSession(); + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + if (!session) { + return { + data: { currentLevel: null, nextLevel: null, currentAuthenticationMethods: [] }, + error: null, + }; + } + const { payload } = (0, helpers_1.decodeJWT)(session.access_token); + let currentLevel = null; + if (payload.aal) { + currentLevel = payload.aal; + } + let nextLevel = currentLevel; + const verifiedFactors = (_b = (_a = session.user.factors) === null || _a === void 0 ? void 0 : _a.filter((factor) => factor.status === 'verified')) !== null && _b !== void 0 ? _b : []; + if (verifiedFactors.length > 0) { + nextLevel = 'aal2'; + } + const currentAuthenticationMethods = payload.amr || []; + return { data: { currentLevel, nextLevel, currentAuthenticationMethods }, error: null }; + } + /** + * Retrieves details about an OAuth authorization request. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * Returns authorization details including client info, scopes, and user information. + * If the API returns a redirect_uri, it means consent was already given - the caller + * should handle the redirect manually if needed. + */ + async _getAuthorizationDetails(authorizationId) { + try { + return await this._useSession(async (result) => { + const { data: { session }, error: sessionError, } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + if (!session) { + return this._returnResult({ data: null, error: new errors_1.AuthSessionMissingError() }); + } + return await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/oauth/authorizations/${authorizationId}`, { + headers: this.headers, + jwt: session.access_token, + xform: (data) => ({ data, error: null }), + }); + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + /** + * Approves an OAuth authorization request. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ + async _approveAuthorization(authorizationId, options) { + try { + return await this._useSession(async (result) => { + const { data: { session }, error: sessionError, } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + if (!session) { + return this._returnResult({ data: null, error: new errors_1.AuthSessionMissingError() }); + } + const response = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/oauth/authorizations/${authorizationId}/consent`, { + headers: this.headers, + jwt: session.access_token, + body: { action: 'approve' }, + xform: (data) => ({ data, error: null }), + }); + if (response.data && response.data.redirect_url) { + // Automatically redirect in browser unless skipBrowserRedirect is true + if ((0, helpers_1.isBrowser)() && !(options === null || options === void 0 ? void 0 : options.skipBrowserRedirect)) { + window.location.assign(response.data.redirect_url); + } + } + return response; + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + /** + * Denies an OAuth authorization request. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ + async _denyAuthorization(authorizationId, options) { + try { + return await this._useSession(async (result) => { + const { data: { session }, error: sessionError, } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + if (!session) { + return this._returnResult({ data: null, error: new errors_1.AuthSessionMissingError() }); + } + const response = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/oauth/authorizations/${authorizationId}/consent`, { + headers: this.headers, + jwt: session.access_token, + body: { action: 'deny' }, + xform: (data) => ({ data, error: null }), + }); + if (response.data && response.data.redirect_url) { + // Automatically redirect in browser unless skipBrowserRedirect is true + if ((0, helpers_1.isBrowser)() && !(options === null || options === void 0 ? void 0 : options.skipBrowserRedirect)) { + window.location.assign(response.data.redirect_url); + } + } + return response; + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + /** + * Lists all OAuth grants that the authenticated user has authorized. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ + async _listOAuthGrants() { + try { + return await this._useSession(async (result) => { + const { data: { session }, error: sessionError, } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + if (!session) { + return this._returnResult({ data: null, error: new errors_1.AuthSessionMissingError() }); + } + return await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/user/oauth/grants`, { + headers: this.headers, + jwt: session.access_token, + xform: (data) => ({ data, error: null }), + }); + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + /** + * Revokes a user's OAuth grant for a specific client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ + async _revokeOAuthGrant(options) { + try { + return await this._useSession(async (result) => { + const { data: { session }, error: sessionError, } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + if (!session) { + return this._returnResult({ data: null, error: new errors_1.AuthSessionMissingError() }); + } + await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/user/oauth/grants`, { + headers: this.headers, + jwt: session.access_token, + query: { client_id: options.clientId }, + noResolveJson: true, + }); + return { data: {}, error: null }; + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + async fetchJwk(kid, jwks = { keys: [] }) { + // try fetching from the supplied jwks + let jwk = jwks.keys.find((key) => key.kid === kid); + if (jwk) { + return jwk; + } + const now = Date.now(); + // try fetching from cache + jwk = this.jwks.keys.find((key) => key.kid === kid); + // jwk exists and jwks isn't stale + if (jwk && this.jwks_cached_at + constants_1.JWKS_TTL > now) { + return jwk; + } + // jwk isn't cached in memory so we need to fetch it from the well-known endpoint + const { data, error } = await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/.well-known/jwks.json`, { + headers: this.headers, + }); + if (error) { + throw error; + } + if (!data.keys || data.keys.length === 0) { + return null; + } + this.jwks = data; + this.jwks_cached_at = now; + // Find the signing key + jwk = data.keys.find((key) => key.kid === kid); + if (!jwk) { + return null; + } + return jwk; + } + /** + * Extracts the JWT claims present in the access token by first verifying the + * JWT against the server's JSON Web Key Set endpoint + * `/.well-known/jwks.json` which is often cached, resulting in significantly + * faster responses. Prefer this method over {@link #getUser} which always + * sends a request to the Auth server for each JWT. + * + * If the project is not using an asymmetric JWT signing key (like ECC or + * RSA) it always sends a request to the Auth server (similar to {@link + * #getUser}) to verify the JWT. + * + * @param jwt An optional specific JWT you wish to verify, not the one you + * can obtain from {@link #getSession}. + * @param options Various additional options that allow you to customize the + * behavior of this method. + */ + async getClaims(jwt, options = {}) { + try { + let token = jwt; + if (!token) { + const { data, error } = await this.getSession(); + if (error || !data.session) { + return this._returnResult({ data: null, error }); + } + token = data.session.access_token; + } + const { header, payload, signature, raw: { header: rawHeader, payload: rawPayload }, } = (0, helpers_1.decodeJWT)(token); + if (!(options === null || options === void 0 ? void 0 : options.allowExpired)) { + // Reject expired JWTs should only happen if jwt argument was passed + (0, helpers_1.validateExp)(payload.exp); + } + const signingKey = !header.alg || + header.alg.startsWith('HS') || + !header.kid || + !('crypto' in globalThis && 'subtle' in globalThis.crypto) + ? null + : await this.fetchJwk(header.kid, (options === null || options === void 0 ? void 0 : options.keys) ? { keys: options.keys } : options === null || options === void 0 ? void 0 : options.jwks); + // If symmetric algorithm or WebCrypto API is unavailable, fallback to getUser() + if (!signingKey) { + const { error } = await this.getUser(token); + if (error) { + throw error; + } + // getUser succeeds so the claims in the JWT can be trusted + return { + data: { + claims: payload, + header, + signature, + }, + error: null, + }; + } + const algorithm = (0, helpers_1.getAlgorithm)(header.alg); + // Convert JWK to CryptoKey + const publicKey = await crypto.subtle.importKey('jwk', signingKey, algorithm, true, [ + 'verify', + ]); + // Verify the signature + const isValid = await crypto.subtle.verify(algorithm, publicKey, signature, (0, base64url_1.stringToUint8Array)(`${rawHeader}.${rawPayload}`)); + if (!isValid) { + throw new errors_1.AuthInvalidJwtError('Invalid JWT signature'); + } + // If verification succeeds, decode and return claims + return { + data: { + claims: payload, + header, + signature, + }, + error: null, + }; + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } +} +GoTrueClient.nextInstanceID = {}; +exports.default = GoTrueClient; +//# sourceMappingURL=GoTrueClient.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/GoTrueClient.js.map b/backend/node_modules/@supabase/auth-js/dist/main/GoTrueClient.js.map new file mode 100644 index 0000000..3bee7c2 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/GoTrueClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GoTrueClient.js","sourceRoot":"","sources":["../../src/GoTrueClient.ts"],"names":[],"mappings":";;;AAAA,8EAA6C;AAC7C,+CAQwB;AACxB,yCAcqB;AACrB,uCAOoB;AACpB,2CAmBsB;AACtB,uDAA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H,CAAC;YAED,MAAM,SAAS,GAAG,IAAA,sBAAY,EAAC,MAAM,CAAC,GAAG,CAAC,CAAA;YAE1C,2BAA2B;YAC3B,MAAM,SAAS,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,EAAE,UAAU,EAAE,SAAS,EAAE,IAAI,EAAE;gBAClF,QAAQ;aACT,CAAC,CAAA;YAEF,uBAAuB;YACvB,MAAM,OAAO,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,MAAM,CACxC,SAAS,EACT,SAAS,EACT,SAAS,EACT,IAAA,8BAAkB,EAAC,GAAG,SAAS,IAAI,UAAU,EAAE,CAAC,CACjD,CAAA;YAED,IAAI,CAAC,OAAO,EAAE,CAAC;gBACb,MAAM,IAAI,4BAAmB,CAAC,uBAAuB,CAAC,CAAA;YACxD,CAAC;YAED,qDAAqD;YACrD,OAAO;gBACL,IAAI,EAAE;oBACJ,MAAM,EAAE,OAAO;oBACf,MAAM;oBACN,SAAS;iBACV;gBACD,KAAK,EAAE,IAAI;aACZ,CAAA;QACH,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,IAAA,oBAAW,EAAC,KAAK,CAAC,EAAE,CAAC;gBACvB,OAAO,IAAI,CAAC,aAAa,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAA;YAClD,CAAC;YACD,MAAM,KAAK,CAAA;QACb,CAAC;IACH,CAAC;;AAziHc,2BAAc,GAA2B,EAAE,AAA7B,CAA6B;kBADvC,YAAY"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/index.d.ts b/backend/node_modules/@supabase/auth-js/dist/main/index.d.ts new file mode 100644 index 0000000..62b23d0 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/index.d.ts @@ -0,0 +1,9 @@ +import GoTrueAdminApi from './GoTrueAdminApi'; +import GoTrueClient from './GoTrueClient'; +import AuthAdminApi from './AuthAdminApi'; +import AuthClient from './AuthClient'; +export { GoTrueAdminApi, GoTrueClient, AuthAdminApi, AuthClient }; +export * from './lib/types'; +export * from './lib/errors'; +export { navigatorLock, NavigatorLockAcquireTimeoutError, internals as lockInternals, processLock, } from './lib/locks'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/index.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/main/index.d.ts.map new file mode 100644 index 0000000..884248d --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,kBAAkB,CAAA;AAC7C,OAAO,YAAY,MAAM,gBAAgB,CAAA;AACzC,OAAO,YAAY,MAAM,gBAAgB,CAAA;AACzC,OAAO,UAAU,MAAM,cAAc,CAAA;AACrC,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,YAAY,EAAE,UAAU,EAAE,CAAA;AACjE,cAAc,aAAa,CAAA;AAC3B,cAAc,cAAc,CAAA;AAC5B,OAAO,EACL,aAAa,EACb,gCAAgC,EAChC,SAAS,IAAI,aAAa,EAC1B,WAAW,GACZ,MAAM,aAAa,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/index.js b/backend/node_modules/@supabase/auth-js/dist/main/index.js new file mode 100644 index 0000000..27f9e50 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/index.js @@ -0,0 +1,20 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.processLock = exports.lockInternals = exports.NavigatorLockAcquireTimeoutError = exports.navigatorLock = exports.AuthClient = exports.AuthAdminApi = exports.GoTrueClient = exports.GoTrueAdminApi = void 0; +const tslib_1 = require("tslib"); +const GoTrueAdminApi_1 = tslib_1.__importDefault(require("./GoTrueAdminApi")); +exports.GoTrueAdminApi = GoTrueAdminApi_1.default; +const GoTrueClient_1 = tslib_1.__importDefault(require("./GoTrueClient")); +exports.GoTrueClient = GoTrueClient_1.default; +const AuthAdminApi_1 = tslib_1.__importDefault(require("./AuthAdminApi")); +exports.AuthAdminApi = AuthAdminApi_1.default; +const AuthClient_1 = tslib_1.__importDefault(require("./AuthClient")); +exports.AuthClient = AuthClient_1.default; +tslib_1.__exportStar(require("./lib/types"), exports); +tslib_1.__exportStar(require("./lib/errors"), exports); +var locks_1 = require("./lib/locks"); +Object.defineProperty(exports, "navigatorLock", { enumerable: true, get: function () { return locks_1.navigatorLock; } }); +Object.defineProperty(exports, "NavigatorLockAcquireTimeoutError", { enumerable: true, get: function () { return locks_1.NavigatorLockAcquireTimeoutError; } }); +Object.defineProperty(exports, "lockInternals", { enumerable: true, get: function () { return locks_1.internals; } }); +Object.defineProperty(exports, "processLock", { enumerable: true, get: function () { return locks_1.processLock; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/index.js.map b/backend/node_modules/@supabase/auth-js/dist/main/index.js.map new file mode 100644 index 0000000..ca499bc --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;AAAA,8EAA6C;AAIpC,yBAJF,wBAAc,CAIE;AAHvB,0EAAyC;AAGhB,uBAHlB,sBAAY,CAGkB;AAFrC,0EAAyC;AAEF,uBAFhC,sBAAY,CAEgC;AADnD,sEAAqC;AACgB,qBAD9C,oBAAU,CAC8C;AAC/D,sDAA2B;AAC3B,uDAA4B;AAC5B,qCAKoB;AAJlB,sGAAA,aAAa,OAAA;AACb,yHAAA,gCAAgC,OAAA;AAChC,sGAAA,SAAS,OAAiB;AAC1B,oGAAA,WAAW,OAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/base64url.d.ts b/backend/node_modules/@supabase/auth-js/dist/main/lib/base64url.d.ts new file mode 100644 index 0000000..62276a3 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/base64url.d.ts @@ -0,0 +1,76 @@ +/** + * Avoid modifying this file. It's part of + * https://github.com/supabase-community/base64url-js. Submit all fixes on + * that repo! + */ +import { Uint8Array_ } from './webauthn.dom'; +/** + * Converts a byte to a Base64-URL string. + * + * @param byte The byte to convert, or null to flush at the end of the byte sequence. + * @param state The Base64 conversion state. Pass an initial value of `{ queue: 0, queuedBits: 0 }`. + * @param emit A function called with the next Base64 character when ready. + */ +export declare function byteToBase64URL(byte: number | null, state: { + queue: number; + queuedBits: number; +}, emit: (char: string) => void): void; +/** + * Converts a String char code (extracted using `string.charCodeAt(position)`) to a sequence of Base64-URL characters. + * + * @param charCode The char code of the JavaScript string. + * @param state The Base64 state. Pass an initial value of `{ queue: 0, queuedBits: 0 }`. + * @param emit A function called with the next byte. + */ +export declare function byteFromBase64URL(charCode: number, state: { + queue: number; + queuedBits: number; +}, emit: (byte: number) => void): void; +/** + * Converts a JavaScript string (which may include any valid character) into a + * Base64-URL encoded string. The string is first encoded in UTF-8 which is + * then encoded as Base64-URL. + * + * @param str The string to convert. + */ +export declare function stringToBase64URL(str: string): string; +/** + * Converts a Base64-URL encoded string into a JavaScript string. It is assumed + * that the underlying string has been encoded as UTF-8. + * + * @param str The Base64-URL encoded string. + */ +export declare function stringFromBase64URL(str: string): string; +/** + * Converts a Unicode codepoint to a multi-byte UTF-8 sequence. + * + * @param codepoint The Unicode codepoint. + * @param emit Function which will be called for each UTF-8 byte that represents the codepoint. + */ +export declare function codepointToUTF8(codepoint: number, emit: (byte: number) => void): void; +/** + * Converts a JavaScript string to a sequence of UTF-8 bytes. + * + * @param str The string to convert to UTF-8. + * @param emit Function which will be called for each UTF-8 byte of the string. + */ +export declare function stringToUTF8(str: string, emit: (byte: number) => void): void; +/** + * Converts a UTF-8 byte to a Unicode codepoint. + * + * @param byte The UTF-8 byte next in the sequence. + * @param state The shared state between consecutive UTF-8 bytes in the + * sequence, an object with the shape `{ utf8seq: 0, codepoint: 0 }`. + * @param emit Function which will be called for each codepoint. + */ +export declare function stringFromUTF8(byte: number, state: { + utf8seq: number; + codepoint: number; +}, emit: (codepoint: number) => void): void; +/** + * Helper functions to convert different types of strings to Uint8Array + */ +export declare function base64UrlToUint8Array(str: string): Uint8Array_; +export declare function stringToUint8Array(str: string): Uint8Array_; +export declare function bytesToBase64URL(bytes: Uint8Array): string; +//# sourceMappingURL=base64url.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/base64url.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/main/lib/base64url.d.ts.map new file mode 100644 index 0000000..5a7591c --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/base64url.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"base64url.d.ts","sourceRoot":"","sources":["../../../src/lib/base64url.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA;AAoC5C;;;;;;GAMG;AACH,wBAAgB,eAAe,CAC7B,IAAI,EAAE,MAAM,GAAG,IAAI,EACnB,KAAK,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,EAC5C,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,QAqB7B;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAC/B,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,EAC5C,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,QAmB7B;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,MAAM,UAgB5C;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,MAAM,UAuB9C;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,QAsB9E;AAED;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,QAgBrE;AAED;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAC5B,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,EAC7C,IAAI,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,IAAI,QAuClC;AAED;;GAEG;AAEH,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,MAAM,GAAG,WAAW,CAa9D;AAED,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,GAAG,WAAW,CAI3D;AAED,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,UAAU,UAcjD"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/base64url.js b/backend/node_modules/@supabase/auth-js/dist/main/lib/base64url.js new file mode 100644 index 0000000..547425d --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/base64url.js @@ -0,0 +1,269 @@ +"use strict"; +/** + * Avoid modifying this file. It's part of + * https://github.com/supabase-community/base64url-js. Submit all fixes on + * that repo! + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.byteToBase64URL = byteToBase64URL; +exports.byteFromBase64URL = byteFromBase64URL; +exports.stringToBase64URL = stringToBase64URL; +exports.stringFromBase64URL = stringFromBase64URL; +exports.codepointToUTF8 = codepointToUTF8; +exports.stringToUTF8 = stringToUTF8; +exports.stringFromUTF8 = stringFromUTF8; +exports.base64UrlToUint8Array = base64UrlToUint8Array; +exports.stringToUint8Array = stringToUint8Array; +exports.bytesToBase64URL = bytesToBase64URL; +/** + * An array of characters that encode 6 bits into a Base64-URL alphabet + * character. + */ +const TO_BASE64URL = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'.split(''); +/** + * An array of characters that can appear in a Base64-URL encoded string but + * should be ignored. + */ +const IGNORE_BASE64URL = ' \t\n\r='.split(''); +/** + * An array of 128 numbers that map a Base64-URL character to 6 bits, or if -2 + * used to skip the character, or if -1 used to error out. + */ +const FROM_BASE64URL = (() => { + const charMap = new Array(128); + for (let i = 0; i < charMap.length; i += 1) { + charMap[i] = -1; + } + for (let i = 0; i < IGNORE_BASE64URL.length; i += 1) { + charMap[IGNORE_BASE64URL[i].charCodeAt(0)] = -2; + } + for (let i = 0; i < TO_BASE64URL.length; i += 1) { + charMap[TO_BASE64URL[i].charCodeAt(0)] = i; + } + return charMap; +})(); +/** + * Converts a byte to a Base64-URL string. + * + * @param byte The byte to convert, or null to flush at the end of the byte sequence. + * @param state The Base64 conversion state. Pass an initial value of `{ queue: 0, queuedBits: 0 }`. + * @param emit A function called with the next Base64 character when ready. + */ +function byteToBase64URL(byte, state, emit) { + if (byte !== null) { + state.queue = (state.queue << 8) | byte; + state.queuedBits += 8; + while (state.queuedBits >= 6) { + const pos = (state.queue >> (state.queuedBits - 6)) & 63; + emit(TO_BASE64URL[pos]); + state.queuedBits -= 6; + } + } + else if (state.queuedBits > 0) { + state.queue = state.queue << (6 - state.queuedBits); + state.queuedBits = 6; + while (state.queuedBits >= 6) { + const pos = (state.queue >> (state.queuedBits - 6)) & 63; + emit(TO_BASE64URL[pos]); + state.queuedBits -= 6; + } + } +} +/** + * Converts a String char code (extracted using `string.charCodeAt(position)`) to a sequence of Base64-URL characters. + * + * @param charCode The char code of the JavaScript string. + * @param state The Base64 state. Pass an initial value of `{ queue: 0, queuedBits: 0 }`. + * @param emit A function called with the next byte. + */ +function byteFromBase64URL(charCode, state, emit) { + const bits = FROM_BASE64URL[charCode]; + if (bits > -1) { + // valid Base64-URL character + state.queue = (state.queue << 6) | bits; + state.queuedBits += 6; + while (state.queuedBits >= 8) { + emit((state.queue >> (state.queuedBits - 8)) & 0xff); + state.queuedBits -= 8; + } + } + else if (bits === -2) { + // ignore spaces, tabs, newlines, = + return; + } + else { + throw new Error(`Invalid Base64-URL character "${String.fromCharCode(charCode)}"`); + } +} +/** + * Converts a JavaScript string (which may include any valid character) into a + * Base64-URL encoded string. The string is first encoded in UTF-8 which is + * then encoded as Base64-URL. + * + * @param str The string to convert. + */ +function stringToBase64URL(str) { + const base64 = []; + const emitter = (char) => { + base64.push(char); + }; + const state = { queue: 0, queuedBits: 0 }; + stringToUTF8(str, (byte) => { + byteToBase64URL(byte, state, emitter); + }); + byteToBase64URL(null, state, emitter); + return base64.join(''); +} +/** + * Converts a Base64-URL encoded string into a JavaScript string. It is assumed + * that the underlying string has been encoded as UTF-8. + * + * @param str The Base64-URL encoded string. + */ +function stringFromBase64URL(str) { + const conv = []; + const utf8Emit = (codepoint) => { + conv.push(String.fromCodePoint(codepoint)); + }; + const utf8State = { + utf8seq: 0, + codepoint: 0, + }; + const b64State = { queue: 0, queuedBits: 0 }; + const byteEmit = (byte) => { + stringFromUTF8(byte, utf8State, utf8Emit); + }; + for (let i = 0; i < str.length; i += 1) { + byteFromBase64URL(str.charCodeAt(i), b64State, byteEmit); + } + return conv.join(''); +} +/** + * Converts a Unicode codepoint to a multi-byte UTF-8 sequence. + * + * @param codepoint The Unicode codepoint. + * @param emit Function which will be called for each UTF-8 byte that represents the codepoint. + */ +function codepointToUTF8(codepoint, emit) { + if (codepoint <= 0x7f) { + emit(codepoint); + return; + } + else if (codepoint <= 0x7ff) { + emit(0xc0 | (codepoint >> 6)); + emit(0x80 | (codepoint & 0x3f)); + return; + } + else if (codepoint <= 0xffff) { + emit(0xe0 | (codepoint >> 12)); + emit(0x80 | ((codepoint >> 6) & 0x3f)); + emit(0x80 | (codepoint & 0x3f)); + return; + } + else if (codepoint <= 0x10ffff) { + emit(0xf0 | (codepoint >> 18)); + emit(0x80 | ((codepoint >> 12) & 0x3f)); + emit(0x80 | ((codepoint >> 6) & 0x3f)); + emit(0x80 | (codepoint & 0x3f)); + return; + } + throw new Error(`Unrecognized Unicode codepoint: ${codepoint.toString(16)}`); +} +/** + * Converts a JavaScript string to a sequence of UTF-8 bytes. + * + * @param str The string to convert to UTF-8. + * @param emit Function which will be called for each UTF-8 byte of the string. + */ +function stringToUTF8(str, emit) { + for (let i = 0; i < str.length; i += 1) { + let codepoint = str.charCodeAt(i); + if (codepoint > 0xd7ff && codepoint <= 0xdbff) { + // most UTF-16 codepoints are Unicode codepoints, except values in this + // range where the next UTF-16 codepoint needs to be combined with the + // current one to get the Unicode codepoint + const highSurrogate = ((codepoint - 0xd800) * 0x400) & 0xffff; + const lowSurrogate = (str.charCodeAt(i + 1) - 0xdc00) & 0xffff; + codepoint = (lowSurrogate | highSurrogate) + 0x10000; + i += 1; + } + codepointToUTF8(codepoint, emit); + } +} +/** + * Converts a UTF-8 byte to a Unicode codepoint. + * + * @param byte The UTF-8 byte next in the sequence. + * @param state The shared state between consecutive UTF-8 bytes in the + * sequence, an object with the shape `{ utf8seq: 0, codepoint: 0 }`. + * @param emit Function which will be called for each codepoint. + */ +function stringFromUTF8(byte, state, emit) { + if (state.utf8seq === 0) { + if (byte <= 0x7f) { + emit(byte); + return; + } + // count the number of 1 leading bits until you reach 0 + for (let leadingBit = 1; leadingBit < 6; leadingBit += 1) { + if (((byte >> (7 - leadingBit)) & 1) === 0) { + state.utf8seq = leadingBit; + break; + } + } + if (state.utf8seq === 2) { + state.codepoint = byte & 31; + } + else if (state.utf8seq === 3) { + state.codepoint = byte & 15; + } + else if (state.utf8seq === 4) { + state.codepoint = byte & 7; + } + else { + throw new Error('Invalid UTF-8 sequence'); + } + state.utf8seq -= 1; + } + else if (state.utf8seq > 0) { + if (byte <= 0x7f) { + throw new Error('Invalid UTF-8 sequence'); + } + state.codepoint = (state.codepoint << 6) | (byte & 63); + state.utf8seq -= 1; + if (state.utf8seq === 0) { + emit(state.codepoint); + } + } +} +/** + * Helper functions to convert different types of strings to Uint8Array + */ +function base64UrlToUint8Array(str) { + const result = []; + const state = { queue: 0, queuedBits: 0 }; + const onByte = (byte) => { + result.push(byte); + }; + for (let i = 0; i < str.length; i += 1) { + byteFromBase64URL(str.charCodeAt(i), state, onByte); + } + return new Uint8Array(result); +} +function stringToUint8Array(str) { + const result = []; + stringToUTF8(str, (byte) => result.push(byte)); + return new Uint8Array(result); +} +function bytesToBase64URL(bytes) { + const result = []; + const state = { queue: 0, queuedBits: 0 }; + const onChar = (char) => { + result.push(char); + }; + bytes.forEach((byte) => byteToBase64URL(byte, state, onChar)); + // always call with `null` after processing all bytes + byteToBase64URL(null, state, onChar); + return result.join(''); +} +//# sourceMappingURL=base64url.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/base64url.js.map b/backend/node_modules/@supabase/auth-js/dist/main/lib/base64url.js.map new file mode 100644 index 0000000..db9998e --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/base64url.js.map @@ -0,0 +1 @@ +{"version":3,"file":"base64url.js","sourceRoot":"","sources":["../../../src/lib/base64url.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AA6CH,0CAwBC;AASD,8CAsBC;AASD,8CAgBC;AAQD,kDAuBC;AAQD,0CAsBC;AAQD,oCAgBC;AAUD,wCA0CC;AAMD,sDAaC;AAED,gDAIC;AAED,4CAcC;AA3SD;;;GAGG;AACH,MAAM,YAAY,GAAG,kEAAkE,CAAC,KAAK,CAAC,EAAE,CAAC,CAAA;AAEjG;;;GAGG;AACH,MAAM,gBAAgB,GAAG,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC,CAAA;AAE7C;;;GAGG;AACH,MAAM,cAAc,GAAG,CAAC,GAAG,EAAE;IAC3B,MAAM,OAAO,GAAa,IAAI,KAAK,CAAC,GAAG,CAAC,CAAA;IAExC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAA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end/node_modules/@supabase/auth-js/dist/main/lib/constants.d.ts new file mode 100644 index 0000000..604f8d0 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/constants.d.ts @@ -0,0 +1,26 @@ +/** Current session will be checked for refresh at this interval. */ +export declare const AUTO_REFRESH_TICK_DURATION_MS: number; +/** + * A token refresh will be attempted this many ticks before the current session expires. */ +export declare const AUTO_REFRESH_TICK_THRESHOLD = 3; +export declare const EXPIRY_MARGIN_MS: number; +export declare const GOTRUE_URL = "http://localhost:9999"; +export declare const STORAGE_KEY = "supabase.auth.token"; +export declare const AUDIENCE = ""; +export declare const DEFAULT_HEADERS: { + 'X-Client-Info': string; +}; +export declare const NETWORK_FAILURE: { + MAX_RETRIES: number; + RETRY_INTERVAL: number; +}; +export declare const API_VERSION_HEADER_NAME = "X-Supabase-Api-Version"; +export declare const API_VERSIONS: { + '2024-01-01': { + timestamp: number; + name: string; + }; +}; +export declare const BASE64URL_REGEX: RegExp; +export declare const JWKS_TTL: number; +//# sourceMappingURL=constants.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/constants.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/main/lib/constants.d.ts.map new file mode 100644 index 0000000..acb62eb --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/constants.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":"AAEA,oEAAoE;AACpE,eAAO,MAAM,6BAA6B,QAAY,CAAA;AAEtD;2FAC2F;AAC3F,eAAO,MAAM,2BAA2B,IAAI,CAAA;AAK5C,eAAO,MAAM,gBAAgB,QAA8D,CAAA;AAE3F,eAAO,MAAM,UAAU,0BAA0B,CAAA;AACjD,eAAO,MAAM,WAAW,wBAAwB,CAAA;AAChD,eAAO,MAAM,QAAQ,KAAK,CAAA;AAC1B,eAAO,MAAM,eAAe;;CAA8C,CAAA;AAC1E,eAAO,MAAM,eAAe;;;CAG3B,CAAA;AAED,eAAO,MAAM,uBAAuB,2BAA2B,CAAA;AAC/D,eAAO,MAAM,YAAY;;;;;CAKxB,CAAA;AAED,eAAO,MAAM,eAAe,QAAyD,CAAA;AAErF,eAAO,MAAM,QAAQ,QAAiB,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/constants.js b/backend/node_modules/@supabase/auth-js/dist/main/lib/constants.js new file mode 100644 index 0000000..7ce758d --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/constants.js @@ -0,0 +1,31 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.JWKS_TTL = exports.BASE64URL_REGEX = exports.API_VERSIONS = exports.API_VERSION_HEADER_NAME = exports.NETWORK_FAILURE = exports.DEFAULT_HEADERS = exports.AUDIENCE = exports.STORAGE_KEY = exports.GOTRUE_URL = exports.EXPIRY_MARGIN_MS = exports.AUTO_REFRESH_TICK_THRESHOLD = exports.AUTO_REFRESH_TICK_DURATION_MS = void 0; +const version_1 = require("./version"); +/** Current session will be checked for refresh at this interval. */ +exports.AUTO_REFRESH_TICK_DURATION_MS = 30 * 1000; +/** + * A token refresh will be attempted this many ticks before the current session expires. */ +exports.AUTO_REFRESH_TICK_THRESHOLD = 3; +/* + * Earliest time before an access token expires that the session should be refreshed. + */ +exports.EXPIRY_MARGIN_MS = exports.AUTO_REFRESH_TICK_THRESHOLD * exports.AUTO_REFRESH_TICK_DURATION_MS; +exports.GOTRUE_URL = 'http://localhost:9999'; +exports.STORAGE_KEY = 'supabase.auth.token'; +exports.AUDIENCE = ''; +exports.DEFAULT_HEADERS = { 'X-Client-Info': `gotrue-js/${version_1.version}` }; +exports.NETWORK_FAILURE = { + MAX_RETRIES: 10, + RETRY_INTERVAL: 2, // in deciseconds +}; +exports.API_VERSION_HEADER_NAME = 'X-Supabase-Api-Version'; +exports.API_VERSIONS = { + '2024-01-01': { + timestamp: Date.parse('2024-01-01T00:00:00.0Z'), + name: '2024-01-01', + }, +}; +exports.BASE64URL_REGEX = /^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i; +exports.JWKS_TTL = 10 * 60 * 1000; // 10 minutes +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/constants.js.map b/backend/node_modules/@supabase/auth-js/dist/main/lib/constants.js.map new file mode 100644 index 0000000..68ebf55 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":";;;AAAA,uCAAmC;AAEnC,oEAAoE;AACvD,QAAA,6BAA6B,GAAG,EAAE,GAAG,IAAI,CAAA;AAEtD;2FAC2F;AAC9E,QAAA,2BAA2B,GAAG,CAAC,CAAA;AAE5C;;GAEG;AACU,QAAA,gBAAgB,GAAG,mCAA2B,GAAG,qCAA6B,CAAA;AAE9E,QAAA,UAAU,GAAG,uBAAuB,CAAA;AACpC,QAAA,WAAW,GAAG,qBAAqB,CAAA;AACnC,QAAA,QAAQ,GAAG,EAAE,CAAA;AACb,QAAA,eAAe,GAAG,EAAE,eAAe,EAAE,aAAa,iBAAO,EAAE,EAAE,CAAA;AAC7D,QAAA,eAAe,GAAG;IAC7B,WAAW,EAAE,EAAE;IACf,cAAc,EAAE,CAAC,EAAE,iBAAiB;CACrC,CAAA;AAEY,QAAA,uBAAuB,GAAG,wBAAwB,CAAA;AAClD,QAAA,YAAY,GAAG;IAC1B,YAAY,EAAE;QACZ,SAAS,EAAE,IAAI,CAAC,KAAK,CAAC,wBAAwB,CAAC;QAC/C,IAAI,EAAE,YAAY;KACnB;CACF,CAAA;AAEY,QAAA,eAAe,GAAG,sDAAsD,CAAA;AAExE,QAAA,QAAQ,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAA,CAAC,aAAa"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/error-codes.d.ts b/backend/node_modules/@supabase/auth-js/dist/main/lib/error-codes.d.ts new file mode 100644 index 0000000..668ad5b --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/error-codes.d.ts @@ -0,0 +1,7 @@ +/** + * Known error codes. Note that the server may also return other error codes + * not included in this list (if the SDK is older than the version + * on the server). + */ +export type ErrorCode = 'unexpected_failure' | 'validation_failed' | 'bad_json' | 'email_exists' | 'phone_exists' | 'bad_jwt' | 'not_admin' | 'no_authorization' | 'user_not_found' | 'session_not_found' | 'session_expired' | 'refresh_token_not_found' | 'refresh_token_already_used' | 'flow_state_not_found' | 'flow_state_expired' | 'signup_disabled' | 'user_banned' | 'provider_email_needs_verification' | 'invite_not_found' | 'bad_oauth_state' | 'bad_oauth_callback' | 'oauth_provider_not_supported' | 'unexpected_audience' | 'single_identity_not_deletable' | 'email_conflict_identity_not_deletable' | 'identity_already_exists' | 'email_provider_disabled' | 'phone_provider_disabled' | 'too_many_enrolled_mfa_factors' | 'mfa_factor_name_conflict' | 'mfa_factor_not_found' | 'mfa_ip_address_mismatch' | 'mfa_challenge_expired' | 'mfa_verification_failed' | 'mfa_verification_rejected' | 'insufficient_aal' | 'captcha_failed' | 'saml_provider_disabled' | 'manual_linking_disabled' | 'sms_send_failed' | 'email_not_confirmed' | 'phone_not_confirmed' | 'reauth_nonce_missing' | 'saml_relay_state_not_found' | 'saml_relay_state_expired' | 'saml_idp_not_found' | 'saml_assertion_no_user_id' | 'saml_assertion_no_email' | 'user_already_exists' | 'sso_provider_not_found' | 'saml_metadata_fetch_failed' | 'saml_idp_already_exists' | 'sso_domain_already_exists' | 'saml_entity_id_mismatch' | 'conflict' | 'provider_disabled' | 'user_sso_managed' | 'reauthentication_needed' | 'same_password' | 'reauthentication_not_valid' | 'otp_expired' | 'otp_disabled' | 'identity_not_found' | 'weak_password' | 'over_request_rate_limit' | 'over_email_send_rate_limit' | 'over_sms_send_rate_limit' | 'bad_code_verifier' | 'anonymous_provider_disabled' | 'hook_timeout' | 'hook_timeout_after_retry' | 'hook_payload_over_size_limit' | 'hook_payload_invalid_content_type' | 'request_timeout' | 'mfa_phone_enroll_not_enabled' | 'mfa_phone_verify_not_enabled' | 'mfa_totp_enroll_not_enabled' | 'mfa_totp_verify_not_enabled' | 'mfa_webauthn_enroll_not_enabled' | 'mfa_webauthn_verify_not_enabled' | 'mfa_verified_factor_exists' | 'invalid_credentials' | 'email_address_not_authorized' | 'email_address_invalid'; +//# sourceMappingURL=error-codes.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/error-codes.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/main/lib/error-codes.d.ts.map new file mode 100644 index 0000000..cc88970 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/error-codes.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"error-codes.d.ts","sourceRoot":"","sources":["../../../src/lib/error-codes.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,MAAM,SAAS,GACjB,oBAAoB,GACpB,mBAAmB,GACnB,UAAU,GACV,cAAc,GACd,cAAc,GACd,SAAS,GACT,WAAW,GACX,kBAAkB,GAClB,gBAAgB,GAChB,mBAAmB,GACnB,iBAAiB,GACjB,yBAAyB,GACzB,4BAA4B,GAC5B,sBAAsB,GACtB,oBAAoB,GACpB,iBAAiB,GACjB,aAAa,GACb,mCAAmC,GACnC,kBAAkB,GAClB,iBAAiB,GACjB,oBAAoB,GACpB,8BAA8B,GAC9B,qBAAqB,GACrB,+BAA+B,GAC/B,uCAAuC,GACvC,yBAAyB,GACzB,yBAAyB,GACzB,yBAAyB,GACzB,+BAA+B,GAC/B,0BAA0B,GAC1B,sBAAsB,GACtB,yBAAyB,GACzB,uBAAuB,GACvB,yBAAyB,GACzB,2BAA2B,GAC3B,kBAAkB,GAClB,gBAAgB,GAChB,wBAAwB,GACxB,yBAAyB,GACzB,iBAAiB,GACjB,qBAAqB,GACrB,qBAAqB,GACrB,sBAAsB,GACtB,4BAA4B,GAC5B,0BAA0B,GAC1B,oBAAoB,GACpB,2BAA2B,GAC3B,yBAAyB,GACzB,qBAAqB,GACrB,wBAAwB,GACxB,4BAA4B,GAC5B,yBAAyB,GACzB,2BAA2B,GAC3B,yBAAyB,GACzB,UAAU,GACV,mBAAmB,GACnB,kBAAkB,GAClB,yBAAyB,GACzB,eAAe,GACf,4BAA4B,GAC5B,aAAa,GACb,cAAc,GACd,oBAAoB,GACpB,eAAe,GACf,yBAAyB,GACzB,4BAA4B,GAC5B,0BAA0B,GAC1B,mBAAmB,GACnB,6BAA6B,GAC7B,cAAc,GACd,0BAA0B,GAC1B,8BAA8B,GAC9B,mCAAmC,GACnC,iBAAiB,GACjB,8BAA8B,GAC9B,8BAA8B,GAC9B,6BAA6B,GAC7B,6BAA6B,GAC7B,iCAAiC,GACjC,iCAAiC,GACjC,4BAA4B,GAC5B,qBAAqB,GACrB,8BAA8B,GAC9B,uBAAuB,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/error-codes.js b/backend/node_modules/@supabase/auth-js/dist/main/lib/error-codes.js new file mode 100644 index 0000000..afa679a --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/error-codes.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=error-codes.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/error-codes.js.map b/backend/node_modules/@supabase/auth-js/dist/main/lib/error-codes.js.map new file mode 100644 index 0000000..a68e8e3 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/error-codes.js.map @@ -0,0 +1 @@ +{"version":3,"file":"error-codes.js","sourceRoot":"","sources":["../../../src/lib/error-codes.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/errors.d.ts b/backend/node_modules/@supabase/auth-js/dist/main/lib/errors.d.ts new file mode 100644 index 0000000..bec859b --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/errors.d.ts @@ -0,0 +1,227 @@ +import { WeakPasswordReasons } from './types'; +import { ErrorCode } from './error-codes'; +/** + * Base error thrown by Supabase Auth helpers. + * + * @example + * ```ts + * import { AuthError } from '@supabase/auth-js' + * + * throw new AuthError('Unexpected auth error', 500, 'unexpected') + * ``` + */ +export declare class AuthError extends Error { + /** + * Error code associated with the error. Most errors coming from + * HTTP responses will have a code, though some errors that occur + * before a response is received will not have one present. In that + * case {@link #status} will also be undefined. + */ + code: ErrorCode | (string & {}) | undefined; + /** HTTP status code that caused the error. */ + status: number | undefined; + protected __isAuthError: boolean; + constructor(message: string, status?: number, code?: string); +} +export declare function isAuthError(error: unknown): error is AuthError; +/** + * Error returned directly from the GoTrue REST API. + * + * @example + * ```ts + * import { AuthApiError } from '@supabase/auth-js' + * + * throw new AuthApiError('Invalid credentials', 400, 'invalid_credentials') + * ``` + */ +export declare class AuthApiError extends AuthError { + status: number; + constructor(message: string, status: number, code: string | undefined); +} +export declare function isAuthApiError(error: unknown): error is AuthApiError; +/** + * Wraps non-standard errors so callers can inspect the root cause. + * + * @example + * ```ts + * import { AuthUnknownError } from '@supabase/auth-js' + * + * try { + * await someAuthCall() + * } catch (err) { + * throw new AuthUnknownError('Auth failed', err) + * } + * ``` + */ +export declare class AuthUnknownError extends AuthError { + originalError: unknown; + constructor(message: string, originalError: unknown); +} +/** + * Flexible error class used to create named auth errors at runtime. + * + * @example + * ```ts + * import { CustomAuthError } from '@supabase/auth-js' + * + * throw new CustomAuthError('My custom auth error', 'MyAuthError', 400, 'custom_code') + * ``` + */ +export declare class CustomAuthError extends AuthError { + name: string; + status: number; + constructor(message: string, name: string, status: number, code: string | undefined); +} +/** + * Error thrown when an operation requires a session but none is present. + * + * @example + * ```ts + * import { AuthSessionMissingError } from '@supabase/auth-js' + * + * throw new AuthSessionMissingError() + * ``` + */ +export declare class AuthSessionMissingError extends CustomAuthError { + constructor(); +} +export declare function isAuthSessionMissingError(error: any): error is AuthSessionMissingError; +/** + * Error thrown when the token response is malformed. + * + * @example + * ```ts + * import { AuthInvalidTokenResponseError } from '@supabase/auth-js' + * + * throw new AuthInvalidTokenResponseError() + * ``` + */ +export declare class AuthInvalidTokenResponseError extends CustomAuthError { + constructor(); +} +/** + * Error thrown when email/password credentials are invalid. + * + * @example + * ```ts + * import { AuthInvalidCredentialsError } from '@supabase/auth-js' + * + * throw new AuthInvalidCredentialsError('Email or password is incorrect') + * ``` + */ +export declare class AuthInvalidCredentialsError extends CustomAuthError { + constructor(message: string); +} +/** + * Error thrown when implicit grant redirects contain an error. + * + * @example + * ```ts + * import { AuthImplicitGrantRedirectError } from '@supabase/auth-js' + * + * throw new AuthImplicitGrantRedirectError('OAuth redirect failed', { + * error: 'access_denied', + * code: 'oauth_error', + * }) + * ``` + */ +export declare class AuthImplicitGrantRedirectError extends CustomAuthError { + details: { + error: string; + code: string; + } | null; + constructor(message: string, details?: { + error: string; + code: string; + } | null); + toJSON(): { + name: string; + message: string; + status: number; + details: { + error: string; + code: string; + } | null; + }; +} +export declare function isAuthImplicitGrantRedirectError(error: any): error is AuthImplicitGrantRedirectError; +/** + * Error thrown during PKCE code exchanges. + * + * @example + * ```ts + * import { AuthPKCEGrantCodeExchangeError } from '@supabase/auth-js' + * + * throw new AuthPKCEGrantCodeExchangeError('PKCE exchange failed') + * ``` + */ +export declare class AuthPKCEGrantCodeExchangeError extends CustomAuthError { + details: { + error: string; + code: string; + } | null; + constructor(message: string, details?: { + error: string; + code: string; + } | null); + toJSON(): { + name: string; + message: string; + status: number; + details: { + error: string; + code: string; + } | null; + }; +} +/** + * Error thrown when a transient fetch issue occurs. + * + * @example + * ```ts + * import { AuthRetryableFetchError } from '@supabase/auth-js' + * + * throw new AuthRetryableFetchError('Service temporarily unavailable', 503) + * ``` + */ +export declare class AuthRetryableFetchError extends CustomAuthError { + constructor(message: string, status: number); +} +export declare function isAuthRetryableFetchError(error: unknown): error is AuthRetryableFetchError; +/** + * This error is thrown on certain methods when the password used is deemed + * weak. Inspect the reasons to identify what password strength rules are + * inadequate. + */ +/** + * Error thrown when a supplied password is considered weak. + * + * @example + * ```ts + * import { AuthWeakPasswordError } from '@supabase/auth-js' + * + * throw new AuthWeakPasswordError('Password too short', 400, ['min_length']) + * ``` + */ +export declare class AuthWeakPasswordError extends CustomAuthError { + /** + * Reasons why the password is deemed weak. + */ + reasons: WeakPasswordReasons[]; + constructor(message: string, status: number, reasons: WeakPasswordReasons[]); +} +export declare function isAuthWeakPasswordError(error: unknown): error is AuthWeakPasswordError; +/** + * Error thrown when a JWT cannot be verified or parsed. + * + * @example + * ```ts + * import { AuthInvalidJwtError } from '@supabase/auth-js' + * + * throw new AuthInvalidJwtError('Token signature is invalid') + * ``` + */ +export declare class AuthInvalidJwtError extends CustomAuthError { + constructor(message: string); +} +//# sourceMappingURL=errors.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/errors.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/main/lib/errors.d.ts.map new file mode 100644 index 0000000..f6dd864 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/errors.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../../src/lib/errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAA;AAC7C,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAA;AAEzC;;;;;;;;;GASG;AACH,qBAAa,SAAU,SAAQ,KAAK;IAClC;;;;;OAKG;IACH,IAAI,EAAE,SAAS,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC,GAAG,SAAS,CAAA;IAE3C,8CAA8C;IAC9C,MAAM,EAAE,MAAM,GAAG,SAAS,CAAA;IAE1B,SAAS,CAAC,aAAa,UAAO;gBAEl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/dist/main/lib/errors.js new file mode 100644 index 0000000..0489466 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/errors.js @@ -0,0 +1,264 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AuthInvalidJwtError = exports.AuthWeakPasswordError = exports.AuthRetryableFetchError = exports.AuthPKCEGrantCodeExchangeError = exports.AuthImplicitGrantRedirectError = exports.AuthInvalidCredentialsError = exports.AuthInvalidTokenResponseError = exports.AuthSessionMissingError = exports.CustomAuthError = exports.AuthUnknownError = exports.AuthApiError = exports.AuthError = void 0; +exports.isAuthError = isAuthError; +exports.isAuthApiError = isAuthApiError; +exports.isAuthSessionMissingError = isAuthSessionMissingError; +exports.isAuthImplicitGrantRedirectError = isAuthImplicitGrantRedirectError; +exports.isAuthRetryableFetchError = isAuthRetryableFetchError; +exports.isAuthWeakPasswordError = isAuthWeakPasswordError; +/** + * Base error thrown by Supabase Auth helpers. + * + * @example + * ```ts + * import { AuthError } from '@supabase/auth-js' + * + * throw new AuthError('Unexpected auth error', 500, 'unexpected') + * ``` + */ +class AuthError extends Error { + constructor(message, status, code) { + super(message); + this.__isAuthError = true; + this.name = 'AuthError'; + this.status = status; + this.code = code; + } +} +exports.AuthError = AuthError; +function isAuthError(error) { + return typeof error === 'object' && error !== null && '__isAuthError' in error; +} +/** + * Error returned directly from the GoTrue REST API. + * + * @example + * ```ts + * import { AuthApiError } from '@supabase/auth-js' + * + * throw new AuthApiError('Invalid credentials', 400, 'invalid_credentials') + * ``` + */ +class AuthApiError extends AuthError { + constructor(message, status, code) { + super(message, status, code); + this.name = 'AuthApiError'; + this.status = status; + this.code = code; + } +} +exports.AuthApiError = AuthApiError; +function isAuthApiError(error) { + return isAuthError(error) && error.name === 'AuthApiError'; +} +/** + * Wraps non-standard errors so callers can inspect the root cause. + * + * @example + * ```ts + * import { AuthUnknownError } from '@supabase/auth-js' + * + * try { + * await someAuthCall() + * } catch (err) { + * throw new AuthUnknownError('Auth failed', err) + * } + * ``` + */ +class AuthUnknownError extends AuthError { + constructor(message, originalError) { + super(message); + this.name = 'AuthUnknownError'; + this.originalError = originalError; + } +} +exports.AuthUnknownError = AuthUnknownError; +/** + * Flexible error class used to create named auth errors at runtime. + * + * @example + * ```ts + * import { CustomAuthError } from '@supabase/auth-js' + * + * throw new CustomAuthError('My custom auth error', 'MyAuthError', 400, 'custom_code') + * ``` + */ +class CustomAuthError extends AuthError { + constructor(message, name, status, code) { + super(message, status, code); + this.name = name; + this.status = status; + } +} +exports.CustomAuthError = CustomAuthError; +/** + * Error thrown when an operation requires a session but none is present. + * + * @example + * ```ts + * import { AuthSessionMissingError } from '@supabase/auth-js' + * + * throw new AuthSessionMissingError() + * ``` + */ +class AuthSessionMissingError extends CustomAuthError { + constructor() { + super('Auth session missing!', 'AuthSessionMissingError', 400, undefined); + } +} +exports.AuthSessionMissingError = AuthSessionMissingError; +function isAuthSessionMissingError(error) { + return isAuthError(error) && error.name === 'AuthSessionMissingError'; +} +/** + * Error thrown when the token response is malformed. + * + * @example + * ```ts + * import { AuthInvalidTokenResponseError } from '@supabase/auth-js' + * + * throw new AuthInvalidTokenResponseError() + * ``` + */ +class AuthInvalidTokenResponseError extends CustomAuthError { + constructor() { + super('Auth session or user missing', 'AuthInvalidTokenResponseError', 500, undefined); + } +} +exports.AuthInvalidTokenResponseError = AuthInvalidTokenResponseError; +/** + * Error thrown when email/password credentials are invalid. + * + * @example + * ```ts + * import { AuthInvalidCredentialsError } from '@supabase/auth-js' + * + * throw new AuthInvalidCredentialsError('Email or password is incorrect') + * ``` + */ +class AuthInvalidCredentialsError extends CustomAuthError { + constructor(message) { + super(message, 'AuthInvalidCredentialsError', 400, undefined); + } +} +exports.AuthInvalidCredentialsError = AuthInvalidCredentialsError; +/** + * Error thrown when implicit grant redirects contain an error. + * + * @example + * ```ts + * import { AuthImplicitGrantRedirectError } from '@supabase/auth-js' + * + * throw new AuthImplicitGrantRedirectError('OAuth redirect failed', { + * error: 'access_denied', + * code: 'oauth_error', + * }) + * ``` + */ +class AuthImplicitGrantRedirectError extends CustomAuthError { + constructor(message, details = null) { + super(message, 'AuthImplicitGrantRedirectError', 500, undefined); + this.details = null; + this.details = details; + } + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + details: this.details, + }; + } +} +exports.AuthImplicitGrantRedirectError = AuthImplicitGrantRedirectError; +function isAuthImplicitGrantRedirectError(error) { + return isAuthError(error) && error.name === 'AuthImplicitGrantRedirectError'; +} +/** + * Error thrown during PKCE code exchanges. + * + * @example + * ```ts + * import { AuthPKCEGrantCodeExchangeError } from '@supabase/auth-js' + * + * throw new AuthPKCEGrantCodeExchangeError('PKCE exchange failed') + * ``` + */ +class AuthPKCEGrantCodeExchangeError extends CustomAuthError { + constructor(message, details = null) { + super(message, 'AuthPKCEGrantCodeExchangeError', 500, undefined); + this.details = null; + this.details = details; + } + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + details: this.details, + }; + } +} +exports.AuthPKCEGrantCodeExchangeError = AuthPKCEGrantCodeExchangeError; +/** + * Error thrown when a transient fetch issue occurs. + * + * @example + * ```ts + * import { AuthRetryableFetchError } from '@supabase/auth-js' + * + * throw new AuthRetryableFetchError('Service temporarily unavailable', 503) + * ``` + */ +class AuthRetryableFetchError extends CustomAuthError { + constructor(message, status) { + super(message, 'AuthRetryableFetchError', status, undefined); + } +} +exports.AuthRetryableFetchError = AuthRetryableFetchError; +function isAuthRetryableFetchError(error) { + return isAuthError(error) && error.name === 'AuthRetryableFetchError'; +} +/** + * This error is thrown on certain methods when the password used is deemed + * weak. Inspect the reasons to identify what password strength rules are + * inadequate. + */ +/** + * Error thrown when a supplied password is considered weak. + * + * @example + * ```ts + * import { AuthWeakPasswordError } from '@supabase/auth-js' + * + * throw new AuthWeakPasswordError('Password too short', 400, ['min_length']) + * ``` + */ +class AuthWeakPasswordError extends CustomAuthError { + constructor(message, status, reasons) { + super(message, 'AuthWeakPasswordError', status, 'weak_password'); + this.reasons = reasons; + } +} +exports.AuthWeakPasswordError = AuthWeakPasswordError; +function isAuthWeakPasswordError(error) { + return isAuthError(error) && error.name === 'AuthWeakPasswordError'; +} +/** + * Error thrown when a JWT cannot be verified or parsed. + * + * @example + * ```ts + * import { AuthInvalidJwtError } from '@supabase/auth-js' + * + * throw new AuthInvalidJwtError('Token signature is invalid') + * ``` + */ +class AuthInvalidJwtError extends CustomAuthError { + constructor(message) { + super(message, 'AuthInvalidJwtError', 400, 'invalid_jwt'); + } +} +exports.AuthInvalidJwtError = AuthInvalidJwtError; +//# sourceMappingURL=errors.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/errors.js.map b/backend/node_modules/@supabase/auth-js/dist/main/lib/errors.js.map new file mode 100644 index 0000000..7d64e4f --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../src/lib/errors.ts"],"names":[],"mappings":";;;AAmCA,kCAEC;AAuBD,wCAEC;AA+DD,8DAEC;AAgED,4EAIC;AA8CD,8DAEC;AA8BD,0DAEC;AAhRD;;;;;;;;;GASG;AACH,MAAa,SAAU,SAAQ,KAAK;IAclC,YAAY,OAAe,EAAE,MAAe,EAAE,IAAa;QACzD,KAAK,CAAC,OAAO,CAAC,CAAA;QAHN,kBAAa,GAAG,IAAI,CAAA;QAI5B,IAAI,CAAC,IAAI,GAAG,WAAW,CAAA;QACvB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;IAClB,CAAC;CACF;AApBD,8BAoBC;AAED,SAAgB,WAAW,CAAC,KAAc;IACxC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,eAAe,IAAI,KAAK,CAAA;AAChF,CAAC;AAED;;;;;;;;;GASG;AACH,MAAa,YAAa,SAAQ,SAAS;IAGzC,YAAY,OAAe,EAAE,MAAc,EAA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AAC,MAAM;YACnB,OAAO,EAAE,IAAI,CAAC,OAAO;SACtB,CAAA;IACH,CAAC;CACF;AAhBD,wEAgBC;AAED;;;;;;;;;GASG;AACH,MAAa,uBAAwB,SAAQ,eAAe;IAC1D,YAAY,OAAe,EAAE,MAAc;QACzC,KAAK,CAAC,OAAO,EAAE,yBAAyB,EAAE,MAAM,EAAE,SAAS,CAAC,CAAA;IAC9D,CAAC;CACF;AAJD,0DAIC;AAED,SAAgB,yBAAyB,CAAC,KAAc;IACtD,OAAO,WAAW,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK,yBAAyB,CAAA;AACvE,CAAC;AAED;;;;GAIG;AACH;;;;;;;;;GASG;AACH,MAAa,qBAAsB,SAAQ,eAAe;IAMxD,YAAY,OAAe,EAAE,MAAc,EAAE,OAA8B;QACzE,KAAK,CAAC,OAAO,EAAE,uBAAuB,EAAE,MAAM,EAAE,eAAe,CAAC,CAAA;QAEhE,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;IACxB,CAAC;CACF;AAXD,sDAWC;AAED,SAAgB,uBAAuB,CAAC,KAAc;IACpD,OAAO,WAAW,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK,uBAAuB,CAAA;AACrE,CAAC;AAED;;;;;;;;;GASG;AACH,MAAa,mBAAoB,SAAQ,eAAe;IACtD,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,EAAE,qBAAqB,EAAE,GAAG,EAAE,aAAa,CAAC,CAAA;IAC3D,CAAC;CACF;AAJD,kDAIC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/fetch.d.ts b/backend/node_modules/@supabase/auth-js/dist/main/lib/fetch.d.ts new file mode 100644 index 0000000..4649c74 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/fetch.d.ts @@ -0,0 +1,34 @@ +import { AuthResponse, AuthResponsePassword, SSOResponse, GenerateLinkResponse, UserResponse } from './types'; +export type Fetch = typeof fetch; +export interface FetchOptions { + headers?: { + [key: string]: string; + }; + noResolveJson?: boolean; +} +export interface FetchParameters { + signal?: AbortSignal; +} +export type RequestMethodType = 'GET' | 'POST' | 'PUT' | 'DELETE'; +export declare function handleError(error: unknown): Promise; +interface GotrueRequestOptions extends FetchOptions { + jwt?: string; + redirectTo?: string; + body?: object; + query?: { + [key: string]: string; + }; + /** + * Function that transforms api response from gotrue into a desirable / standardised format + */ + xform?: (data: any) => any; +} +export declare function _request(fetcher: Fetch, method: RequestMethodType, url: string, options?: GotrueRequestOptions): Promise; +export declare function _sessionResponse(data: any): AuthResponse; +export declare function _sessionResponsePassword(data: any): AuthResponsePassword; +export declare function _userResponse(data: any): UserResponse; +export declare function _ssoResponse(data: any): SSOResponse; +export declare function _generateLinkResponse(data: any): GenerateLinkResponse; +export declare function _noResolveJsonResponse(data: any): Response; +export {}; +//# sourceMappingURL=fetch.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/fetch.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/main/lib/fetch.d.ts.map new file mode 100644 index 0000000..9f607b0 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/fetch.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../../../src/lib/fetch.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,YAAY,EACZ,oBAAoB,EACpB,WAAW,EAEX,oBAAoB,EAEpB,YAAY,EACb,MAAM,SAAS,CAAA;AAShB,MAAM,MAAM,KAAK,GAAG,OAAO,KAAK,CAAA;AAEhC,MAAM,WAAW,YAAY;IAC3B,OAAO,CAAC,EAAE;QACR,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KACtB,CAAA;IACD,aAAa,CAAC,EAAE,OAAO,CAAA;CACxB;AAED,MAAM,WAAW,eAAe;IAC9B,MAAM,CAAC,EAAE,WAAW,CAAA;CACrB;AAED,MAAM,MAAM,iBAAiB,GAAG,KAAK,GAAG,MAAM,GAAG,KAAK,GAAG,QAAQ,CAAA;AAOjE,wBAAsB,WAAW,CAAC,KAAK,EAAE,OAAO,iBA+D/C;AAmBD,UAAU,oBAAqB,SAAQ,YAAY;IACjD,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,KAAK,CAAC,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE,CAAA;IACjC;;OAEG;IACH,KAAK,CAAC,EAAE,CAAC,IAAI,EAAE,GAAG,KAAK,GAAG,CAAA;CAC3B;AAED,wBAAsB,QAAQ,CAC5B,OAAO,EAAE,KAAK,EACd,MAAM,EAAE,iBAAiB,EACzB,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,oBAAoB,gBAgC/B;AAwCD,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,GAAG,GAAG,YAAY,CAYxD;AAED,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,GAAG,GAAG,oBAAoB,CAiBxE;AAED,wBAAgB,aAAa,CAAC,IAAI,EAAE,GAAG,GAAG,YAAY,CAGrD;AAED,wBAAgB,YAAY,CAAC,IAAI,EAAE,GAAG,GAAG,WAAW,CAEnD;AAED,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,GAAG,GAAG,oBAAoB,CAmBrE;AAED,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,GAAG,GAAG,QAAQ,CAE1D"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/fetch.js b/backend/node_modules/@supabase/auth-js/dist/main/lib/fetch.js new file mode 100644 index 0000000..a7dd9d8 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/fetch.js @@ -0,0 +1,184 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.handleError = handleError; +exports._request = _request; +exports._sessionResponse = _sessionResponse; +exports._sessionResponsePassword = _sessionResponsePassword; +exports._userResponse = _userResponse; +exports._ssoResponse = _ssoResponse; +exports._generateLinkResponse = _generateLinkResponse; +exports._noResolveJsonResponse = _noResolveJsonResponse; +const tslib_1 = require("tslib"); +const constants_1 = require("./constants"); +const helpers_1 = require("./helpers"); +const errors_1 = require("./errors"); +const _getErrorMessage = (err) => err.msg || err.message || err.error_description || err.error || JSON.stringify(err); +const NETWORK_ERROR_CODES = [502, 503, 504]; +async function handleError(error) { + var _a; + if (!(0, helpers_1.looksLikeFetchResponse)(error)) { + throw new errors_1.AuthRetryableFetchError(_getErrorMessage(error), 0); + } + if (NETWORK_ERROR_CODES.includes(error.status)) { + // status in 500...599 range - server had an error, request might be retryed. + throw new errors_1.AuthRetryableFetchError(_getErrorMessage(error), error.status); + } + let data; + try { + data = await error.json(); + } + catch (e) { + throw new errors_1.AuthUnknownError(_getErrorMessage(e), e); + } + let errorCode = undefined; + const responseAPIVersion = (0, helpers_1.parseResponseAPIVersion)(error); + if (responseAPIVersion && + responseAPIVersion.getTime() >= constants_1.API_VERSIONS['2024-01-01'].timestamp && + typeof data === 'object' && + data && + typeof data.code === 'string') { + errorCode = data.code; + } + else if (typeof data === 'object' && data && typeof data.error_code === 'string') { + errorCode = data.error_code; + } + if (!errorCode) { + // Legacy support for weak password errors, when there were no error codes + if (typeof data === 'object' && + data && + typeof data.weak_password === 'object' && + data.weak_password && + Array.isArray(data.weak_password.reasons) && + data.weak_password.reasons.length && + data.weak_password.reasons.reduce((a, i) => a && typeof i === 'string', true)) { + throw new errors_1.AuthWeakPasswordError(_getErrorMessage(data), error.status, data.weak_password.reasons); + } + } + else if (errorCode === 'weak_password') { + throw new errors_1.AuthWeakPasswordError(_getErrorMessage(data), error.status, ((_a = data.weak_password) === null || _a === void 0 ? void 0 : _a.reasons) || []); + } + else if (errorCode === 'session_not_found') { + // The `session_id` inside the JWT does not correspond to a row in the + // `sessions` table. This usually means the user has signed out, has been + // deleted, or their session has somehow been terminated. + throw new errors_1.AuthSessionMissingError(); + } + throw new errors_1.AuthApiError(_getErrorMessage(data), error.status || 500, errorCode); +} +const _getRequestParams = (method, options, parameters, body) => { + const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} }; + if (method === 'GET') { + return params; + } + params.headers = Object.assign({ 'Content-Type': 'application/json;charset=UTF-8' }, options === null || options === void 0 ? void 0 : options.headers); + params.body = JSON.stringify(body); + return Object.assign(Object.assign({}, params), parameters); +}; +async function _request(fetcher, method, url, options) { + var _a; + const headers = Object.assign({}, options === null || options === void 0 ? void 0 : options.headers); + if (!headers[constants_1.API_VERSION_HEADER_NAME]) { + headers[constants_1.API_VERSION_HEADER_NAME] = constants_1.API_VERSIONS['2024-01-01'].name; + } + if (options === null || options === void 0 ? void 0 : options.jwt) { + headers['Authorization'] = `Bearer ${options.jwt}`; + } + const qs = (_a = options === null || options === void 0 ? void 0 : options.query) !== null && _a !== void 0 ? _a : {}; + if (options === null || options === void 0 ? void 0 : options.redirectTo) { + qs['redirect_to'] = options.redirectTo; + } + const queryString = Object.keys(qs).length ? '?' + new URLSearchParams(qs).toString() : ''; + const data = await _handleRequest(fetcher, method, url + queryString, { + headers, + noResolveJson: options === null || options === void 0 ? void 0 : options.noResolveJson, + }, {}, options === null || options === void 0 ? void 0 : options.body); + return (options === null || options === void 0 ? void 0 : options.xform) ? options === null || options === void 0 ? void 0 : options.xform(data) : { data: Object.assign({}, data), error: null }; +} +async function _handleRequest(fetcher, method, url, options, parameters, body) { + const requestParams = _getRequestParams(method, options, parameters, body); + let result; + try { + result = await fetcher(url, Object.assign({}, requestParams)); + } + catch (e) { + console.error(e); + // fetch failed, likely due to a network or CORS error + throw new errors_1.AuthRetryableFetchError(_getErrorMessage(e), 0); + } + if (!result.ok) { + await handleError(result); + } + if (options === null || options === void 0 ? void 0 : options.noResolveJson) { + return result; + } + try { + return await result.json(); + } + catch (e) { + await handleError(e); + } +} +function _sessionResponse(data) { + var _a; + let session = null; + if (hasSession(data)) { + session = Object.assign({}, data); + if (!data.expires_at) { + session.expires_at = (0, helpers_1.expiresAt)(data.expires_in); + } + } + const user = (_a = data.user) !== null && _a !== void 0 ? _a : data; + return { data: { session, user }, error: null }; +} +function _sessionResponsePassword(data) { + const response = _sessionResponse(data); + if (!response.error && + data.weak_password && + typeof data.weak_password === 'object' && + Array.isArray(data.weak_password.reasons) && + data.weak_password.reasons.length && + data.weak_password.message && + typeof data.weak_password.message === 'string' && + data.weak_password.reasons.reduce((a, i) => a && typeof i === 'string', true)) { + response.data.weak_password = data.weak_password; + } + return response; +} +function _userResponse(data) { + var _a; + const user = (_a = data.user) !== null && _a !== void 0 ? _a : data; + return { data: { user }, error: null }; +} +function _ssoResponse(data) { + return { data, error: null }; +} +function _generateLinkResponse(data) { + const { action_link, email_otp, hashed_token, redirect_to, verification_type } = data, rest = tslib_1.__rest(data, ["action_link", "email_otp", "hashed_token", "redirect_to", "verification_type"]); + const properties = { + action_link, + email_otp, + hashed_token, + redirect_to, + verification_type, + }; + const user = Object.assign({}, rest); + return { + data: { + properties, + user, + }, + error: null, + }; +} +function _noResolveJsonResponse(data) { + return data; +} +/** + * hasSession checks if the response object contains a valid session + * @param data A response object + * @returns true if a session is in the response + */ +function hasSession(data) { + return data.access_token && data.refresh_token && data.expires_in; +} +//# sourceMappingURL=fetch.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/fetch.js.map b/backend/node_modules/@supabase/auth-js/dist/main/lib/fetch.js.map new file mode 100644 index 0000000..2123852 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/fetch.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fetch.js","sourceRoot":"","sources":["../../../src/lib/fetch.ts"],"names":[],"mappings":";;AAuCA,kCA+DC;AA8BD,4BAoCC;AAwCD,4CAYC;AAED,4DAiBC;AAED,sCAGC;AAED,oCAEC;AAED,sDAmBC;AAED,wDAEC;;AAjRD,2CAAmE;AACnE,uCAAsF;AAUt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/main/lib/helpers.d.ts b/backend/node_modules/@supabase/auth-js/dist/main/lib/helpers.d.ts new file mode 100644 index 0000000..43fdc86 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/helpers.d.ts @@ -0,0 +1,91 @@ +import { JwtHeader, JwtPayload, SupportedStorage, User } from './types'; +import { Uint8Array_ } from './webauthn.dom'; +export declare function expiresAt(expiresIn: number): number; +/** + * Generates a unique identifier for internal callback subscriptions. + * + * This function uses JavaScript Symbols to create guaranteed-unique identifiers + * for auth state change callbacks. Symbols are ideal for this use case because: + * - They are guaranteed unique by the JavaScript runtime + * - They work in all environments (browser, SSR, Node.js) + * - They avoid issues with Next.js 16 deterministic rendering requirements + * - They are perfect for internal, non-serializable identifiers + * + * Note: This function is only used for internal subscription management, + * not for security-critical operations like session tokens. + */ +export declare function generateCallbackId(): symbol; +export declare const isBrowser: () => boolean; +/** + * Checks whether localStorage is supported on this browser. + */ +export declare const supportsLocalStorage: () => boolean; +/** + * Extracts parameters encoded in the URL both in the query and fragment. + */ +export declare function parseParametersFromURL(href: string): { + [parameter: string]: string; +}; +type Fetch = typeof fetch; +export declare const resolveFetch: (customFetch?: Fetch) => Fetch; +export declare const looksLikeFetchResponse: (maybeResponse: unknown) => maybeResponse is Response; +export declare const setItemAsync: (storage: SupportedStorage, key: string, data: any) => Promise; +export declare const getItemAsync: (storage: SupportedStorage, key: string) => Promise; +export declare const removeItemAsync: (storage: SupportedStorage, key: string) => Promise; +/** + * A deferred represents some asynchronous work that is not yet finished, which + * may or may not culminate in a value. + * Taken from: https://github.com/mike-north/types/blob/master/src/async.ts + */ +export declare class Deferred { + static promiseConstructor: PromiseConstructor; + readonly promise: PromiseLike; + readonly resolve: (value?: T | PromiseLike) => void; + readonly reject: (reason?: any) => any; + constructor(); +} +export declare function decodeJWT(token: string): { + header: JwtHeader; + payload: JwtPayload; + signature: Uint8Array_; + raw: { + header: string; + payload: string; + }; +}; +/** + * Creates a promise that resolves to null after some time. + */ +export declare function sleep(time: number): Promise; +/** + * Converts the provided async function into a retryable function. Each result + * or thrown error is sent to the isRetryable function which should return true + * if the function should run again. + */ +export declare function retryable(fn: (attempt: number) => Promise, isRetryable: (attempt: number, error: any | null, result?: T) => boolean): Promise; +export declare function generatePKCEVerifier(): string; +export declare function generatePKCEChallenge(verifier: string): Promise; +export declare function getCodeChallengeAndMethod(storage: SupportedStorage, storageKey: string, isPasswordRecovery?: boolean): Promise; +export declare function parseResponseAPIVersion(response: Response): Date | null; +export declare function validateExp(exp: number): void; +export declare function getAlgorithm(alg: 'HS256' | 'RS256' | 'ES256'): RsaHashedImportParams | EcKeyImportParams; +export declare function validateUUID(str: string): void; +export declare function userNotAvailableProxy(): User; +/** + * Creates a proxy around a user object that warns when properties are accessed on the server. + * This is used to alert developers that using user data from getSession() on the server is insecure. + * + * @param user The actual user object to wrap + * @param suppressWarningRef An object with a 'value' property that controls warning suppression + * @returns A proxied user object that warns on property access + */ +export declare function insecureUserWarningProxy(user: User, suppressWarningRef: { + value: boolean; +}): User; +/** + * Deep clones a JSON-serializable object using JSON.parse(JSON.stringify(obj)). + * Note: Only works for JSON-safe data. + */ +export declare function deepClone(obj: T): T; +export {}; +//# sourceMappingURL=helpers.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/helpers.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/main/lib/helpers.d.ts.map new file mode 100644 index 0000000..b87fd00 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/helpers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../../../src/lib/helpers.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,gBAAgB,EAAE,IAAI,EAAE,MAAM,SAAS,CAAA;AACvE,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA;AAE5C,wBAAgB,SAAS,CAAC,SAAS,EAAE,MAAM,UAG1C;AAED;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dist/main/lib/helpers.js new file mode 100644 index 0000000..0a8637f --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/helpers.js @@ -0,0 +1,395 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Deferred = exports.removeItemAsync = exports.getItemAsync = exports.setItemAsync = exports.looksLikeFetchResponse = exports.resolveFetch = exports.supportsLocalStorage = exports.isBrowser = void 0; +exports.expiresAt = expiresAt; +exports.generateCallbackId = generateCallbackId; +exports.parseParametersFromURL = parseParametersFromURL; +exports.decodeJWT = decodeJWT; +exports.sleep = sleep; +exports.retryable = retryable; +exports.generatePKCEVerifier = generatePKCEVerifier; +exports.generatePKCEChallenge = generatePKCEChallenge; +exports.getCodeChallengeAndMethod = getCodeChallengeAndMethod; +exports.parseResponseAPIVersion = parseResponseAPIVersion; +exports.validateExp = validateExp; +exports.getAlgorithm = getAlgorithm; +exports.validateUUID = validateUUID; +exports.userNotAvailableProxy = userNotAvailableProxy; +exports.insecureUserWarningProxy = insecureUserWarningProxy; +exports.deepClone = deepClone; +const constants_1 = require("./constants"); +const errors_1 = require("./errors"); +const base64url_1 = require("./base64url"); +function expiresAt(expiresIn) { + const timeNow = Math.round(Date.now() / 1000); + return timeNow + expiresIn; +} +/** + * Generates a unique identifier for internal callback subscriptions. + * + * This function uses JavaScript Symbols to create guaranteed-unique identifiers + * for auth state change callbacks. Symbols are ideal for this use case because: + * - They are guaranteed unique by the JavaScript runtime + * - They work in all environments (browser, SSR, Node.js) + * - They avoid issues with Next.js 16 deterministic rendering requirements + * - They are perfect for internal, non-serializable identifiers + * + * Note: This function is only used for internal subscription management, + * not for security-critical operations like session tokens. + */ +function generateCallbackId() { + return Symbol('auth-callback'); +} +const isBrowser = () => typeof window !== 'undefined' && typeof document !== 'undefined'; +exports.isBrowser = isBrowser; +const localStorageWriteTests = { + tested: false, + writable: false, +}; +/** + * Checks whether localStorage is supported on this browser. + */ +const supportsLocalStorage = () => { + if (!(0, exports.isBrowser)()) { + return false; + } + try { + if (typeof globalThis.localStorage !== 'object') { + return false; + } + } + catch (e) { + // DOM exception when accessing `localStorage` + return false; + } + if (localStorageWriteTests.tested) { + return localStorageWriteTests.writable; + } + const randomKey = `lswt-${Math.random()}${Math.random()}`; + try { + globalThis.localStorage.setItem(randomKey, randomKey); + globalThis.localStorage.removeItem(randomKey); + localStorageWriteTests.tested = true; + localStorageWriteTests.writable = true; + } + catch (e) { + // localStorage can't be written to + // https://www.chromium.org/for-testers/bug-reporting-guidelines/uncaught-securityerror-failed-to-read-the-localstorage-property-from-window-access-is-denied-for-this-document + localStorageWriteTests.tested = true; + localStorageWriteTests.writable = false; + } + return localStorageWriteTests.writable; +}; +exports.supportsLocalStorage = supportsLocalStorage; +/** + * Extracts parameters encoded in the URL both in the query and fragment. + */ +function parseParametersFromURL(href) { + const result = {}; + const url = new URL(href); + if (url.hash && url.hash[0] === '#') { + try { + const hashSearchParams = new URLSearchParams(url.hash.substring(1)); + hashSearchParams.forEach((value, key) => { + result[key] = value; + }); + } + catch (e) { + // hash is not a query string + } + } + // search parameters take precedence over hash parameters + url.searchParams.forEach((value, key) => { + result[key] = value; + }); + return result; +} +const resolveFetch = (customFetch) => { + if (customFetch) { + return (...args) => customFetch(...args); + } + return (...args) => fetch(...args); +}; +exports.resolveFetch = resolveFetch; +const looksLikeFetchResponse = (maybeResponse) => { + return (typeof maybeResponse === 'object' && + maybeResponse !== null && + 'status' in maybeResponse && + 'ok' in maybeResponse && + 'json' in maybeResponse && + typeof maybeResponse.json === 'function'); +}; +exports.looksLikeFetchResponse = looksLikeFetchResponse; +// Storage helpers +const setItemAsync = async (storage, key, data) => { + await storage.setItem(key, JSON.stringify(data)); +}; +exports.setItemAsync = setItemAsync; +const getItemAsync = async (storage, key) => { + const value = await storage.getItem(key); + if (!value) { + return null; + } + try { + return JSON.parse(value); + } + catch (_a) { + return value; + } +}; +exports.getItemAsync = getItemAsync; +const removeItemAsync = async (storage, key) => { + await storage.removeItem(key); +}; +exports.removeItemAsync = removeItemAsync; +/** + * A deferred represents some asynchronous work that is not yet finished, which + * may or may not culminate in a value. + * Taken from: https://github.com/mike-north/types/blob/master/src/async.ts + */ +class Deferred { + constructor() { + // eslint-disable-next-line @typescript-eslint/no-extra-semi + ; + this.promise = new Deferred.promiseConstructor((res, rej) => { + // eslint-disable-next-line @typescript-eslint/no-extra-semi + ; + this.resolve = res; + this.reject = rej; + }); + } +} +exports.Deferred = Deferred; +Deferred.promiseConstructor = Promise; +function decodeJWT(token) { + const parts = token.split('.'); + if (parts.length !== 3) { + throw new errors_1.AuthInvalidJwtError('Invalid JWT structure'); + } + // Regex checks for base64url format + for (let i = 0; i < parts.length; i++) { + if (!constants_1.BASE64URL_REGEX.test(parts[i])) { + throw new errors_1.AuthInvalidJwtError('JWT not in base64url format'); + } + } + const data = { + // using base64url lib + header: JSON.parse((0, base64url_1.stringFromBase64URL)(parts[0])), + payload: JSON.parse((0, base64url_1.stringFromBase64URL)(parts[1])), + signature: (0, base64url_1.base64UrlToUint8Array)(parts[2]), + raw: { + header: parts[0], + payload: parts[1], + }, + }; + return data; +} +/** + * Creates a promise that resolves to null after some time. + */ +async function sleep(time) { + return await new Promise((accept) => { + setTimeout(() => accept(null), time); + }); +} +/** + * Converts the provided async function into a retryable function. Each result + * or thrown error is sent to the isRetryable function which should return true + * if the function should run again. + */ +function retryable(fn, isRetryable) { + const promise = new Promise((accept, reject) => { + // eslint-disable-next-line @typescript-eslint/no-extra-semi + ; + (async () => { + for (let attempt = 0; attempt < Infinity; attempt++) { + try { + const result = await fn(attempt); + if (!isRetryable(attempt, null, result)) { + accept(result); + return; + } + } + catch (e) { + if (!isRetryable(attempt, e)) { + reject(e); + return; + } + } + } + })(); + }); + return promise; +} +function dec2hex(dec) { + return ('0' + dec.toString(16)).substr(-2); +} +// Functions below taken from: https://stackoverflow.com/questions/63309409/creating-a-code-verifier-and-challenge-for-pkce-auth-on-spotify-api-in-reactjs +function generatePKCEVerifier() { + const verifierLength = 56; + const array = new Uint32Array(verifierLength); + if (typeof crypto === 'undefined') { + const charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~'; + const charSetLen = charSet.length; + let verifier = ''; + for (let i = 0; i < verifierLength; i++) { + verifier += charSet.charAt(Math.floor(Math.random() * charSetLen)); + } + return verifier; + } + crypto.getRandomValues(array); + return Array.from(array, dec2hex).join(''); +} +async function sha256(randomString) { + const encoder = new TextEncoder(); + const encodedData = encoder.encode(randomString); + const hash = await crypto.subtle.digest('SHA-256', encodedData); + const bytes = new Uint8Array(hash); + return Array.from(bytes) + .map((c) => String.fromCharCode(c)) + .join(''); +} +async function generatePKCEChallenge(verifier) { + const hasCryptoSupport = typeof crypto !== 'undefined' && + typeof crypto.subtle !== 'undefined' && + typeof TextEncoder !== 'undefined'; + if (!hasCryptoSupport) { + console.warn('WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256.'); + return verifier; + } + const hashed = await sha256(verifier); + return btoa(hashed).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); +} +async function getCodeChallengeAndMethod(storage, storageKey, isPasswordRecovery = false) { + const codeVerifier = generatePKCEVerifier(); + let storedCodeVerifier = codeVerifier; + if (isPasswordRecovery) { + storedCodeVerifier += '/PASSWORD_RECOVERY'; + } + await (0, exports.setItemAsync)(storage, `${storageKey}-code-verifier`, storedCodeVerifier); + const codeChallenge = await generatePKCEChallenge(codeVerifier); + const codeChallengeMethod = codeVerifier === codeChallenge ? 'plain' : 's256'; + return [codeChallenge, codeChallengeMethod]; +} +/** Parses the API version which is 2YYY-MM-DD. */ +const API_VERSION_REGEX = /^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i; +function parseResponseAPIVersion(response) { + const apiVersion = response.headers.get(constants_1.API_VERSION_HEADER_NAME); + if (!apiVersion) { + return null; + } + if (!apiVersion.match(API_VERSION_REGEX)) { + return null; + } + try { + const date = new Date(`${apiVersion}T00:00:00.0Z`); + return date; + } + catch (e) { + return null; + } +} +function validateExp(exp) { + if (!exp) { + throw new Error('Missing exp claim'); + } + const timeNow = Math.floor(Date.now() / 1000); + if (exp <= timeNow) { + throw new Error('JWT has expired'); + } +} +function getAlgorithm(alg) { + switch (alg) { + case 'RS256': + return { + name: 'RSASSA-PKCS1-v1_5', + hash: { name: 'SHA-256' }, + }; + case 'ES256': + return { + name: 'ECDSA', + namedCurve: 'P-256', + hash: { name: 'SHA-256' }, + }; + default: + throw new Error('Invalid alg claim'); + } +} +const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; +function validateUUID(str) { + if (!UUID_REGEX.test(str)) { + throw new Error('@supabase/auth-js: Expected parameter to be UUID but is not'); + } +} +function userNotAvailableProxy() { + const proxyTarget = {}; + return new Proxy(proxyTarget, { + get: (target, prop) => { + if (prop === '__isUserNotAvailableProxy') { + return true; + } + // Preventative check for common problematic symbols during cloning/inspection + // These symbols might be accessed by structuredClone or other internal mechanisms. + if (typeof prop === 'symbol') { + const sProp = prop.toString(); + if (sProp === 'Symbol(Symbol.toPrimitive)' || + sProp === 'Symbol(Symbol.toStringTag)' || + sProp === 'Symbol(util.inspect.custom)') { + // Node.js util.inspect + return undefined; + } + } + throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${prop}" property of the session object is not supported. Please use getUser() instead.`); + }, + set: (_target, prop) => { + throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${prop}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`); + }, + deleteProperty: (_target, prop) => { + throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${prop}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`); + }, + }); +} +/** + * Creates a proxy around a user object that warns when properties are accessed on the server. + * This is used to alert developers that using user data from getSession() on the server is insecure. + * + * @param user The actual user object to wrap + * @param suppressWarningRef An object with a 'value' property that controls warning suppression + * @returns A proxied user object that warns on property access + */ +function insecureUserWarningProxy(user, suppressWarningRef) { + return new Proxy(user, { + get: (target, prop, receiver) => { + // Allow internal checks without warning + if (prop === '__isInsecureUserWarningProxy') { + return true; + } + // Preventative check for common problematic symbols during cloning/inspection + // These symbols might be accessed by structuredClone or other internal mechanisms + if (typeof prop === 'symbol') { + const sProp = prop.toString(); + if (sProp === 'Symbol(Symbol.toPrimitive)' || + sProp === 'Symbol(Symbol.toStringTag)' || + sProp === 'Symbol(util.inspect.custom)' || + sProp === 'Symbol(nodejs.util.inspect.custom)') { + // Return the actual value for these symbols to allow proper inspection + return Reflect.get(target, prop, receiver); + } + } + // Emit warning on first property access + if (!suppressWarningRef.value && typeof prop === 'string') { + console.warn('Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server.'); + suppressWarningRef.value = true; + } + return Reflect.get(target, prop, receiver); + }, + }); +} +/** + * Deep clones a JSON-serializable object using JSON.parse(JSON.stringify(obj)). + * Note: Only works for JSON-safe data. + */ +function deepClone(obj) { + return JSON.parse(JSON.stringify(obj)); +} +//# sourceMappingURL=helpers.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/helpers.js.map b/backend/node_modules/@supabase/auth-js/dist/main/lib/helpers.js.map new file mode 100644 index 0000000..1528183 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/helpers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"helpers.js","sourceRoot":"","sources":["../../../src/lib/helpers.ts"],"names":[],"mappings":";;;AAMA,8BAGC;AAeD,gDAEC;AAoDD,wDAsBC;AA0ED,8BAgCC;AAKD,sBAIC;AAOD,8BA0BC;AAOD,oDAcC;AAaD,sDAcC;AAED,8DAcC;AAKD,0DAiBC;A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zF,OAAO,IAAI,KAAK,CAAC,IAAI,EAAE;QACrB,GAAG,EAAE,CAAC,MAAW,EAAE,IAAqB,EAAE,QAAa,EAAE,EAAE;YACzD,wCAAwC;YACxC,IAAI,IAAI,KAAK,8BAA8B,EAAE,CAAC;gBAC5C,OAAO,IAAI,CAAA;YACb,CAAC;YAED,8EAA8E;YAC9E,kFAAkF;YAClF,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;gBAC7B,MAAM,KAAK,GAAG,IAAI,CAAC,QAAQ,EAAE,CAAA;gBAC7B,IACE,KAAK,KAAK,4BAA4B;oBACtC,KAAK,KAAK,4BAA4B;oBACtC,KAAK,KAAK,6BAA6B;oBACvC,KAAK,KAAK,oCAAoC,EAC9C,CAAC;oBACD,uEAAuE;oBACvE,OAAO,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAA;gBAC5C,CAAC;YACH,CAAC;YAED,wCAAwC;YACxC,IAAI,CAAC,kBAAkB,CAAC,KAAK,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;gBAC1D,OAAO,CAAC,IAAI,CACV,iWAAiW,CAClW,CAAA;gBACD,kBAAkB,CAAC,KAAK,GAAG,IAAI,CAAA;YACjC,CAAC;YAED,OAAO,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAA;QAC5C,CAAC;KACF,CAAC,CAAA;AACJ,CAAC;AAED;;;GAGG;AACH,SAAgB,SAAS,CAAI,GAAM;IACjC,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAA;AACxC,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/local-storage.d.ts b/backend/node_modules/@supabase/auth-js/dist/main/lib/local-storage.d.ts new file mode 100644 index 0000000..05dabc3 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/local-storage.d.ts @@ -0,0 +1,9 @@ +import { SupportedStorage } from './types'; +/** + * Returns a localStorage-like object that stores the key-value pairs in + * memory. + */ +export declare function memoryLocalStorageAdapter(store?: { + [key: string]: string; +}): SupportedStorage; +//# sourceMappingURL=local-storage.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/local-storage.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/main/lib/local-storage.d.ts.map new file mode 100644 index 0000000..7dc636e --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/local-storage.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"local-storage.d.ts","sourceRoot":"","sources":["../../../src/lib/local-storage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAE1C;;;GAGG;AACH,wBAAgB,yBAAyB,CAAC,KAAK,GAAE;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;CAAO,GAAG,gBAAgB,CAcjG"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/local-storage.js b/backend/node_modules/@supabase/auth-js/dist/main/lib/local-storage.js new file mode 100644 index 0000000..bd9e06a --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/local-storage.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.memoryLocalStorageAdapter = memoryLocalStorageAdapter; +/** + * Returns a localStorage-like object that stores the key-value pairs in + * memory. + */ +function memoryLocalStorageAdapter(store = {}) { + return { + getItem: (key) => { + return store[key] || null; + }, + setItem: (key, value) => { + store[key] = value; + }, + removeItem: (key) => { + delete store[key]; + }, + }; +} +//# sourceMappingURL=local-storage.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/local-storage.js.map b/backend/node_modules/@supabase/auth-js/dist/main/lib/local-storage.js.map new file mode 100644 index 0000000..c2eb762 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/local-storage.js.map @@ -0,0 +1 @@ +{"version":3,"file":"local-storage.js","sourceRoot":"","sources":["../../../src/lib/local-storage.ts"],"names":[],"mappings":";;AAMA,8DAcC;AAlBD;;;GAGG;AACH,SAAgB,yBAAyB,CAAC,QAAmC,EAAE;IAC7E,OAAO;QACL,OAAO,EAAE,CAAC,GAAG,EAAE,EAAE;YACf,OAAO,KAAK,CAAC,GAAG,CAAC,IAAI,IAAI,CAAA;QAC3B,CAAC;QAED,OAAO,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE;YACtB,KAAK,CAAC,GAAG,CAAC,GAAG,KAAK,CAAA;QACpB,CAAC;QAED,UAAU,EAAE,CAAC,GAAG,EAAE,EAAE;YAClB,OAAO,KAAK,CAAC,GAAG,CAAC,CAAA;QACnB,CAAC;KACF,CAAA;AACH,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/locks.d.ts b/backend/node_modules/@supabase/auth-js/dist/main/lib/locks.d.ts new file mode 100644 index 0000000..41c5032 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/locks.d.ts @@ -0,0 +1,107 @@ +/** + * @experimental + */ +export declare const internals: { + /** + * @experimental + */ + debug: boolean; +}; +/** + * An error thrown when a lock cannot be acquired after some amount of time. + * + * Use the {@link #isAcquireTimeout} property instead of checking with `instanceof`. + * + * @example + * ```ts + * import { LockAcquireTimeoutError } from '@supabase/auth-js' + * + * class CustomLockError extends LockAcquireTimeoutError { + * constructor() { + * super('Lock timed out') + * } + * } + * ``` + */ +export declare abstract class LockAcquireTimeoutError extends Error { + readonly isAcquireTimeout = true; + constructor(message: string); +} +/** + * Error thrown when the browser Navigator Lock API fails to acquire a lock. + * + * @example + * ```ts + * import { NavigatorLockAcquireTimeoutError } from '@supabase/auth-js' + * + * throw new NavigatorLockAcquireTimeoutError('Lock timed out') + * ``` + */ +export declare class NavigatorLockAcquireTimeoutError extends LockAcquireTimeoutError { +} +/** + * Error thrown when the process-level lock helper cannot acquire a lock. + * + * @example + * ```ts + * import { ProcessLockAcquireTimeoutError } from '@supabase/auth-js' + * + * throw new ProcessLockAcquireTimeoutError('Lock timed out') + * ``` + */ +export declare class ProcessLockAcquireTimeoutError extends LockAcquireTimeoutError { +} +/** + * Implements a global exclusive lock using the Navigator LockManager API. It + * is available on all browsers released after 2022-03-15 with Safari being the + * last one to release support. If the API is not available, this function will + * throw. Make sure you check availablility before configuring {@link + * GoTrueClient}. + * + * You can turn on debugging by setting the `supabase.gotrue-js.locks.debug` + * local storage item to `true`. + * + * Internals: + * + * Since the LockManager API does not preserve stack traces for the async + * function passed in the `request` method, a trick is used where acquiring the + * lock releases a previously started promise to run the operation in the `fn` + * function. The lock waits for that promise to finish (with or without error), + * while the function will finally wait for the result anyway. + * + * @param name Name of the lock to be acquired. + * @param acquireTimeout If negative, no timeout. If 0 an error is thrown if + * the lock can't be acquired without waiting. If positive, the lock acquire + * will time out after so many milliseconds. An error is + * a timeout if it has `isAcquireTimeout` set to true. + * @param fn The operation to run once the lock is acquired. + * @example + * ```ts + * await navigatorLock('sync-user', 1000, async () => { + * await refreshSession() + * }) + * ``` + */ +export declare function navigatorLock(name: string, acquireTimeout: number, fn: () => Promise): Promise; +/** + * Implements a global exclusive lock that works only in the current process. + * Useful for environments like React Native or other non-browser + * single-process (i.e. no concept of "tabs") environments. + * + * Use {@link #navigatorLock} in browser environments. + * + * @param name Name of the lock to be acquired. + * @param acquireTimeout If negative, no timeout. If 0 an error is thrown if + * the lock can't be acquired without waiting. If positive, the lock acquire + * will time out after so many milliseconds. An error is + * a timeout if it has `isAcquireTimeout` set to true. + * @param fn The operation to run once the lock is acquired. + * @example + * ```ts + * await processLock('migrate', 5000, async () => { + * await runMigration() + * }) + * ``` + */ +export declare function processLock(name: string, acquireTimeout: number, fn: () => Promise): Promise; +//# sourceMappingURL=locks.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/locks.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/main/lib/locks.d.ts.map new file mode 100644 index 0000000..c03b579 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/locks.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"locks.d.ts","sourceRoot":"","sources":["../../../src/lib/locks.ts"],"names":[],"mappings":"AAEA;;GAEG;AACH,eAAO,MAAM,SAAS;IACpB;;OAEG;;CAOJ,CAAA;AAED;;;;;;;;;;;;;;;GAeG;AACH,8BAAsB,uBAAwB,SAAQ,KAAK;IACzD,SAAgB,gBAAgB,QAAO;gBAE3B,OAAO,EAAE,MAAM;CAG5B;AAED;;;;;;;;;GASG;AACH,qBAAa,gCAAiC,SAAQ,uBAAuB;CAAG;AAChF;;;;;;;;;GASG;AACH,qBAAa,8BAA+B,SAAQ,uBAAuB;CAAG;AAE9E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,wBAAsB,aAAa,CAAC,CAAC,EACnC,IAAI,EAAE,MAAM,EACZ,cAAc,EAAE,MAAM,EACtB,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GACnB,OAAO,CAAC,CAAC,CAAC,CA0FZ;AAID;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAsB,WAAW,CAAC,CAAC,EACjC,IAAI,EAAE,MAAM,EACZ,cAAc,EAAE,MAAM,EACtB,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GACnB,OAAO,CAAC,CAAC,CAAC,CAkDZ"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/locks.js b/backend/node_modules/@supabase/auth-js/dist/main/lib/locks.js new file mode 100644 index 0000000..d1df03e --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/locks.js @@ -0,0 +1,230 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ProcessLockAcquireTimeoutError = exports.NavigatorLockAcquireTimeoutError = exports.LockAcquireTimeoutError = exports.internals = void 0; +exports.navigatorLock = navigatorLock; +exports.processLock = processLock; +const helpers_1 = require("./helpers"); +/** + * @experimental + */ +exports.internals = { + /** + * @experimental + */ + debug: !!(globalThis && + (0, helpers_1.supportsLocalStorage)() && + globalThis.localStorage && + globalThis.localStorage.getItem('supabase.gotrue-js.locks.debug') === 'true'), +}; +/** + * An error thrown when a lock cannot be acquired after some amount of time. + * + * Use the {@link #isAcquireTimeout} property instead of checking with `instanceof`. + * + * @example + * ```ts + * import { LockAcquireTimeoutError } from '@supabase/auth-js' + * + * class CustomLockError extends LockAcquireTimeoutError { + * constructor() { + * super('Lock timed out') + * } + * } + * ``` + */ +class LockAcquireTimeoutError extends Error { + constructor(message) { + super(message); + this.isAcquireTimeout = true; + } +} +exports.LockAcquireTimeoutError = LockAcquireTimeoutError; +/** + * Error thrown when the browser Navigator Lock API fails to acquire a lock. + * + * @example + * ```ts + * import { NavigatorLockAcquireTimeoutError } from '@supabase/auth-js' + * + * throw new NavigatorLockAcquireTimeoutError('Lock timed out') + * ``` + */ +class NavigatorLockAcquireTimeoutError extends LockAcquireTimeoutError { +} +exports.NavigatorLockAcquireTimeoutError = NavigatorLockAcquireTimeoutError; +/** + * Error thrown when the process-level lock helper cannot acquire a lock. + * + * @example + * ```ts + * import { ProcessLockAcquireTimeoutError } from '@supabase/auth-js' + * + * throw new ProcessLockAcquireTimeoutError('Lock timed out') + * ``` + */ +class ProcessLockAcquireTimeoutError extends LockAcquireTimeoutError { +} +exports.ProcessLockAcquireTimeoutError = ProcessLockAcquireTimeoutError; +/** + * Implements a global exclusive lock using the Navigator LockManager API. It + * is available on all browsers released after 2022-03-15 with Safari being the + * last one to release support. If the API is not available, this function will + * throw. Make sure you check availablility before configuring {@link + * GoTrueClient}. + * + * You can turn on debugging by setting the `supabase.gotrue-js.locks.debug` + * local storage item to `true`. + * + * Internals: + * + * Since the LockManager API does not preserve stack traces for the async + * function passed in the `request` method, a trick is used where acquiring the + * lock releases a previously started promise to run the operation in the `fn` + * function. The lock waits for that promise to finish (with or without error), + * while the function will finally wait for the result anyway. + * + * @param name Name of the lock to be acquired. + * @param acquireTimeout If negative, no timeout. If 0 an error is thrown if + * the lock can't be acquired without waiting. If positive, the lock acquire + * will time out after so many milliseconds. An error is + * a timeout if it has `isAcquireTimeout` set to true. + * @param fn The operation to run once the lock is acquired. + * @example + * ```ts + * await navigatorLock('sync-user', 1000, async () => { + * await refreshSession() + * }) + * ``` + */ +async function navigatorLock(name, acquireTimeout, fn) { + if (exports.internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock: acquire lock', name, acquireTimeout); + } + const abortController = new globalThis.AbortController(); + if (acquireTimeout > 0) { + setTimeout(() => { + abortController.abort(); + if (exports.internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock acquire timed out', name); + } + }, acquireTimeout); + } + // MDN article: https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request + // Wrapping navigator.locks.request() with a plain Promise is done as some + // libraries like zone.js patch the Promise object to track the execution + // context. However, it appears that most browsers use an internal promise + // implementation when using the navigator.locks.request() API causing them + // to lose context and emit confusing log messages or break certain features. + // This wrapping is believed to help zone.js track the execution context + // better. + return await Promise.resolve().then(() => globalThis.navigator.locks.request(name, acquireTimeout === 0 + ? { + mode: 'exclusive', + ifAvailable: true, + } + : { + mode: 'exclusive', + signal: abortController.signal, + }, async (lock) => { + if (lock) { + if (exports.internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock: acquired', name, lock.name); + } + try { + return await fn(); + } + finally { + if (exports.internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock: released', name, lock.name); + } + } + } + else { + if (acquireTimeout === 0) { + if (exports.internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock: not immediately available', name); + } + throw new NavigatorLockAcquireTimeoutError(`Acquiring an exclusive Navigator LockManager lock "${name}" immediately failed`); + } + else { + if (exports.internals.debug) { + try { + const result = await globalThis.navigator.locks.query(); + console.log('@supabase/gotrue-js: Navigator LockManager state', JSON.stringify(result, null, ' ')); + } + catch (e) { + console.warn('@supabase/gotrue-js: Error when querying Navigator LockManager state', e); + } + } + // Browser is not following the Navigator LockManager spec, it + // returned a null lock when we didn't use ifAvailable. So we can + // pretend the lock is acquired in the name of backward compatibility + // and user experience and just run the function. + console.warn('@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request'); + return await fn(); + } + } + })); +} +const PROCESS_LOCKS = {}; +/** + * Implements a global exclusive lock that works only in the current process. + * Useful for environments like React Native or other non-browser + * single-process (i.e. no concept of "tabs") environments. + * + * Use {@link #navigatorLock} in browser environments. + * + * @param name Name of the lock to be acquired. + * @param acquireTimeout If negative, no timeout. If 0 an error is thrown if + * the lock can't be acquired without waiting. If positive, the lock acquire + * will time out after so many milliseconds. An error is + * a timeout if it has `isAcquireTimeout` set to true. + * @param fn The operation to run once the lock is acquired. + * @example + * ```ts + * await processLock('migrate', 5000, async () => { + * await runMigration() + * }) + * ``` + */ +async function processLock(name, acquireTimeout, fn) { + var _a; + const previousOperation = (_a = PROCESS_LOCKS[name]) !== null && _a !== void 0 ? _a : Promise.resolve(); + const currentOperation = Promise.race([ + previousOperation.catch(() => { + // ignore error of previous operation that we're waiting to finish + return null; + }), + acquireTimeout >= 0 + ? new Promise((_, reject) => { + setTimeout(() => { + reject(new ProcessLockAcquireTimeoutError(`Acquring process lock with name "${name}" timed out`)); + }, acquireTimeout); + }) + : null, + ].filter((x) => x)) + .catch((e) => { + if (e && e.isAcquireTimeout) { + throw e; + } + return null; + }) + .then(async () => { + // previous operations finished and we didn't get a race on the acquire + // timeout, so the current operation can finally start + return await fn(); + }); + PROCESS_LOCKS[name] = currentOperation.catch(async (e) => { + if (e && e.isAcquireTimeout) { + // if the current operation timed out, it doesn't mean that the previous + // operation finished, so we need contnue waiting for it to finish + await previousOperation; + return null; + } + throw e; + }); + // finally wait for the current operation to finish successfully, with an + // error or with an acquire timeout error + return await currentOperation; +} +//# sourceMappingURL=locks.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/locks.js.map b/backend/node_modules/@supabase/auth-js/dist/main/lib/locks.js.map new file mode 100644 index 0000000..42d12ab --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/locks.js.map @@ -0,0 +1 @@ +{"version":3,"file":"locks.js","sourceRoot":"","sources":["../../../src/lib/locks.ts"],"names":[],"mappings":";;;AA+FA,sCA8FC;AAwBD,kCAsDC;AA3QD,uCAAgD;AAEhD;;GAEG;AACU,QAAA,SAAS,GAAG;IACvB;;OAEG;IACH,KAAK,EAAE,CAAC,CAAC,CACP,UAAU;QACV,IAAA,8BAAoB,GAAE;QACtB,UAAU,CAAC,YAAY;QACvB,UAAU,CAAC,YAAY,CAAC,OAAO,CAAC,gCAAgC,CAAC,KAAK,MAAM,CAC7E;CACF,CAAA;AAED;;;;;;;;;;;;;;;GAeG;AACH,MAAsB,uBAAwB,SAAQ,KAAK;IAGzD,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAA;QAHA,qBAAgB,GAAG,IAAI,CAAA;IAIvC,CAAC;CACF;AAND,0DAMC;AAED;;;;;;;;;GASG;AACH,MAAa,gCAAiC,SAAQ,uBAAuB;CAAG;AAAhF,4EAAgF;AAChF;;;;;;;;;GASG;AACH,MAAa,8BAA+B,SAAQ,uBAAuB;CAAG;AAA9E,wEAA8E;AAE9E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACI,KAAK,UAAU,aAAa,CACjC,IAAY,EACZ,cAAsB,EACtB,EAAoB;IAEpB,IAAI,iBAAS,CAAC,KAAK,EAAE,CAAC;QACpB,OAAO,CAAC,GAAG,CAAC,kDAAkD,EAAE,IAAI,EAAE,cAAc,CAAC,CAAA;IACvF,CAAC;IAED,MAAM,eAAe,GAAG,IAAI,UAAU,CAAC,eAAe,EAAE,CAAA;IAExD,IAAI,cAAc,GAAG,C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AAE,EAAE;gBACxB,UAAU,CAAC,GAAG,EAAE;oBACd,MAAM,CACJ,IAAI,8BAA8B,CAChC,oCAAoC,IAAI,aAAa,CACtD,CACF,CAAA;gBACH,CAAC,EAAE,cAAc,CAAC,CAAA;YACpB,CAAC,CAAC;YACJ,CAAC,CAAC,IAAI;KACT,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CACnB;SACE,KAAK,CAAC,CAAC,CAAM,EAAE,EAAE;QAChB,IAAI,CAAC,IAAI,CAAC,CAAC,gBAAgB,EAAE,CAAC;YAC5B,MAAM,CAAC,CAAA;QACT,CAAC;QAED,OAAO,IAAI,CAAA;IACb,CAAC,CAAC;SACD,IAAI,CAAC,KAAK,IAAI,EAAE;QACf,uEAAuE;QACvE,sDAAsD;QACtD,OAAO,MAAM,EAAE,EAAE,CAAA;IACnB,CAAC,CAAC,CAAA;IAEJ,aAAa,CAAC,IAAI,CAAC,GAAG,gBAAgB,CAAC,KAAK,CAAC,KAAK,EAAE,CAAM,EAAE,EAAE;QAC5D,IAAI,CAAC,IAAI,CAAC,CAAC,gBAAgB,EAAE,CAAC;YAC5B,wEAAwE;YACxE,kEAAkE;YAClE,MAAM,iBAAiB,CAAA;YAEvB,OAAO,IAAI,CAAA;QACb,CAAC;QAED,MAAM,CAAC,CAAA;IACT,CAAC,CAAC,CAAA;IAEF,yEAAyE;IACzE,yCAAyC;IACzC,OAAO,MAAM,gBAAgB,CAAA;AAC/B,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/polyfills.d.ts b/backend/node_modules/@supabase/auth-js/dist/main/lib/polyfills.d.ts new file mode 100644 index 0000000..d85562a --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/polyfills.d.ts @@ -0,0 +1,5 @@ +/** + * https://mathiasbynens.be/notes/globalthis + */ +export declare function polyfillGlobalThis(): void; +//# sourceMappingURL=polyfills.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/polyfills.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/main/lib/polyfills.d.ts.map new file mode 100644 index 0000000..ee5ea0f --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/polyfills.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfills.d.ts","sourceRoot":"","sources":["../../../src/lib/polyfills.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,wBAAgB,kBAAkB,SAmBjC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/polyfills.js b/backend/node_modules/@supabase/auth-js/dist/main/lib/polyfills.js new file mode 100644 index 0000000..7623d47 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/polyfills.js @@ -0,0 +1,29 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.polyfillGlobalThis = polyfillGlobalThis; +/** + * https://mathiasbynens.be/notes/globalthis + */ +function polyfillGlobalThis() { + if (typeof globalThis === 'object') + return; + try { + Object.defineProperty(Object.prototype, '__magic__', { + get: function () { + return this; + }, + configurable: true, + }); + // @ts-expect-error 'Allow access to magic' + __magic__.globalThis = __magic__; + // @ts-expect-error 'Allow access to magic' + delete Object.prototype.__magic__; + } + catch (e) { + if (typeof self !== 'undefined') { + // @ts-expect-error 'Allow access to globals' + self.globalThis = self; + } + } +} +//# sourceMappingURL=polyfills.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/polyfills.js.map b/backend/node_modules/@supabase/auth-js/dist/main/lib/polyfills.js.map new file mode 100644 index 0000000..8edc336 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/polyfills.js.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfills.js","sourceRoot":"","sources":["../../../src/lib/polyfills.ts"],"names":[],"mappings":";;AAGA,gDAmBC;AAtBD;;GAEG;AACH,SAAgB,kBAAkB;IAChC,IAAI,OAAO,UAAU,KAAK,QAAQ;QAAE,OAAM;IAC1C,IAAI,CAAC;QACH,MAAM,CAAC,cAAc,CAAC,MAAM,CAAC,SAAS,EAAE,WAAW,EAAE;YACnD,GAAG,EAAE;gBACH,OAAO,IAAI,CAAA;YACb,CAAC;YACD,YAAY,EAAE,IAAI;SACnB,CAAC,CAAA;QACF,2CAA2C;QAC3C,SAAS,CAAC,UAAU,GAAG,SAAS,CAAA;QAChC,2CAA2C;QAC3C,OAAO,MAAM,CAAC,SAAS,CAAC,SAAS,CAAA;IACnC,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,IAAI,OAAO,IAAI,KAAK,WAAW,EAAE,CAAC;YAChC,6CAA6C;YAC7C,IAAI,CAAC,UAAU,GAAG,IAAI,CAAA;QACxB,CAAC;IACH,CAAC;AACH,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/types.d.ts b/backend/node_modules/@supabase/auth-js/dist/main/lib/types.d.ts new file mode 100644 index 0000000..2f66ff4 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/types.d.ts @@ -0,0 +1,1468 @@ +import { AuthError } from './errors'; +import { Fetch } from './fetch'; +import { EIP1193Provider, EthereumSignInInput, Hex } from './web3/ethereum'; +import type { SolanaSignInInput, SolanaSignInOutput } from './web3/solana'; +import { ServerCredentialCreationOptions, ServerCredentialRequestOptions, WebAuthnApi } from './webauthn'; +import { AuthenticationCredential, PublicKeyCredentialCreationOptionsFuture, PublicKeyCredentialRequestOptionsFuture, RegistrationCredential } from './webauthn.dom'; +/** One of the providers supported by GoTrue. */ +export type Provider = 'apple' | 'azure' | 'bitbucket' | 'discord' | 'facebook' | 'figma' | 'github' | 'gitlab' | 'google' | 'kakao' | 'keycloak' | 'linkedin' | 'linkedin_oidc' | 'notion' | 'slack' | 'slack_oidc' | 'spotify' | 'twitch' | 'twitter' | 'workos' | 'zoom' | 'fly'; +export type AuthChangeEventMFA = 'MFA_CHALLENGE_VERIFIED'; +export type AuthChangeEvent = 'INITIAL_SESSION' | 'PASSWORD_RECOVERY' | 'SIGNED_IN' | 'SIGNED_OUT' | 'TOKEN_REFRESHED' | 'USER_UPDATED' | AuthChangeEventMFA; +/** + * Provide your own global lock implementation instead of the default + * implementation. The function should acquire a lock for the duration of the + * `fn` async function, such that no other client instances will be able to + * hold it at the same time. + * + * @experimental + * + * @param name Name of the lock to be acquired. + * @param acquireTimeout If negative, no timeout should occur. If positive it + * should throw an Error with an `isAcquireTimeout` + * property set to true if the operation fails to be + * acquired after this much time (ms). + * @param fn The operation to execute when the lock is acquired. + */ +export type LockFunc = (name: string, acquireTimeout: number, fn: () => Promise) => Promise; +export type GoTrueClientOptions = { + url?: string; + headers?: { + [key: string]: string; + }; + storageKey?: string; + detectSessionInUrl?: boolean; + autoRefreshToken?: boolean; + persistSession?: boolean; + storage?: SupportedStorage; + /** + * Stores the user object in a separate storage location from the rest of the session data. When non-null, `storage` will only store a JSON object containing the access and refresh token and some adjacent metadata, while `userStorage` will only contain the user object under the key `storageKey + '-user'`. + * + * When this option is set and cookie storage is used, `getSession()` and other functions that load a session from the cookie store might not return back a user. It's very important to always use `getUser()` to fetch a user object in those scenarios. + * + * @experimental + */ + userStorage?: SupportedStorage; + fetch?: Fetch; + flowType?: AuthFlowType; + debug?: boolean | ((message: string, ...args: any[]) => void); + /** + * Provide your own locking mechanism based on the environment. By default no locking is done at this time. + * + * @experimental + */ + lock?: LockFunc; + /** + * Set to "true" if there is a custom authorization header set globally. + * @experimental + */ + hasCustomAuthorizationHeader?: boolean; + /** + * If there is an error with the query, throwOnError will reject the promise by + * throwing the error instead of returning it as part of a successful response. + */ + throwOnError?: boolean; +}; +declare const WeakPasswordReasons: readonly ["length", "characters", "pwned"]; +export type WeakPasswordReasons = (typeof WeakPasswordReasons)[number]; +export type WeakPassword = { + reasons: WeakPasswordReasons[]; + message: string; +}; +/** + * Resolve mapped types and show the derived keys and their types when hovering in + * VS Code, instead of just showing the names those mapped types are defined with. + */ +export type Prettify = T extends Function ? T : { + [K in keyof T]: T[K]; +}; +/** + * A stricter version of TypeScript's Omit that only allows omitting keys that actually exist. + * This prevents typos and ensures type safety at compile time. + * Unlike regular Omit, this will error if you try to omit a non-existent key. + */ +export type StrictOmit = Omit; +/** + * a shared result type that encapsulates errors instead of throwing them, allows you to optionally specify the ErrorType + */ +export type RequestResult = { + data: T; + error: null; +} | { + data: null; + error: Error extends AuthError ? AuthError : ErrorType; +}; +/** + * similar to RequestResult except it allows you to destructure the possible shape of the success response + * {@see RequestResult} + */ +export type RequestResultSafeDestructure = { + data: T; + error: null; +} | { + data: T extends object ? { + [K in keyof T]: null; + } : null; + error: AuthError; +}; +export type AuthResponse = RequestResultSafeDestructure<{ + user: User | null; + session: Session | null; +}>; +export type AuthResponsePassword = RequestResultSafeDestructure<{ + user: User | null; + session: Session | null; + weak_password?: WeakPassword | null; +}>; +/** + * AuthOtpResponse is returned when OTP is used. + * + * {@see AuthResponse} + */ +export type AuthOtpResponse = RequestResultSafeDestructure<{ + user: null; + session: null; + messageId?: string | null; +}>; +export type AuthTokenResponse = RequestResultSafeDestructure<{ + user: User; + session: Session; +}>; +export type AuthTokenResponsePassword = RequestResultSafeDestructure<{ + user: User; + session: Session; + weakPassword?: WeakPassword; +}>; +export type OAuthResponse = { + data: { + provider: Provider; + url: string; + }; + error: null; +} | { + data: { + provider: Provider; + url: null; + }; + error: AuthError; +}; +export type SSOResponse = RequestResult<{ + /** + * URL to open in a browser which will complete the sign-in flow by + * taking the user to the identity provider's authentication flow. + * + * On browsers you can set the URL to `window.location.href` to take + * the user to the authentication flow. + */ + url: string; +}>; +export type UserResponse = RequestResultSafeDestructure<{ + user: User; +}>; +export interface Session { + /** + * The oauth provider token. If present, this can be used to make external API requests to the oauth provider used. + */ + provider_token?: string | null; + /** + * The oauth provider refresh token. If present, this can be used to refresh the provider_token via the oauth provider's API. + * Not all oauth providers return a provider refresh token. If the provider_refresh_token is missing, please refer to the oauth provider's documentation for information on how to obtain the provider refresh token. + */ + provider_refresh_token?: string | null; + /** + * The access token jwt. It is recommended to set the JWT_EXPIRY to a shorter expiry value. + */ + access_token: string; + /** + * A one-time used refresh token that never expires. + */ + refresh_token: string; + /** + * The number of seconds until the token expires (since it was issued). Returned when a login is confirmed. + */ + expires_in: number; + /** + * A timestamp of when the token will expire. Returned when a login is confirmed. + */ + expires_at?: number; + token_type: 'bearer'; + /** + * When using a separate user storage, accessing properties of this object will throw an error. + */ + user: User; +} +declare const AMRMethods: readonly ["password", "otp", "oauth", "totp", "mfa/totp", "mfa/phone", "mfa/webauthn", "anonymous", "sso/saml", "magiclink", "web3"]; +export type AMRMethod = (typeof AMRMethods)[number] | (string & {}); +/** + * An authentication methord reference (AMR) entry. + * + * An entry designates what method was used by the user to verify their + * identity and at what time. + * + * @see {@link GoTrueMFAApi#getAuthenticatorAssuranceLevel}. + */ +export interface AMREntry { + /** Authentication method name. */ + method: AMRMethod; + /** + * Timestamp when the method was successfully used. Represents number of + * seconds since 1st January 1970 (UNIX epoch) in UTC. + */ + timestamp: number; +} +export interface UserIdentity { + id: string; + user_id: string; + identity_data?: { + [key: string]: any; + }; + identity_id: string; + provider: string; + created_at?: string; + last_sign_in_at?: string; + updated_at?: string; +} +declare const FactorTypes: readonly ["totp", "phone", "webauthn"]; +/** + * Type of factor. `totp` and `phone` supported with this version + */ +export type FactorType = (typeof FactorTypes)[number]; +declare const FactorVerificationStatuses: readonly ["verified", "unverified"]; +/** + * The verification status of the factor, default is `unverified` after `.enroll()`, then `verified` after the user verifies it with `.verify()` + */ +type FactorVerificationStatus = (typeof FactorVerificationStatuses)[number]; +/** + * A MFA factor. + * + * @see {@link GoTrueMFAApi#enroll} + * @see {@link GoTrueMFAApi#listFactors} + * @see {@link GoTrueMFAAdminApi#listFactors} + */ +export type Factor = { + /** ID of the factor. */ + id: string; + /** Friendly name of the factor, useful to disambiguate between multiple factors. */ + friendly_name?: string; + /** + * Type of factor. `totp` and `phone` supported with this version + */ + factor_type: Type; + /** + * The verification status of the factor, default is `unverified` after `.enroll()`, then `verified` after the user verifies it with `.verify()` + */ + status: Status; + created_at: string; + updated_at: string; +}; +export interface UserAppMetadata { + /** + * The first provider that the user used to sign up with. + */ + provider?: string; + /** + * A list of all providers that the user has linked to their account. + */ + providers?: string[]; + [key: string]: any; +} +export interface UserMetadata { + [key: string]: any; +} +export interface User { + id: string; + app_metadata: UserAppMetadata; + user_metadata: UserMetadata; + aud: string; + confirmation_sent_at?: string; + recovery_sent_at?: string; + email_change_sent_at?: string; + new_email?: string; + new_phone?: string; + invited_at?: string; + action_link?: string; + email?: string; + phone?: string; + created_at: string; + confirmed_at?: string; + email_confirmed_at?: string; + phone_confirmed_at?: string; + last_sign_in_at?: string; + role?: string; + updated_at?: string; + identities?: UserIdentity[]; + is_anonymous?: boolean; + is_sso_user?: boolean; + factors?: (Factor | Factor)[]; + deleted_at?: string; +} +export interface UserAttributes { + /** + * The user's email. + */ + email?: string; + /** + * The user's phone. + */ + phone?: string; + /** + * The user's password. + */ + password?: string; + /** + * The nonce sent for reauthentication if the user's password is to be updated. + * + * Call reauthenticate() to obtain the nonce first. + */ + nonce?: string; + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.raw_user_meta_data` column. + * + * The `data` should be a JSON object that includes user-specific info, such as their first and last name. + * + */ + data?: object; +} +export interface AdminUserAttributes extends Omit { + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.raw_user_meta_data` column. + * + * + * The `user_metadata` should be a JSON object that includes user-specific info, such as their first and last name. + * + * Note: When using the GoTrueAdminApi and wanting to modify a user's metadata, + * this attribute is used instead of UserAttributes data. + * + */ + user_metadata?: object; + /** + * A custom data object to store the user's application specific metadata. This maps to the `auth.users.app_metadata` column. + * + * Only a service role can modify. + * + * The `app_metadata` should be a JSON object that includes app-specific info, such as identity providers, roles, and other + * access control information. + */ + app_metadata?: object; + /** + * Confirms the user's email address if set to true. + * + * Only a service role can modify. + */ + email_confirm?: boolean; + /** + * Confirms the user's phone number if set to true. + * + * Only a service role can modify. + */ + phone_confirm?: boolean; + /** + * Determines how long a user is banned for. + * + * The format for the ban duration follows a strict sequence of decimal numbers with a unit suffix. + * Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h". + * + * For example, some possible durations include: '300ms', '2h45m'. + * + * Setting the ban duration to 'none' lifts the ban on the user. + */ + ban_duration?: string | 'none'; + /** + * The `role` claim set in the user's access token JWT. + * + * When a user signs up, this role is set to `authenticated` by default. You should only modify the `role` if you need to provision several levels of admin access that have different permissions on individual columns in your database. + * + * Setting this role to `service_role` is not recommended as it grants the user admin privileges. + */ + role?: string; + /** + * The `password_hash` for the user's password. + * + * Allows you to specify a password hash for the user. This is useful for migrating a user's password hash from another service. + * + * Supports bcrypt, scrypt (firebase), and argon2 password hashes. + */ + password_hash?: string; + /** + * The `id` for the user. + * + * Allows you to overwrite the default `id` set for the user. + */ + id?: string; +} +export interface Subscription { + /** + * A unique identifier for this subscription, set by the client. + * This is an internal identifier used for managing callbacks and should not be + * relied upon by application code. Use the unsubscribe() method to remove listeners. + */ + id: string | symbol; + /** + * The function to call every time there is an event. eg: (eventName) => {} + */ + callback: (event: AuthChangeEvent, session: Session | null) => void; + /** + * Call this to remove the listener. + */ + unsubscribe: () => void; +} +export type SignInAnonymouslyCredentials = { + options?: { + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.raw_user_meta_data` column. + * + * The `data` should be a JSON object that includes user-specific info, such as their first and last name. + */ + data?: object; + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + }; +}; +export type SignUpWithPasswordCredentials = Prettify; +type PasswordCredentialsBase = { + email: string; + password: string; +} | { + phone: string; + password: string; +}; +export type SignInWithPasswordCredentials = PasswordCredentialsBase & { + options?: { + captchaToken?: string; + }; +}; +export type SignInWithPasswordlessCredentials = { + /** The user's email address. */ + email: string; + options?: { + /** The redirect url embedded in the email link */ + emailRedirectTo?: string; + /** If set to false, this method will not create a new user. Defaults to true. */ + shouldCreateUser?: boolean; + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.raw_user_meta_data` column. + * + * The `data` should be a JSON object that includes user-specific info, such as their first and last name. + */ + data?: object; + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + }; +} | { + /** The user's phone number. */ + phone: string; + options?: { + /** If set to false, this method will not create a new user. Defaults to true. */ + shouldCreateUser?: boolean; + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.raw_user_meta_data` column. + * + * The `data` should be a JSON object that includes user-specific info, such as their first and last name. + */ + data?: object; + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + /** Messaging channel to use (e.g. whatsapp or sms) */ + channel?: 'sms' | 'whatsapp'; + }; +}; +export type AuthFlowType = 'implicit' | 'pkce'; +export type SignInWithOAuthCredentials = { + /** One of the providers supported by GoTrue. */ + provider: Provider; + options?: { + /** A URL to send the user to after they are confirmed. */ + redirectTo?: string; + /** A space-separated list of scopes granted to the OAuth application. */ + scopes?: string; + /** An object of query params */ + queryParams?: { + [key: string]: string; + }; + /** If set to true does not immediately redirect the current browser context to visit the OAuth authorization page for the provider. */ + skipBrowserRedirect?: boolean; + }; +}; +export type SignInWithIdTokenCredentials = { + /** Provider name or OIDC `iss` value identifying which provider should be used to verify the provided token. Supported names: `google`, `apple`, `azure`, `facebook`, `kakao`, `keycloak` (deprecated). */ + provider: 'google' | 'apple' | 'azure' | 'facebook' | 'kakao' | (string & {}); + /** OIDC ID token issued by the specified provider. The `iss` claim in the ID token must match the supplied provider. Some ID tokens contain an `at_hash` which require that you provide an `access_token` value to be accepted properly. If the token contains a `nonce` claim you must supply the nonce used to obtain the ID token. */ + token: string; + /** If the ID token contains an `at_hash` claim, then the hash of this value is compared to the value in the ID token. */ + access_token?: string; + /** If the ID token contains a `nonce` claim, then the hash of this value is compared to the value in the ID token. */ + nonce?: string; + options?: { + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + }; +}; +export type SolanaWallet = { + signIn?: (...inputs: SolanaSignInInput[]) => Promise; + publicKey?: { + toBase58: () => string; + } | null; + signMessage?: (message: Uint8Array, encoding?: 'utf8' | string) => Promise | undefined; +}; +export type SolanaWeb3Credentials = { + chain: 'solana'; + /** Wallet interface to use. If not specified will default to `window.solana`. */ + wallet?: SolanaWallet; + /** Optional statement to include in the Sign in with Solana message. Must not include new line characters. Most wallets like Phantom **require specifying a statement!** */ + statement?: string; + options?: { + /** URL to use with the wallet interface. Some wallets do not allow signing a message for URLs different from the current page. */ + url?: string; + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + signInWithSolana?: Partial>; + }; +} | { + chain: 'solana'; + /** Sign in with Solana compatible message. Must include `Issued At`, `URI` and `Version`. */ + message: string; + /** Ed25519 signature of the message. */ + signature: Uint8Array; + options?: { + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + }; +}; +export type EthereumWallet = EIP1193Provider; +export type EthereumWeb3Credentials = { + chain: 'ethereum'; + /** Wallet interface to use. If not specified will default to `window.ethereum`. */ + wallet?: EthereumWallet; + /** Optional statement to include in the Sign in with Ethereum message. Must not include new line characters. Most wallets like Phantom **require specifying a statement!** */ + statement?: string; + options?: { + /** URL to use with the wallet interface. Some wallets do not allow signing a message for URLs different from the current page. */ + url?: string; + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + signInWithEthereum?: Partial>; + }; +} | { + chain: 'ethereum'; + /** Sign in with Ethereum compatible message. Must include `Issued At`, `URI` and `Version`. */ + message: string; + /** Ethereum curve (secp256k1) signature of the message. */ + signature: Hex; + options?: { + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + }; +}; +export type Web3Credentials = SolanaWeb3Credentials | EthereumWeb3Credentials; +export type VerifyOtpParams = VerifyMobileOtpParams | VerifyEmailOtpParams | VerifyTokenHashParams; +export interface VerifyMobileOtpParams { + /** The user's phone number. */ + phone: string; + /** The otp sent to the user's phone number. */ + token: string; + /** The user's verification type. */ + type: MobileOtpType; + options?: { + /** A URL to send the user to after they are confirmed. */ + redirectTo?: string; + /** + * Verification token received when the user completes the captcha on the site. + * + * @deprecated + */ + captchaToken?: string; + }; +} +export interface VerifyEmailOtpParams { + /** The user's email address. */ + email: string; + /** The otp sent to the user's email address. */ + token: string; + /** The user's verification type. */ + type: EmailOtpType; + options?: { + /** A URL to send the user to after they are confirmed. */ + redirectTo?: string; + /** Verification token received when the user completes the captcha on the site. + * + * @deprecated + */ + captchaToken?: string; + }; +} +export interface VerifyTokenHashParams { + /** The token hash used in an email link */ + token_hash: string; + /** The user's verification type. */ + type: EmailOtpType; +} +export type MobileOtpType = 'sms' | 'phone_change'; +export type EmailOtpType = 'signup' | 'invite' | 'magiclink' | 'recovery' | 'email_change' | 'email'; +export type ResendParams = { + type: Extract; + email: string; + options?: { + /** A URL to send the user to after they have signed-in. */ + emailRedirectTo?: string; + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + }; +} | { + type: Extract; + phone: string; + options?: { + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + }; +}; +export type SignInWithSSO = { + /** UUID of the SSO provider to invoke single-sign on to. */ + providerId: string; + options?: { + /** A URL to send the user to after they have signed-in. */ + redirectTo?: string; + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + /** + * If set to true, the redirect will not happen on the client side. + * This parameter is used when you wish to handle the redirect yourself. + * Defaults to false. + */ + skipBrowserRedirect?: boolean; + }; +} | { + /** Domain name of the organization for which to invoke single-sign on. */ + domain: string; + options?: { + /** A URL to send the user to after they have signed-in. */ + redirectTo?: string; + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + /** + * If set to true, the redirect will not happen on the client side. + * This parameter is used when you wish to handle the redirect yourself. + * Defaults to false. + */ + skipBrowserRedirect?: boolean; + }; +}; +export type GenerateSignupLinkParams = { + type: 'signup'; + email: string; + password: string; + options?: Pick; +}; +export type GenerateInviteOrMagiclinkParams = { + type: 'invite' | 'magiclink'; + /** The user's email */ + email: string; + options?: Pick; +}; +export type GenerateRecoveryLinkParams = { + type: 'recovery'; + /** The user's email */ + email: string; + options?: Pick; +}; +export type GenerateEmailChangeLinkParams = { + type: 'email_change_current' | 'email_change_new'; + /** The user's email */ + email: string; + /** + * The user's new email. Only required if type is 'email_change_current' or 'email_change_new'. + */ + newEmail: string; + options?: Pick; +}; +export interface GenerateLinkOptions { + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.raw_user_meta_data` column. + * + * The `data` should be a JSON object that includes user-specific info, such as their first and last name. + */ + data?: object; + /** The URL which will be appended to the email link generated. */ + redirectTo?: string; +} +export type GenerateLinkParams = GenerateSignupLinkParams | GenerateInviteOrMagiclinkParams | GenerateRecoveryLinkParams | GenerateEmailChangeLinkParams; +export type GenerateLinkResponse = RequestResultSafeDestructure<{ + properties: GenerateLinkProperties; + user: User; +}>; +/** The properties related to the email link generated */ +export type GenerateLinkProperties = { + /** + * The email link to send to the user. + * The action_link follows the following format: auth/v1/verify?type={verification_type}&token={hashed_token}&redirect_to={redirect_to} + * */ + action_link: string; + /** + * The raw email OTP. + * You should send this in the email if you want your users to verify using an OTP instead of the action link. + * */ + email_otp: string; + /** + * The hashed token appended to the action link. + * */ + hashed_token: string; + /** The URL appended to the action link. */ + redirect_to: string; + /** The verification type that the email link is associated to. */ + verification_type: GenerateLinkType; +}; +export type GenerateLinkType = 'signup' | 'invite' | 'magiclink' | 'recovery' | 'email_change_current' | 'email_change_new'; +export type MFAEnrollParams = MFAEnrollTOTPParams | MFAEnrollPhoneParams | MFAEnrollWebauthnParams; +export type MFAUnenrollParams = { + /** ID of the factor being unenrolled. */ + factorId: string; +}; +type MFAVerifyParamsBase = { + /** ID of the factor being verified. Returned in enroll(). */ + factorId: string; + /** ID of the challenge being verified. Returned in challenge(). */ + challengeId: string; +}; +type MFAVerifyTOTPParamFields = { + /** Verification code provided by the user. */ + code: string; +}; +export type MFAVerifyTOTPParams = Prettify; +type MFAVerifyPhoneParamFields = MFAVerifyTOTPParamFields; +export type MFAVerifyPhoneParams = Prettify; +type MFAVerifyWebauthnParamFieldsBase = { + /** Relying party ID */ + rpId: string; + /** Relying party origins */ + rpOrigins?: string[]; +}; +type MFAVerifyWebauthnCredentialParamFields = { + /** Operation type */ + type: T; + /** Creation response from the authenticator (for enrollment/unverified factors) */ + credential_response: T extends 'create' ? RegistrationCredential : AuthenticationCredential; +}; +/** + * WebAuthn-specific fields for MFA verification. + * Supports both credential creation (registration) and request (authentication) flows. + * @template T - Type of WebAuthn operation: 'create' for registration, 'request' for authentication + */ +export type MFAVerifyWebauthnParamFields = { + webauthn: MFAVerifyWebauthnParamFieldsBase & MFAVerifyWebauthnCredentialParamFields; +}; +/** + * Parameters for WebAuthn MFA verification. + * Used to verify WebAuthn credentials after challenge. + * @template T - Type of WebAuthn operation: 'create' for registration, 'request' for authentication + * @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying an Authentication Assertion} + */ +export type MFAVerifyWebauthnParams = Prettify>; +export type MFAVerifyParams = MFAVerifyTOTPParams | MFAVerifyPhoneParams | MFAVerifyWebauthnParams; +type MFAChallengeParamsBase = { + /** ID of the factor to be challenged. Returned in enroll(). */ + factorId: string; +}; +declare const MFATOTPChannels: readonly ["sms", "whatsapp"]; +export type MFATOTPChannel = (typeof MFATOTPChannels)[number]; +export type MFAChallengeTOTPParams = Prettify; +type MFAChallengePhoneParamFields = { + /** Messaging channel to use (e.g. whatsapp or sms). Only relevant for phone factors */ + channel: Channel; +}; +export type MFAChallengePhoneParams = Prettify; +/** WebAuthn parameters for WebAuthn factor challenge */ +type MFAChallengeWebauthnParamFields = { + webauthn: { + /** Relying party ID */ + rpId: string; + /** Relying party origins*/ + rpOrigins?: string[]; + }; +}; +/** + * Parameters for initiating a WebAuthn MFA challenge. + * Includes Relying Party information needed for WebAuthn ceremonies. + * @see {@link https://w3c.github.io/webauthn/#sctn-rp-operations W3C WebAuthn Spec - Relying Party Operations} + */ +export type MFAChallengeWebauthnParams = Prettify; +export type MFAChallengeParams = MFAChallengeTOTPParams | MFAChallengePhoneParams | MFAChallengeWebauthnParams; +type MFAChallengeAndVerifyParamsBase = Omit; +type MFAChallengeAndVerifyTOTPParamFields = MFAVerifyTOTPParamFields; +type MFAChallengeAndVerifyTOTPParams = Prettify; +export type MFAChallengeAndVerifyParams = MFAChallengeAndVerifyTOTPParams; +/** + * Data returned after successful MFA verification. + * Contains new session tokens and updated user information. + */ +export type AuthMFAVerifyResponseData = { + /** New access token (JWT) after successful verification. */ + access_token: string; + /** Type of token, always `bearer`. */ + token_type: 'bearer'; + /** Number of seconds in which the access token will expire. */ + expires_in: number; + /** Refresh token you can use to obtain new access tokens when expired. */ + refresh_token: string; + /** Updated user profile. */ + user: User; +}; +/** + * Response type for MFA verification operations. + * Returns session tokens on successful verification. + */ +export type AuthMFAVerifyResponse = RequestResult; +export type AuthMFAEnrollResponse = AuthMFAEnrollTOTPResponse | AuthMFAEnrollPhoneResponse | AuthMFAEnrollWebauthnResponse; +export type AuthMFAUnenrollResponse = RequestResult<{ + /** ID of the factor that was successfully unenrolled. */ + id: string; +}>; +type AuthMFAChallengeResponseBase = { + /** ID of the newly created challenge. */ + id: string; + /** Factor Type which generated the challenge */ + type: T; + /** Timestamp in UNIX seconds when this challenge will no longer be usable. */ + expires_at: number; +}; +type AuthMFAChallengeTOTPResponseFields = {}; +export type AuthMFAChallengeTOTPResponse = RequestResult & AuthMFAChallengeTOTPResponseFields>>; +type AuthMFAChallengePhoneResponseFields = {}; +export type AuthMFAChallengePhoneResponse = RequestResult & AuthMFAChallengePhoneResponseFields>>; +type AuthMFAChallengeWebauthnResponseFields = { + webauthn: { + type: 'create'; + credential_options: { + publicKey: PublicKeyCredentialCreationOptionsFuture; + }; + } | { + type: 'request'; + credential_options: { + publicKey: PublicKeyCredentialRequestOptionsFuture; + }; + }; +}; +/** + * Response type for WebAuthn MFA challenge. + * Contains credential creation or request options from the server. + * @see {@link https://w3c.github.io/webauthn/#sctn-credential-creation W3C WebAuthn Spec - Credential Creation} + */ +export type AuthMFAChallengeWebauthnResponse = RequestResult & AuthMFAChallengeWebauthnResponseFields>>; +type AuthMFAChallengeWebauthnResponseFieldsJSON = { + webauthn: { + type: 'create'; + credential_options: { + publicKey: ServerCredentialCreationOptions; + }; + } | { + type: 'request'; + credential_options: { + publicKey: ServerCredentialRequestOptions; + }; + }; +}; +/** + * JSON-serializable version of WebAuthn challenge response. + * Used for server communication with base64url-encoded binary fields. + */ +export type AuthMFAChallengeWebauthnResponseDataJSON = Prettify & AuthMFAChallengeWebauthnResponseFieldsJSON>; +/** + * Server response type for WebAuthn MFA challenge. + * Contains JSON-formatted WebAuthn options ready for browser API. + */ +export type AuthMFAChallengeWebauthnServerResponse = RequestResult; +export type AuthMFAChallengeResponse = AuthMFAChallengeTOTPResponse | AuthMFAChallengePhoneResponse | AuthMFAChallengeWebauthnResponse; +/** response of ListFactors, which should contain all the types of factors that are available, this ensures we always include all */ +export type AuthMFAListFactorsResponse = RequestResult<{ + /** All available factors (verified and unverified). */ + all: Prettify[]; +} & { + [K in T[number]]: Prettify>[]; +}>; +export type AuthenticatorAssuranceLevels = 'aal1' | 'aal2'; +export type AuthMFAGetAuthenticatorAssuranceLevelResponse = RequestResult<{ + /** Current AAL level of the session. */ + currentLevel: AuthenticatorAssuranceLevels | null; + /** + * Next possible AAL level for the session. If the next level is higher + * than the current one, the user should go through MFA. + * + * @see {@link GoTrueMFAApi#challenge} + */ + nextLevel: AuthenticatorAssuranceLevels | null; + /** + * A list of all authentication methods attached to this session. Use + * the information here to detect the last time a user verified a + * factor, for example if implementing a step-up scenario. + */ + currentAuthenticationMethods: AMREntry[]; +}>; +/** + * Contains the full multi-factor authentication API. + * + */ +export interface GoTrueMFAApi { + /** + * Starts the enrollment process for a new Multi-Factor Authentication (MFA) + * factor. This method creates a new `unverified` factor. + * To verify a factor, present the QR code or secret to the user and ask them to add it to their + * authenticator app. + * The user has to enter the code from their authenticator app to verify it. + * + * Upon verifying a factor, all other sessions are logged out and the current session's authenticator level is promoted to `aal2`. + */ + enroll(params: MFAEnrollTOTPParams): Promise; + enroll(params: MFAEnrollPhoneParams): Promise; + enroll(params: MFAEnrollWebauthnParams): Promise; + enroll(params: MFAEnrollParams): Promise; + /** + * Prepares a challenge used to verify that a user has access to a MFA + * factor. + */ + challenge(params: MFAChallengeTOTPParams): Promise>; + challenge(params: MFAChallengePhoneParams): Promise>; + challenge(params: MFAChallengeWebauthnParams): Promise>; + challenge(params: MFAChallengeParams): Promise; + /** + * Verifies a code against a challenge. The verification code is + * provided by the user by entering a code seen in their authenticator app. + */ + verify(params: MFAVerifyTOTPParams): Promise; + verify(params: MFAVerifyPhoneParams): Promise; + verify(params: MFAVerifyWebauthnParams): Promise; + verify(params: MFAVerifyParams): Promise; + /** + * Unenroll removes a MFA factor. + * A user has to have an `aal2` authenticator level in order to unenroll a `verified` factor. + */ + unenroll(params: MFAUnenrollParams): Promise; + /** + * Helper method which creates a challenge and immediately uses the given code to verify against it thereafter. The verification code is + * provided by the user by entering a code seen in their authenticator app. + */ + challengeAndVerify(params: MFAChallengeAndVerifyParams): Promise; + /** + * Returns the list of MFA factors enabled for this user. + * + * @see {@link GoTrueMFAApi#enroll} + * @see {@link GoTrueMFAApi#getAuthenticatorAssuranceLevel} + * @see {@link GoTrueClient#getUser} + * + */ + listFactors(): Promise; + /** + * Returns the Authenticator Assurance Level (AAL) for the active session. + * + * - `aal1` (or `null`) means that the user's identity has been verified only + * with a conventional login (email+password, OTP, magic link, social login, + * etc.). + * - `aal2` means that the user's identity has been verified both with a conventional login and at least one MFA factor. + * + * Although this method returns a promise, it's fairly quick (microseconds) + * and rarely uses the network. You can use this to check whether the current + * user needs to be shown a screen to verify their MFA factors. + * + */ + getAuthenticatorAssuranceLevel(): Promise; + webauthn: WebAuthnApi; +} +/** + * @expermental + */ +export type AuthMFAAdminDeleteFactorResponse = RequestResult<{ + /** ID of the factor that was successfully deleted. */ + id: string; +}>; +/** + * @expermental + */ +export type AuthMFAAdminDeleteFactorParams = { + /** ID of the MFA factor to delete. */ + id: string; + /** ID of the user whose factor is being deleted. */ + userId: string; +}; +/** + * @expermental + */ +export type AuthMFAAdminListFactorsResponse = RequestResult<{ + /** All factors attached to the user. */ + factors: Factor[]; +}>; +/** + * @expermental + */ +export type AuthMFAAdminListFactorsParams = { + /** ID of the user. */ + userId: string; +}; +/** + * Contains the full multi-factor authentication administration API. + * + * @expermental + */ +export interface GoTrueAdminMFAApi { + /** + * Lists all factors associated to a user. + * + */ + listFactors(params: AuthMFAAdminListFactorsParams): Promise; + /** + * Deletes a factor on a user. This will log the user out of all active + * sessions if the deleted factor was verified. + * + * @see {@link GoTrueMFAApi#unenroll} + * + * @expermental + */ + deleteFactor(params: AuthMFAAdminDeleteFactorParams): Promise; +} +type AnyFunction = (...args: any[]) => any; +type MaybePromisify = T | Promise; +type PromisifyMethods = { + [K in keyof T]: T[K] extends AnyFunction ? (...args: Parameters) => MaybePromisify> : T[K]; +}; +export type SupportedStorage = PromisifyMethods> & { + /** + * If set to `true` signals to the library that the storage medium is used + * on a server and the values may not be authentic, such as reading from + * request cookies. Implementations should not set this to true if the client + * is used on a server that reads storage information from authenticated + * sources, such as a secure database or file. + */ + isServer?: boolean; +}; +export type InitializeResult = { + error: AuthError | null; +}; +export type CallRefreshTokenResult = RequestResult; +export type Pagination = { + [key: string]: any; + nextPage: number | null; + lastPage: number; + total: number; +}; +export type PageParams = { + /** The page number */ + page?: number; + /** Number of items returned per page */ + perPage?: number; +}; +export type SignOut = { + /** + * Determines which sessions should be + * logged out. Global means all + * sessions by this account. Local + * means only this session. Others + * means all other sessions except the + * current one. When using others, + * there is no sign-out event fired on + * the current session! + */ + scope?: 'global' | 'local' | 'others'; +}; +type MFAEnrollParamsBase = { + /** The type of factor being enrolled. */ + factorType: T; + /** Human readable name assigned to the factor. */ + friendlyName?: string; +}; +type MFAEnrollTOTPParamFields = { + /** Domain which the user is enrolled with. */ + issuer?: string; +}; +export type MFAEnrollTOTPParams = Prettify & MFAEnrollTOTPParamFields>; +type MFAEnrollPhoneParamFields = { + /** Phone number associated with a factor. Number should conform to E.164 format */ + phone: string; +}; +export type MFAEnrollPhoneParams = Prettify & MFAEnrollPhoneParamFields>; +type MFAEnrollWebauthnFields = {}; +/** + * Parameters for enrolling a WebAuthn factor. + * Creates an unverified WebAuthn factor that must be verified with a credential. + * @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registering a New Credential} + */ +export type MFAEnrollWebauthnParams = Prettify & MFAEnrollWebauthnFields>; +type AuthMFAEnrollResponseBase = { + /** ID of the factor that was just enrolled (in an unverified state). */ + id: string; + /** Type of MFA factor.*/ + type: T; + /** Friendly name of the factor, useful for distinguishing between factors **/ + friendly_name?: string; +}; +type AuthMFAEnrollTOTPResponseFields = { + /** TOTP enrollment information. */ + totp: { + /** Contains a QR code encoding the authenticator URI. You can + * convert it to a URL by prepending `data:image/svg+xml;utf-8,` to + * the value. Avoid logging this value to the console. */ + qr_code: string; + /** The TOTP secret (also encoded in the QR code). Show this secret + * in a password-style field to the user, in case they are unable to + * scan the QR code. Avoid logging this value to the console. */ + secret: string; + /** The authenticator URI encoded within the QR code, should you need + * to use it. Avoid loggin this value to the console. */ + uri: string; + }; +}; +export type AuthMFAEnrollTOTPResponse = RequestResult & AuthMFAEnrollTOTPResponseFields>>; +type AuthMFAEnrollPhoneResponseFields = { + /** Phone number of the MFA factor in E.164 format. Used to send messages */ + phone: string; +}; +export type AuthMFAEnrollPhoneResponse = RequestResult & AuthMFAEnrollPhoneResponseFields>>; +type AuthMFAEnrollWebauthnFields = {}; +/** + * Response type for WebAuthn factor enrollment. + * Returns the enrolled factor ID and metadata. + * @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registering a New Credential} + */ +export type AuthMFAEnrollWebauthnResponse = RequestResult & AuthMFAEnrollWebauthnFields>>; +export type JwtHeader = { + alg: 'RS256' | 'ES256' | 'HS256'; + kid: string; + typ: string; +}; +export type RequiredClaims = { + iss: string; + sub: string; + aud: string | string[]; + exp: number; + iat: number; + role: string; + aal: AuthenticatorAssuranceLevels; + session_id: string; +}; +/** + * JWT Payload containing claims for Supabase authentication tokens. + * + * Required claims (iss, aud, exp, iat, sub, role, aal, session_id) are inherited from RequiredClaims. + * All other claims are optional as they can be customized via Custom Access Token Hooks. + * + * @see https://supabase.com/docs/guides/auth/jwt-fields + */ +export interface JwtPayload extends RequiredClaims { + email?: string; + phone?: string; + is_anonymous?: boolean; + jti?: string; + nbf?: number; + app_metadata?: UserAppMetadata; + user_metadata?: UserMetadata; + amr?: AMREntry[]; + ref?: string; + [key: string]: any; +} +export interface JWK { + kty: 'RSA' | 'EC' | 'oct'; + key_ops: string[]; + alg?: string; + kid?: string; + [key: string]: any; +} +export declare const SIGN_OUT_SCOPES: readonly ["global", "local", "others"]; +export type SignOutScope = (typeof SIGN_OUT_SCOPES)[number]; +/** + * OAuth client grant types supported by the OAuth 2.1 server. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type OAuthClientGrantType = 'authorization_code' | 'refresh_token'; +/** + * OAuth client response types supported by the OAuth 2.1 server. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type OAuthClientResponseType = 'code'; +/** + * OAuth client type indicating whether the client can keep credentials confidential. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type OAuthClientType = 'public' | 'confidential'; +/** + * OAuth client registration type. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type OAuthClientRegistrationType = 'dynamic' | 'manual'; +/** + * OAuth client object returned from the OAuth 2.1 server. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type OAuthClient = { + /** Unique identifier for the OAuth client */ + client_id: string; + /** Human-readable name of the OAuth client */ + client_name: string; + /** Client secret (only returned on registration and regeneration) */ + client_secret?: string; + /** Type of OAuth client */ + client_type: OAuthClientType; + /** Token endpoint authentication method */ + token_endpoint_auth_method: string; + /** Registration type of the client */ + registration_type: OAuthClientRegistrationType; + /** URI of the OAuth client */ + client_uri?: string; + /** URI of the OAuth client's logo */ + logo_uri?: string; + /** Array of allowed redirect URIs */ + redirect_uris: string[]; + /** Array of allowed grant types */ + grant_types: OAuthClientGrantType[]; + /** Array of allowed response types */ + response_types: OAuthClientResponseType[]; + /** Scope of the OAuth client */ + scope?: string; + /** Timestamp when the client was created */ + created_at: string; + /** Timestamp when the client was last updated */ + updated_at: string; +}; +/** + * Parameters for creating a new OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type CreateOAuthClientParams = { + /** Human-readable name of the OAuth client */ + client_name: string; + /** URI of the OAuth client */ + client_uri?: string; + /** Array of allowed redirect URIs */ + redirect_uris: string[]; + /** Array of allowed grant types (optional, defaults to authorization_code and refresh_token) */ + grant_types?: OAuthClientGrantType[]; + /** Array of allowed response types (optional, defaults to code) */ + response_types?: OAuthClientResponseType[]; + /** Scope of the OAuth client */ + scope?: string; +}; +/** + * Parameters for updating an existing OAuth client. + * All fields are optional. Only provided fields will be updated. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type UpdateOAuthClientParams = { + /** Human-readable name of the OAuth client */ + client_name?: string; + /** URI of the OAuth client */ + client_uri?: string; + /** URI of the OAuth client's logo */ + logo_uri?: string; + /** Array of allowed redirect URIs */ + redirect_uris?: string[]; + /** Array of allowed grant types */ + grant_types?: OAuthClientGrantType[]; +}; +/** + * Response type for OAuth client operations. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type OAuthClientResponse = RequestResult; +/** + * Response type for listing OAuth clients. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type OAuthClientListResponse = { + data: { + clients: OAuthClient[]; + aud: string; + } & Pagination; + error: null; +} | { + data: { + clients: []; + }; + error: AuthError; +}; +/** + * Contains all OAuth client administration methods. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export interface GoTrueAdminOAuthApi { + /** + * Lists all OAuth clients with optional pagination. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + listClients(params?: PageParams): Promise; + /** + * Creates a new OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + createClient(params: CreateOAuthClientParams): Promise; + /** + * Gets details of a specific OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + getClient(clientId: string): Promise; + /** + * Updates an existing OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + updateClient(clientId: string, params: UpdateOAuthClientParams): Promise; + /** + * Deletes an OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + deleteClient(clientId: string): Promise<{ + data: null; + error: AuthError | null; + }>; + /** + * Regenerates the secret for an OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + regenerateClientSecret(clientId: string): Promise; +} +/** + * OAuth client details in an authorization request. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type OAuthAuthorizationClient = { + /** Unique identifier for the OAuth client (UUID) */ + id: string; + /** Human-readable name of the OAuth client */ + name: string; + /** URI of the OAuth client's website */ + uri: string; + /** URI of the OAuth client's logo */ + logo_uri: string; +}; +/** + * OAuth authorization details for the consent flow. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type OAuthAuthorizationDetails = { + /** The authorization ID */ + authorization_id: string; + /** Redirect URL - present if user already consented (can be used to trigger immediate redirect) */ + redirect_url?: string; + /** OAuth client requesting authorization */ + client: OAuthAuthorizationClient; + /** User object associated with the authorization */ + user: { + /** User ID (UUID) */ + id: string; + /** User email */ + email: string; + }; + /** Space-separated list of requested scopes */ + scope: string; +}; +/** + * Response type for getting OAuth authorization details. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type AuthOAuthAuthorizationDetailsResponse = RequestResult; +/** + * Response type for OAuth consent decision (approve/deny). + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type AuthOAuthConsentResponse = RequestResult<{ + /** URL to redirect the user back to the OAuth client */ + redirect_url: string; +}>; +/** + * An OAuth grant representing a user's authorization of an OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type OAuthGrant = { + /** OAuth client information */ + client: OAuthAuthorizationClient; + /** Array of scopes granted to this client */ + scopes: string[]; + /** Timestamp when the grant was created (ISO 8601 date-time) */ + granted_at: string; +}; +/** + * Response type for listing user's OAuth grants. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type AuthOAuthGrantsResponse = RequestResult; +/** + * Response type for revoking an OAuth grant. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type AuthOAuthRevokeGrantResponse = RequestResult<{}>; +/** + * Contains all OAuth 2.1 authorization server user-facing methods. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * These methods are used to implement the consent page. + */ +export interface AuthOAuthServerApi { + /** + * Retrieves details about an OAuth authorization request. + * Used to display consent information to the user. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This method returns authorization details including client info, scopes, and user information. + * If the response includes a redirect_uri, it means consent was already given - the caller + * should handle the redirect manually if needed. + * + * @param authorizationId - The authorization ID from the authorization request + * @returns Authorization details including client info and requested scopes + */ + getAuthorizationDetails(authorizationId: string): Promise; + /** + * Approves an OAuth authorization request. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * @param authorizationId - The authorization ID to approve + * @param options - Optional parameters including skipBrowserRedirect + * @returns Redirect URL to send the user back to the OAuth client + */ + approveAuthorization(authorizationId: string, options?: { + skipBrowserRedirect?: boolean; + }): Promise; + /** + * Denies an OAuth authorization request. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * @param authorizationId - The authorization ID to deny + * @param options - Optional parameters including skipBrowserRedirect + * @returns Redirect URL to send the user back to the OAuth client + */ + denyAuthorization(authorizationId: string, options?: { + skipBrowserRedirect?: boolean; + }): Promise; + /** + * Lists all OAuth grants that the authenticated user has authorized. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * @returns Response with array of OAuth grants with client information and granted scopes + */ + listGrants(): Promise; + /** + * Revokes a user's OAuth grant for a specific client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * Revocation marks consent as revoked, deletes active sessions for that OAuth client, + * and invalidates associated refresh tokens. + * + * @param options - Revocation options + * @param options.clientId - The OAuth client identifier (UUID) to revoke access for + * @returns Empty response on successful revocation + */ + revokeGrant(options: { + clientId: string; + }): Promise; +} +export {}; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/types.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/main/lib/types.d.ts.map new file mode 100644 index 0000000..ba89c28 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/lib/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAA;AACpC,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAC/B,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAA;AAC3E,OAAO,KAAK,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAA;AAC1E,OAAO,EACL,+BAA+B,EAC/B,8BAA8B,EAC9B,WAAW,EACZ,MAAM,YAAY,CAAA;AACnB,OAAO,EACL,wBAAwB,EACxB,wCAAwC,EACxC,uCAAuC,EACvC,sBAAsB,EACvB,MAAM,gBAAgB,C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AqC,CAAC,CAAA;IAEhG;;;;;;;OAOG;IACH,oBAAoB,CAClB,eAAe,EAAE,MAAM,EACvB,OAAO,CAAC,EAAE;QAAE,mBAAmB,CAAC,EAAE,OAAO,CAAA;KAAE,GAC1C,OAAO,CAAC,wBAAwB,CAAC,CAAA;IAEpC;;;;;;;OAOG;IACH,iBAAiB,CACf,eAAe,EAAE,MAAM,EACvB,OAAO,CAAC,EAAE;QAAE,mBAAmB,CAAC,EAAE,OAAO,CAAA;KAAE,GAC1C,OAAO,CAAC,wBAAwB,CAAC,CAAA;IAEpC;;;;;OAKG;IACH,UAAU,IAAI,OAAO,CAAC,uBAAuB,CAAC,CAAA;IAE9C;;;;;;;;;;OAUG;IACH,WAAW,CAAC,OAAO,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,4BAA4B,CAAC,CAAA;CAClF"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/types.js b/backend/node_modules/@supabase/auth-js/dist/main/lib/types.js new file mode 100644 index 0000000..c48f360 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/types.js @@ -0,0 +1,22 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SIGN_OUT_SCOPES = void 0; +const WeakPasswordReasons = ['length', 'characters', 'pwned']; +const AMRMethods = [ + 'password', + 'otp', + 'oauth', + 'totp', + 'mfa/totp', + 'mfa/phone', + 'mfa/webauthn', + 'anonymous', + 'sso/saml', + 'magiclink', + 'web3', +]; +const FactorTypes = ['totp', 'phone', 'webauthn']; +const FactorVerificationStatuses = ['verified', 'unverified']; +const MFATOTPChannels = ['sms', 'whatsapp']; +exports.SIGN_OUT_SCOPES = ['global', 'local', 'others']; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/types.js.map b/backend/node_modules/@supabase/auth-js/dist/main/lib/types.js.map new file mode 100644 index 0000000..401c59a --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/lib/types.ts"],"names":[],"mappings":";;;AAoHA,MAAM,mBAAmB,GAAG,CAAC,QAAQ,EAAE,YAAY,EAAE,OAAO,CAAU,CAAA;AA+ItE,MAAM,UAAU,GAAG;IACjB,UAAU;IACV,KAAK;IACL,OAAO;IACP,MAAM;IACN,UAAU;IACV,WAAW;IACX,cAAc;IACd,WAAW;IACX,UAAU;IACV,WAAW;IACX,MAAM;CACE,CAAA;AAoCV,MAAM,WAAW,GAAG,CAAC,MAAM,EAAE,OAAO,EAAE,UAAU,CAAU,CAAA;AAO1D,MAAM,0BAA0B,GAAG,CAAC,UAAU,EAAE,YAAY,CAAU,CAAA;AA2oBtE,MAAM,eAAe,GAAG,CAAC,KAAK,EAAE,UAAU,CAAU,CAAA;AAqhBvC,QAAA,eAAe,GAAG,CAAC,QAAQ,EAAE,OAAO,EAAE,QAAQ,CAAU,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/version.d.ts b/backend/node_modules/@supabase/auth-js/dist/main/lib/version.d.ts new file mode 100644 index 0000000..da11aac --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/version.d.ts @@ -0,0 +1,2 @@ +export declare const version = "2.87.1"; +//# sourceMappingURL=version.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/version.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/main/lib/version.d.ts.map new file mode 100644 index 0000000..a4c2b72 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/version.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,OAAO,WAAW,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/version.js b/backend/node_modules/@supabase/auth-js/dist/main/lib/version.js new file mode 100644 index 0000000..31bcb0a --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/version.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.version = void 0; +// Generated automatically during releases by scripts/update-version-files.ts +// This file provides runtime access to the package version for: +// - HTTP request headers (e.g., X-Client-Info header for API requests) +// - Debugging and support (identifying which version is running) +// - Telemetry and logging (version reporting in errors/analytics) +// - Ensuring build artifacts match the published package version +exports.version = '2.87.1'; +//# sourceMappingURL=version.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/version.js.map b/backend/node_modules/@supabase/auth-js/dist/main/lib/version.js.map new file mode 100644 index 0000000..e9f984c --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/version.js.map @@ -0,0 +1 @@ +{"version":3,"file":"version.js","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":";;;AAAA,6EAA6E;AAC7E,gEAAgE;AAChE,uEAAuE;AACvE,iEAAiE;AACjE,kEAAkE;AAClE,iEAAiE;AACpD,QAAA,OAAO,GAAG,QAAQ,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/web3/ethereum.d.ts b/backend/node_modules/@supabase/auth-js/dist/main/lib/web3/ethereum.d.ts new file mode 100644 index 0000000..71f4b6e --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/web3/ethereum.d.ts @@ -0,0 +1,96 @@ +export type Hex = `0x${string}`; +export type Address = Hex; +export type EIP1193EventMap = { + accountsChanged(accounts: Address[]): void; + chainChanged(chainId: string): void; + connect(connectInfo: { + chainId: string; + }): void; + disconnect(error: { + code: number; + message: string; + }): void; + message(message: { + type: string; + data: unknown; + }): void; +}; +export type EIP1193Events = { + on(event: event, listener: EIP1193EventMap[event]): void; + removeListener(event: event, listener: EIP1193EventMap[event]): void; +}; +export type EIP1193RequestFn = (args: { + method: string; + params?: unknown; +}) => Promise; +export type EIP1193Provider = EIP1193Events & { + address: string; + request: EIP1193RequestFn; +}; +export type EthereumWallet = EIP1193Provider; +/** + * EIP-4361 message fields + */ +export type SiweMessage = { + /** + * The Ethereum address performing the signing. + */ + address: Address; + /** + * The [EIP-155](https://eips.ethereum.org/EIPS/eip-155) Chain ID to which the session is bound, + */ + chainId: number; + /** + * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) authority that is requesting the signing. + */ + domain: string; + /** + * Time when the signed authentication message is no longer valid. + */ + expirationTime?: Date | undefined; + /** + * Time when the message was generated, typically the current time. + */ + issuedAt?: Date | undefined; + /** + * A random string typically chosen by the relying party and used to prevent replay attacks. + */ + nonce?: string; + /** + * Time when the signed authentication message will become valid. + */ + notBefore?: Date | undefined; + /** + * A system-specific identifier that may be used to uniquely refer to the sign-in request. + */ + requestId?: string | undefined; + /** + * A list of information or references to information the user wishes to have resolved as part of authentication by the relying party. + */ + resources?: string[] | undefined; + /** + * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) URI scheme of the origin of the request. + */ + scheme?: string | undefined; + /** + * A human-readable ASCII assertion that the user will sign. + */ + statement?: string | undefined; + /** + * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) URI referring to the resource that is the subject of the signing (as in the subject of a claim). + */ + uri: string; + /** + * The current version of the SIWE Message. + */ + version: '1'; +}; +export type EthereumSignInInput = SiweMessage; +export declare function getAddress(address: string): Address; +export declare function fromHex(hex: Hex): number; +export declare function toHex(value: string): Hex; +/** + * Creates EIP-4361 formatted message. + */ +export declare function createSiweMessage(parameters: SiweMessage): string; +//# sourceMappingURL=ethereum.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/web3/ethereum.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/main/lib/web3/ethereum.d.ts.map new file mode 100644 index 0000000..7b3ac39 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js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,OAAO,EAAE,gBAAgB,CAAA;CAC1B,CAAA;AAED,MAAM,MAAM,cAAc,GAAG,eAAe,CAAA;AAE5C;;GAEG;AACH,MAAM,MAAM,WAAW,GAAG;IACxB;;OAEG;IACH,OAAO,EAAE,OAAO,CAAA;IAChB;;OAEG;IACH,OAAO,EAAE,MAAM,CAAA;IACf;;OAEG;IACH,MAAM,EAAE,MAAM,CAAA;IACd;;OAEG;IACH,cAAc,CAAC,EAAE,IAAI,GAAG,SAAS,CAAA;IACjC;;OAEG;IACH,QAAQ,CAAC,EAAE,IAAI,GAAG,SAAS,CAAA;IAC3B;;OAEG;IACH,KAAK,CAAC,EAAE,MAAM,CAAA;IACd;;OAEG;IACH,SAAS,CAAC,EAAE,IAAI,GAAG,SAAS,CAAA;IAC5B;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IAC9B;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,EAAE,GAAG,SAAS,CAAA;IAChC;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IAC3B;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IAC9B;;OAEG;IACH,GAAG,EAAE,MAAM,CAAA;IACX;;OAEG;IACH,OAAO,EAAE,GAAG,CAAA;CACb,CAAA;AAED,MAAM,MAAM,mBAAmB,GAAG,WAAW,CAAA;AAE7C,wBAAgB,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAKnD;AAED,wBAAgB,OAAO,CAAC,GAAG,EAAE,GAAG,GAAG,MAAM,CAExC;AAED,wBAAgB,KAAK,CAAC,KAAK,EAAE,MAAM,GAAG,GAAG,CAIxC;AAED;;GAEG;AACH,wBAAgB,iBAAiB,CAAC,UAAU,EAAE,WAAW,GAAG,MAAM,CAwEjE"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/web3/ethereum.js b/backend/node_modules/@supabase/auth-js/dist/main/lib/web3/ethereum.js new file mode 100644 index 0000000..2e299a7 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/web3/ethereum.js @@ -0,0 +1,66 @@ +"use strict"; +// types and functions copied over from viem so this library doesn't depend on it +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getAddress = getAddress; +exports.fromHex = fromHex; +exports.toHex = toHex; +exports.createSiweMessage = createSiweMessage; +function getAddress(address) { + if (!/^0x[a-fA-F0-9]{40}$/.test(address)) { + throw new Error(`@supabase/auth-js: Address "${address}" is invalid.`); + } + return address.toLowerCase(); +} +function fromHex(hex) { + return parseInt(hex, 16); +} +function toHex(value) { + const bytes = new TextEncoder().encode(value); + const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join(''); + return ('0x' + hex); +} +/** + * Creates EIP-4361 formatted message. + */ +function createSiweMessage(parameters) { + var _a; + const { chainId, domain, expirationTime, issuedAt = new Date(), nonce, notBefore, requestId, resources, scheme, uri, version, } = parameters; + // Validate fields + { + if (!Number.isInteger(chainId)) + throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${chainId}`); + if (!domain) + throw new Error(`@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.`); + if (nonce && nonce.length < 8) + throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${nonce}`); + if (!uri) + throw new Error(`@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.`); + if (version !== '1') + throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${version}`); + if ((_a = parameters.statement) === null || _a === void 0 ? void 0 : _a.includes('\n')) + throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${parameters.statement}`); + } + // Construct message + const address = getAddress(parameters.address); + const origin = scheme ? `${scheme}://${domain}` : domain; + const statement = parameters.statement ? `${parameters.statement}\n` : ''; + const prefix = `${origin} wants you to sign in with your Ethereum account:\n${address}\n\n${statement}`; + let suffix = `URI: ${uri}\nVersion: ${version}\nChain ID: ${chainId}${nonce ? `\nNonce: ${nonce}` : ''}\nIssued At: ${issuedAt.toISOString()}`; + if (expirationTime) + suffix += `\nExpiration Time: ${expirationTime.toISOString()}`; + if (notBefore) + suffix += `\nNot Before: ${notBefore.toISOString()}`; + if (requestId) + suffix += `\nRequest ID: ${requestId}`; + if (resources) { + let content = '\nResources:'; + for (const resource of resources) { + if (!resource || typeof resource !== 'string') + throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${resource}`); + content += `\n- ${resource}`; + } + suffix += content; + } + return `${prefix}\n${suffix}`; +} +//# sourceMappingURL=ethereum.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/web3/ethereum.js.map b/backend/node_modules/@supabase/auth-js/dist/main/lib/web3/ethereum.js.map new file mode 100644 index 0000000..1a279ee --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/web3/ethereum.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ethereum.js","sourceRoot":"","sources":["../../../../src/lib/web3/ethereum.ts"],"names":[],"mappings":";AAAA,iFAAiF;;AA2FjF,gCAKC;AAED,0BAEC;AAED,sBAIC;AAKD,8CAwEC;AA5FD,SAAgB,UAAU,CAAC,OAAe;IACxC,IAAI,CAAC,qBAAqB,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;QACzC,MAAM,IAAI,KAAK,CAAC,+BAA+B,OAAO,eAAe,CAAC,CAAA;IACxE,CAAC;IACD,OAAO,OAAO,CAAC,WAAW,EAAa,CAAA;AACzC,CAAC;AAED,SAAgB,OAAO,CAAC,GAAQ;IAC9B,OAAO,QAAQ,CAAC,GAAG,EAAE,EAAE,CAAC,CAAA;AAC1B,CAAC;AAED,SAAgB,KAAK,CAAC,KAAa;IACjC,MAAM,KAAK,GAAG,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,K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ts new file mode 100644 index 0000000..1fa5b62 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/web3/solana.d.ts @@ -0,0 +1,160 @@ +/** + * A namespaced identifier in the format `${namespace}:${reference}`. + * + * Used by {@link IdentifierArray} and {@link IdentifierRecord}. + * + * @group Identifier + */ +export type IdentifierString = `${string}:${string}`; +/** + * A read-only array of namespaced identifiers in the format `${namespace}:${reference}`. + * + * Used by {@link Wallet.chains | Wallet::chains}, {@link WalletAccount.chains | WalletAccount::chains}, and + * {@link WalletAccount.features | WalletAccount::features}. + * + * @group Identifier + */ +export type IdentifierArray = readonly IdentifierString[]; +/** + * Version of the Wallet Standard implemented by a {@link Wallet}. + * + * Used by {@link Wallet.version | Wallet::version}. + * + * Note that this is _NOT_ a version of the Wallet, but a version of the Wallet Standard itself that the Wallet + * supports. + * + * This may be used by the app to determine compatibility and feature detect. + * + * @group Wallet + */ +export type WalletVersion = '1.0.0'; +/** + * A data URI containing a base64-encoded SVG, WebP, PNG, or GIF image. + * + * Used by {@link Wallet.icon | Wallet::icon} and {@link WalletAccount.icon | WalletAccount::icon}. + * + * @group Wallet + */ +export type WalletIcon = `data:image/${'svg+xml' | 'webp' | 'png' | 'gif'};base64,${string}`; +/** + * Interface of a **WalletAccount**, also referred to as an **Account**. + * + * An account is a _read-only data object_ that is provided from the Wallet to the app, authorizing the app to use it. + * + * The app can use an account to display and query information from a chain. + * + * The app can also act using an account by passing it to {@link Wallet.features | features} of the Wallet. + * + * Wallets may use or extend {@link "@wallet-standard/wallet".ReadonlyWalletAccount} which implements this interface. + * + * @group Wallet + */ +export interface WalletAccount { + /** Address of the account, corresponding with a public key. */ + readonly address: string; + /** Public key of the account, corresponding with a secret key to use. */ + readonly publicKey: Uint8Array; + /** + * Chains supported by the account. + * + * This must be a subset of the {@link Wallet.chains | chains} of the Wallet. + */ + readonly chains: IdentifierArray; + /** + * Feature names supported by the account. + * + * This must be a subset of the names of {@link Wallet.features | features} of the Wallet. + */ + readonly features: IdentifierArray; + /** Optional user-friendly descriptive label or name for the account. This may be displayed by the app. */ + readonly label?: string; + /** Optional user-friendly icon for the account. This may be displayed by the app. */ + readonly icon?: WalletIcon; +} +/** Input for signing in. */ +export interface SolanaSignInInput { + /** + * Optional EIP-4361 Domain. + * If not provided, the wallet must determine the Domain to include in the message. + */ + readonly domain?: string; + /** + * Optional EIP-4361 Address. + * If not provided, the wallet must determine the Address to include in the message. + */ + readonly address?: string; + /** + * Optional EIP-4361 Statement. + * If not provided, the wallet must not include Statement in the message. + */ + readonly statement?: string; + /** + * Optional EIP-4361 URI. + * If not provided, the wallet must not include URI in the message. + */ + readonly uri?: string; + /** + * Optional EIP-4361 Version. + * If not provided, the wallet must not include Version in the message. + */ + readonly version?: string; + /** + * Optional EIP-4361 Chain ID. + * If not provided, the wallet must not include Chain ID in the message. + */ + readonly chainId?: string; + /** + * Optional EIP-4361 Nonce. + * If not provided, the wallet must not include Nonce in the message. + */ + readonly nonce?: string; + /** + * Optional EIP-4361 Issued At. + * If not provided, the wallet must not include Issued At in the message. + */ + readonly issuedAt?: string; + /** + * Optional EIP-4361 Expiration Time. + * If not provided, the wallet must not include Expiration Time in the message. + */ + readonly expirationTime?: string; + /** + * Optional EIP-4361 Not Before. + * If not provided, the wallet must not include Not Before in the message. + */ + readonly notBefore?: string; + /** + * Optional EIP-4361 Request ID. + * If not provided, the wallet must not include Request ID in the message. + */ + readonly requestId?: string; + /** + * Optional EIP-4361 Resources. + * If not provided, the wallet must not include Resources in the message. + */ + readonly resources?: readonly string[]; +} +/** Output of signing in. */ +export interface SolanaSignInOutput { + /** + * Account that was signed in. + * The address of the account may be different from the provided input Address. + */ + readonly account: WalletAccount; + /** + * Message bytes that were signed. + * The wallet may prefix or otherwise modify the message before signing it. + */ + readonly signedMessage: Uint8Array; + /** + * Message signature produced. + * If the signature type is provided, the signature must be Ed25519. + */ + readonly signature: Uint8Array; + /** + * Optional type of the message signature produced. + * If not provided, the signature must be Ed25519. + */ + readonly signatureType?: 'ed25519'; +} +//# sourceMappingURL=solana.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/web3/solana.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/main/lib/web3/solana.d.ts.map new file mode 100644 index 0000000..447112c --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/web3/solana.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"solana.d.ts","sourceRoot":"","sources":["../../../../src/lib/web3/solana.ts"],"names":[],"mappings":"AAEA;;;;;;GAMG;AACH,MAAM,MAAM,gBAAgB,GAAG,GAAG,MAAM,IAAI,MAAM,EAAE,CAAA;AAEpD;;;;;;;GAOG;AACH,MAAM,MAAM,eAAe,GAAG,SAAS,gBAAgB,EAAE,CAAA;AAEzD;;;;;;;;;;;GAWG;AACH,MAAM,MAAM,aAAa,GAAG,OAAO,CAAA;AAEnC;;;;;;GAMG;AACH,MAAM,MAAM,UAAU,GAAG,cAAc,SAAS,GAAG,MAAM,GAAG,KAAK,GAAG,KAAK,WAAW,MAAM,EAAE,CAAA;AAE5F;;;;;;;;;;;;GAYG;AACH,MAAM,WAAW,aAAa;IAC5B,+DAA+D;IAC/D,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;IAExB,yEAAyE;IACzE,QAAQ,CAAC,SAAS,EAAE,UAAU,CAAA;IAE9B;;;;OAIG;IACH,QAAQ,CAAC,MAAM,EAAE,eAAe,CAAA;IAEhC;;;;OAIG;IACH,QAAQ,CAAC,QAAQ,EAAE,eAAe,CAAA;IAElC,0GAA0G;IAC1G,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAA;IAEvB,qFAAqF;IACrF,QAAQ,CAAC,IAAI,CAAC,EAAE,UAAU,CAAA;CAC3B;AAED,4BAA4B;AAC5B,MAAM,WAAW,iBAAiB;IAChC;;;OAGG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAA;IAExB;;;OAGG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAA;IAEzB;;;OAGG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAA;IAE3B;;;OAGG;IACH,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAA;IAErB;;;OAGG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAA;IAEzB;;;OAGG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAA;IAEzB;;;OAGG;IACH,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAA;IAEvB;;;OAGG;IACH,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;IAE1B;;;OAGG;IACH,QAAQ,CAAC,cAAc,CAAC,EAAE,MAAM,CAAA;IAEhC;;;OAGG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAA;IAE3B;;;OAGG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAA;IAE3B;;;OAGG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,SAAS,MAAM,EAAE,CAAA;CACvC;AAED,4BAA4B;AAC5B,MAAM,WAAW,kBAAkB;IACjC;;;OAGG;IACH,QAAQ,CAAC,OAAO,EAAE,aAAa,CAAA;IAE/B;;;OAGG;IACH,QAAQ,CAAC,aAAa,EAAE,UAAU,CAAA;IAElC;;;OAGG;IACH,QAAQ,CAAC,SAAS,EAAE,UAAU,CAAA;IAE9B;;;OAGG;IACH,QAAQ,CAAC,aAAa,CAAC,EAAE,SAAS,CAAA;CACnC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/web3/solana.js b/backend/node_modules/@supabase/auth-js/dist/main/lib/web3/solana.js new file mode 100644 index 0000000..c13c785 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/web3/solana.js @@ -0,0 +1,4 @@ +"use strict"; +// types copied over from @solana/wallet-standard-features and @wallet-standard/base so this library doesn't depend on them +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=solana.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/web3/solana.js.map b/backend/node_modules/@supabase/auth-js/dist/main/lib/web3/solana.js.map new file mode 100644 index 0000000..4e2a29a --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/web3/solana.js.map @@ -0,0 +1 @@ +{"version":3,"file":"solana.js","sourceRoot":"","sources":["../../../../src/lib/web3/solana.ts"],"names":[],"mappings":";AAAA,2HAA2H"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/webauthn.d.ts b/backend/node_modules/@supabase/auth-js/dist/main/lib/webauthn.d.ts new file mode 100644 index 0000000..a0fd0d8 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/webauthn.d.ts @@ -0,0 +1,276 @@ +import GoTrueClient from '../GoTrueClient'; +import { AuthError } from './errors'; +import { AuthMFAEnrollWebauthnResponse, AuthMFAVerifyResponse, AuthMFAVerifyResponseData, MFAChallengeWebauthnParams, MFAEnrollWebauthnParams, MFAVerifyWebauthnParamFields, MFAVerifyWebauthnParams, RequestResult, StrictOmit } from './types'; +import type { AuthenticationCredential, AuthenticationResponseJSON, PublicKeyCredentialCreationOptionsFuture, PublicKeyCredentialCreationOptionsJSON, PublicKeyCredentialRequestOptionsFuture, PublicKeyCredentialRequestOptionsJSON, RegistrationCredential, RegistrationResponseJSON } from './webauthn.dom'; +import { identifyAuthenticationError, identifyRegistrationError, isWebAuthnError, WebAuthnError } from './webauthn.errors'; +export { WebAuthnError, isWebAuthnError, identifyRegistrationError, identifyAuthenticationError }; +export type { RegistrationResponseJSON, AuthenticationResponseJSON }; +/** + * WebAuthn abort service to manage ceremony cancellation. + * Ensures only one WebAuthn ceremony is active at a time to prevent "operation already in progress" errors. + * + * @experimental This class is experimental and may change in future releases + * @see {@link https://w3c.github.io/webauthn/#sctn-automation-webdriver-capability W3C WebAuthn Spec - Aborting Ceremonies} + */ +export declare class WebAuthnAbortService { + private controller; + /** + * Create an abort signal for a new WebAuthn operation. + * Automatically cancels any existing operation. + * + * @returns {AbortSignal} Signal to pass to navigator.credentials.create() or .get() + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal MDN - AbortSignal} + */ + createNewAbortSignal(): AbortSignal; + /** + * Manually cancel the current WebAuthn operation. + * Useful for cleaning up when user cancels or navigates away. + * + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort MDN - AbortController.abort} + */ + cancelCeremony(): void; +} +/** + * Singleton instance to ensure only one WebAuthn ceremony is active at a time. + * This prevents "operation already in progress" errors when retrying WebAuthn operations. + * + * @experimental This instance is experimental and may change in future releases + */ +export declare const webAuthnAbortService: WebAuthnAbortService; +/** + * Server response format for WebAuthn credential creation options. + * Uses W3C standard JSON format with base64url-encoded binary fields. + */ +export type ServerCredentialCreationOptions = PublicKeyCredentialCreationOptionsJSON; +/** + * Server response format for WebAuthn credential request options. + * Uses W3C standard JSON format with base64url-encoded binary fields. + */ +export type ServerCredentialRequestOptions = PublicKeyCredentialRequestOptionsJSON; +/** + * Convert base64url encoded strings in WebAuthn credential creation options to ArrayBuffers + * as required by the WebAuthn browser API. + * Supports both native WebAuthn Level 3 parseCreationOptionsFromJSON and manual fallback. + * + * @param {ServerCredentialCreationOptions} options - JSON options from server with base64url encoded fields + * @returns {PublicKeyCredentialCreationOptionsFuture} Options ready for navigator.credentials.create() + * @see {@link https://w3c.github.io/webauthn/#sctn-parseCreationOptionsFromJSON W3C WebAuthn Spec - parseCreationOptionsFromJSON} + */ +export declare function deserializeCredentialCreationOptions(options: ServerCredentialCreationOptions): PublicKeyCredentialCreationOptionsFuture; +/** + * Convert base64url encoded strings in WebAuthn credential request options to ArrayBuffers + * as required by the WebAuthn browser API. + * Supports both native WebAuthn Level 3 parseRequestOptionsFromJSON and manual fallback. + * + * @param {ServerCredentialRequestOptions} options - JSON options from server with base64url encoded fields + * @returns {PublicKeyCredentialRequestOptionsFuture} Options ready for navigator.credentials.get() + * @see {@link https://w3c.github.io/webauthn/#sctn-parseRequestOptionsFromJSON W3C WebAuthn Spec - parseRequestOptionsFromJSON} + */ +export declare function deserializeCredentialRequestOptions(options: ServerCredentialRequestOptions): PublicKeyCredentialRequestOptionsFuture; +/** + * Server format for credential response with base64url-encoded binary fields + * Can be either a registration or authentication response + */ +export type ServerCredentialResponse = RegistrationResponseJSON | AuthenticationResponseJSON; +/** + * Convert a registration/enrollment credential response to server format. + * Serializes binary fields to base64url for JSON transmission. + * Supports both native WebAuthn Level 3 toJSON and manual fallback. + * + * @param {RegistrationCredential} credential - Credential from navigator.credentials.create() + * @returns {RegistrationResponseJSON} JSON-serializable credential for server + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-tojson W3C WebAuthn Spec - toJSON} + */ +export declare function serializeCredentialCreationResponse(credential: RegistrationCredential): RegistrationResponseJSON; +/** + * Convert an authentication/verification credential response to server format. + * Serializes binary fields to base64url for JSON transmission. + * Supports both native WebAuthn Level 3 toJSON and manual fallback. + * + * @param {AuthenticationCredential} credential - Credential from navigator.credentials.get() + * @returns {AuthenticationResponseJSON} JSON-serializable credential for server + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-tojson W3C WebAuthn Spec - toJSON} + */ +export declare function serializeCredentialRequestResponse(credential: AuthenticationCredential): AuthenticationResponseJSON; +/** + * A simple test to determine if a hostname is a properly-formatted domain name. + * Considers localhost valid for development environments. + * + * A "valid domain" is defined here: https://url.spec.whatwg.org/#valid-domain + * + * Regex sourced from here: + * https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch08s15.html + * + * @param {string} hostname - The hostname to validate + * @returns {boolean} True if valid domain or localhost + * @see {@link https://url.spec.whatwg.org/#valid-domain WHATWG URL Spec - Valid Domain} + */ +export declare function isValidDomain(hostname: string): boolean; +/** + * Create a WebAuthn credential using the browser's credentials API. + * Wraps navigator.credentials.create() with error handling. + * + * @param {CredentialCreationOptions} options - Options including publicKey parameters + * @returns {Promise>} Created credential or error + * @see {@link https://w3c.github.io/webauthn/#sctn-createCredential W3C WebAuthn Spec - Create Credential} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/create MDN - credentials.create} + */ +export declare function createCredential(options: StrictOmit & { + publicKey: PublicKeyCredentialCreationOptionsFuture; +}): Promise>; +/** + * Get a WebAuthn credential using the browser's credentials API. + * Wraps navigator.credentials.get() with error handling. + * + * @param {CredentialRequestOptions} options - Options including publicKey parameters + * @returns {Promise>} Retrieved credential or error + * @see {@link https://w3c.github.io/webauthn/#sctn-getAssertion W3C WebAuthn Spec - Get Assertion} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/get MDN - credentials.get} + */ +export declare function getCredential(options: StrictOmit & { + publicKey: PublicKeyCredentialRequestOptionsFuture; +}): Promise>; +export declare const DEFAULT_CREATION_OPTIONS: Partial; +export declare const DEFAULT_REQUEST_OPTIONS: Partial; +/** + * Merges WebAuthn credential creation options with overrides. + * Sets sensible defaults for authenticator selection and extensions. + * + * @param {PublicKeyCredentialCreationOptionsFuture} baseOptions - The base options from the server + * @param {PublicKeyCredentialCreationOptionsFuture} overrides - Optional overrides to apply + * @param {string} friendlyName - Optional friendly name for the credential + * @returns {PublicKeyCredentialCreationOptionsFuture} Merged credential creation options + * @see {@link https://w3c.github.io/webauthn/#dictdef-authenticatorselectioncriteria W3C WebAuthn Spec - AuthenticatorSelectionCriteria} + */ +export declare function mergeCredentialCreationOptions(baseOptions: PublicKeyCredentialCreationOptionsFuture, overrides?: Partial): PublicKeyCredentialCreationOptionsFuture; +/** + * Merges WebAuthn credential request options with overrides. + * Sets sensible defaults for user verification and hints. + * + * @param {PublicKeyCredentialRequestOptionsFuture} baseOptions - The base options from the server + * @param {PublicKeyCredentialRequestOptionsFuture} overrides - Optional overrides to apply + * @returns {PublicKeyCredentialRequestOptionsFuture} Merged credential request options + * @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialrequestoptions W3C WebAuthn Spec - PublicKeyCredentialRequestOptions} + */ +export declare function mergeCredentialRequestOptions(baseOptions: PublicKeyCredentialRequestOptionsFuture, overrides?: Partial): PublicKeyCredentialRequestOptionsFuture; +/** + * WebAuthn API wrapper for Supabase Auth. + * Provides methods for enrolling, challenging, verifying, authenticating, and registering WebAuthn credentials. + * + * @experimental This API is experimental and may change in future releases + * @see {@link https://w3c.github.io/webauthn/ W3C WebAuthn Specification} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API MDN - Web Authentication API} + */ +export declare class WebAuthnApi { + private client; + enroll: typeof WebAuthnApi.prototype._enroll; + challenge: typeof WebAuthnApi.prototype._challenge; + verify: typeof WebAuthnApi.prototype._verify; + authenticate: typeof WebAuthnApi.prototype._authenticate; + register: typeof WebAuthnApi.prototype._register; + constructor(client: GoTrueClient); + /** + * Enroll a new WebAuthn factor. + * Creates an unverified WebAuthn factor that must be verified with a credential. + * + * @experimental This method is experimental and may change in future releases + * @param {Omit} params - Enrollment parameters (friendlyName required) + * @returns {Promise} Enrolled factor details or error + * @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registering a New Credential} + */ + _enroll(params: Omit): Promise; + /** + * Challenge for WebAuthn credential creation or authentication. + * Combines server challenge with browser credential operations. + * Handles both registration (create) and authentication (request) flows. + * + * @experimental This method is experimental and may change in future releases + * @param {MFAChallengeWebauthnParams & { friendlyName?: string; signal?: AbortSignal }} params - Challenge parameters including factorId + * @param {Object} overrides - Allows you to override the parameters passed to navigator.credentials + * @param {PublicKeyCredentialCreationOptionsFuture} overrides.create - Override options for credential creation + * @param {PublicKeyCredentialRequestOptionsFuture} overrides.request - Override options for credential request + * @returns {Promise} Challenge response with credential or error + * @see {@link https://w3c.github.io/webauthn/#sctn-credential-creation W3C WebAuthn Spec - Credential Creation} + * @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying Assertion} + */ + _challenge({ factorId, webauthn, friendlyName, signal, }: MFAChallengeWebauthnParams & { + friendlyName?: string; + signal?: AbortSignal; + }, overrides?: { + create?: Partial; + request?: never; + } | { + create?: never; + request?: Partial; + }): Promise['webauthn'], 'rpId' | 'rpOrigins'>; + }, WebAuthnError | AuthError>>; + /** + * Verify a WebAuthn credential with the server. + * Completes the WebAuthn ceremony by sending the credential to the server for verification. + * + * @experimental This method is experimental and may change in future releases + * @param {Object} params - Verification parameters + * @param {string} params.challengeId - ID of the challenge being verified + * @param {string} params.factorId - ID of the WebAuthn factor + * @param {MFAVerifyWebauthnParams['webauthn']} params.webauthn - WebAuthn credential response + * @returns {Promise} Verification result with session or error + * @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying an Authentication Assertion} + * */ + _verify({ challengeId, factorId, webauthn, }: { + challengeId: string; + factorId: string; + webauthn: MFAVerifyWebauthnParams['webauthn']; + }): Promise; + /** + * Complete WebAuthn authentication flow. + * Performs challenge and verification in a single operation for existing credentials. + * + * @experimental This method is experimental and may change in future releases + * @param {Object} params - Authentication parameters + * @param {string} params.factorId - ID of the WebAuthn factor to authenticate with + * @param {Object} params.webauthn - WebAuthn configuration + * @param {string} params.webauthn.rpId - Relying Party ID (defaults to current hostname) + * @param {string[]} params.webauthn.rpOrigins - Allowed origins (defaults to current origin) + * @param {AbortSignal} params.webauthn.signal - Optional abort signal + * @param {PublicKeyCredentialRequestOptionsFuture} overrides - Override options for navigator.credentials.get + * @returns {Promise>} Authentication result + * @see {@link https://w3c.github.io/webauthn/#sctn-authentication W3C WebAuthn Spec - Authentication Ceremony} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialRequestOptions MDN - PublicKeyCredentialRequestOptions} + */ + _authenticate({ factorId, webauthn: { rpId, rpOrigins, signal, }, }: { + factorId: string; + webauthn?: { + rpId?: string; + rpOrigins?: string[]; + signal?: AbortSignal; + }; + }, overrides?: PublicKeyCredentialRequestOptionsFuture): Promise>; + /** + * Complete WebAuthn registration flow. + * Performs enrollment, challenge, and verification in a single operation for new credentials. + * + * @experimental This method is experimental and may change in future releases + * @param {Object} params - Registration parameters + * @param {string} params.friendlyName - User-friendly name for the credential + * @param {string} params.rpId - Relying Party ID (defaults to current hostname) + * @param {string[]} params.rpOrigins - Allowed origins (defaults to current origin) + * @param {AbortSignal} params.signal - Optional abort signal + * @param {PublicKeyCredentialCreationOptionsFuture} overrides - Override options for navigator.credentials.create + * @returns {Promise>} Registration result + * @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registration Ceremony} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions MDN - PublicKeyCredentialCreationOptions} + */ + _register({ friendlyName, webauthn: { rpId, rpOrigins, signal, }, }: { + friendlyName: string; + webauthn?: { + rpId?: string; + rpOrigins?: string[]; + signal?: AbortSignal; + }; + }, overrides?: Partial): Promise>; +} +//# sourceMappingURL=webauthn.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/webauthn.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/main/lib/webauthn.d.ts.map new file mode 100644 index 0000000..a608276 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/webauthn.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"webauthn.d.ts","sourceRoot":"","sources":["../../../src/lib/webauthn.ts"],"names":[],"mappings":"AAAA,OAAO,YAAY,MAAM,iBAAiB,CAAA;AAE1C,OAAO,EAAE,SAAS,EAAiC,MAAM,UAAU,CAAA;AACnE,OAAO,EACL,6BAA6B,EAC7B,qBAAqB,EACrB,yBAAyB,EACzB,0BAA0B,EAC1B,uBAAuB,EACvB,4BAA4B,EAC5B,uBAAuB,EACvB,aAAa,EACb,UAAU,EACX,MAAM,SAAS,CAAA;AAEhB,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAE1B,wCAAwC,EACxC,sCAAsC,EAEtC,uCAA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AI,CAAC,EAAE,MAAM,CAAA;YACb,SAAS,CAAC,EAAE,MAAM,EAAE,CAAA;YACpB,MAAM,CAAC,EAAE,WAAW,CAAA;SACrB,CAAA;KACF,EACD,SAAS,CAAC,EAAE,uCAAuC,GAClD,OAAO,CAAC,aAAa,CAAC,yBAAyB,EAAE,aAAa,GAAG,SAAS,CAAC,CAAC;IAqD/E;;;;;;;;;;;;;;OAcG;IACU,SAAS,CACpB,EACE,YAAY,EACZ,QAAQ,EAAE,EACR,IAA2E,EAC3E,SAAgF,EAChF,MAAM,GACF,GACP,EAAE;QACD,YAAY,EAAE,MAAM,CAAA;QACpB,QAAQ,CAAC,EAAE;YACT,IAAI,CAAC,EAAE,MAAM,CAAA;YACb,SAAS,CAAC,EAAE,MAAM,EAAE,CAAA;YACpB,MAAM,CAAC,EAAE,WAAW,CAAA;SACrB,CAAA;KACF,EACD,SAAS,CAAC,EAAE,OAAO,CAAC,wCAAwC,CAAC,GAC5D,OAAO,CAAC,aAAa,CAAC,yBAAyB,EAAE,aAAa,GAAG,SAAS,CAAC,CAAC;CAwEhF"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/webauthn.dom.d.ts b/backend/node_modules/@supabase/auth-js/dist/main/lib/webauthn.dom.d.ts new file mode 100644 index 0000000..ff0410f --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/webauthn.dom.d.ts @@ -0,0 +1,583 @@ +import { StrictOmit } from './types'; +/** + * A variant of PublicKeyCredentialCreationOptions suitable for JSON transmission to the browser to + * (eventually) get passed into navigator.credentials.create(...) in the browser. + * + * This should eventually get replaced with official TypeScript DOM types when WebAuthn Level 3 types + * eventually make it into the language: + * + * @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialcreationoptionsjson W3C WebAuthn Spec - PublicKeyCredentialCreationOptionsJSON} + */ +export interface PublicKeyCredentialCreationOptionsJSON { + /** + * Information about the Relying Party responsible for the request. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-rp W3C - rp} + */ + rp: PublicKeyCredentialRpEntity; + /** + * Information about the user account for which the credential is being created. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-user W3C - user} + */ + user: PublicKeyCredentialUserEntityJSON; + /** + * A server-generated challenge in base64url format. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-challenge W3C - challenge} + */ + challenge: Base64URLString; + /** + * Information about desired properties of the credential to be created. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-pubkeycredparams W3C - pubKeyCredParams} + */ + pubKeyCredParams: PublicKeyCredentialParameters[]; + /** + * Time in milliseconds that the caller is willing to wait for the operation to complete. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-timeout W3C - timeout} + */ + timeout?: number; + /** + * Credentials that the authenticator should not create a new credential for. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-excludecredentials W3C - excludeCredentials} + */ + excludeCredentials?: PublicKeyCredentialDescriptorJSON[]; + /** + * Criteria for authenticator selection. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-authenticatorselection W3C - authenticatorSelection} + */ + authenticatorSelection?: AuthenticatorSelectionCriteria; + /** + * Hints about what types of authenticators the user might want to use. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-hints W3C - hints} + */ + hints?: PublicKeyCredentialHint[]; + /** + * How the attestation statement should be transported. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-attestation W3C - attestation} + */ + attestation?: AttestationConveyancePreference; + /** + * The attestation statement formats that the Relying Party will accept. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-attestationformats W3C - attestationFormats} + */ + attestationFormats?: AttestationFormat[]; + /** + * Additional parameters requesting additional processing by the client and authenticator. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-extensions W3C - extensions} + */ + extensions?: AuthenticationExtensionsClientInputs; +} +/** + * A variant of PublicKeyCredentialRequestOptions suitable for JSON transmission to the browser to + * (eventually) get passed into navigator.credentials.get(...) in the browser. + * + * @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialrequestoptionsjson W3C WebAuthn Spec - PublicKeyCredentialRequestOptionsJSON} + */ +export interface PublicKeyCredentialRequestOptionsJSON { + /** + * A server-generated challenge in base64url format. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialrequestoptions-challenge W3C - challenge} + */ + challenge: Base64URLString; + /** + * Time in milliseconds that the caller is willing to wait for the operation to complete. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialrequestoptions-timeout W3C - timeout} + */ + timeout?: number; + /** + * The relying party identifier claimed by the caller. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialrequestoptions-rpid W3C - rpId} + */ + rpId?: string; + /** + * A list of credentials acceptable for authentication. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialrequestoptions-allowcredentials W3C - allowCredentials} + */ + allowCredentials?: PublicKeyCredentialDescriptorJSON[]; + /** + * Whether user verification should be performed by the authenticator. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialrequestoptions-userverification W3C - userVerification} + */ + userVerification?: UserVerificationRequirement; + /** + * Hints about what types of authenticators the user might want to use. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialrequestoptions-hints W3C - hints} + */ + hints?: PublicKeyCredentialHint[]; + /** + * Additional parameters requesting additional processing by the client and authenticator. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialrequestoptions-extensions W3C - extensions} + */ + extensions?: AuthenticationExtensionsClientInputs; +} +/** + * Represents a public key credential descriptor in JSON format. + * Used to identify credentials for exclusion or allowance during WebAuthn ceremonies. + * + * @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialdescriptorjson W3C WebAuthn Spec - PublicKeyCredentialDescriptorJSON} + */ +export interface PublicKeyCredentialDescriptorJSON { + /** + * The credential ID in base64url format. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialdescriptor-id W3C - id} + */ + id: Base64URLString; + /** + * The type of the public key credential (always "public-key"). + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialdescriptor-type W3C - type} + */ + type: PublicKeyCredentialType; + /** + * How the authenticator communicates with clients. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialdescriptor-transports W3C - transports} + */ + transports?: AuthenticatorTransportFuture[]; +} +/** + * Represents user account information in JSON format for WebAuthn registration. + * Contains identifiers and display information for the user being registered. + * + * @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialuserentityjson W3C WebAuthn Spec - PublicKeyCredentialUserEntityJSON} + */ +export interface PublicKeyCredentialUserEntityJSON { + /** + * A unique identifier for the user account (base64url encoded). + * Maximum 64 bytes. Should not contain PII. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialuserentity-id W3C - user.id} + */ + id: string; + /** + * A human-readable identifier for the account (e.g., email, username). + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialentity-name W3C - user.name} + */ + name: string; + /** + * A human-friendly display name for the user (e.g., "John Doe"). + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialuserentity-displayname W3C - user.displayName} + */ + displayName: string; +} +/** + * Represents user account information for WebAuthn registration with binary data. + * Contains identifiers and display information for the user being registered. + * + * @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialuserentity W3C WebAuthn Spec - PublicKeyCredentialUserEntity} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialUserEntity MDN - PublicKeyCredentialUserEntity} + */ +export interface PublicKeyCredentialUserEntity { + /** + * A unique identifier for the user account. + * Maximum 64 bytes. Should not contain PII. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialuserentity-id W3C - user.id} + */ + id: BufferSource; + /** + * A human-readable identifier for the account. + * Typically an email, username, or phone number. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialentity-name W3C - user.name} + */ + name: string; + /** + * A human-friendly display name for the user. + * Example: "John Doe" + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialuserentity-displayname W3C - user.displayName} + */ + displayName: string; +} +/** + * The credential returned from navigator.credentials.create() during WebAuthn registration. + * Contains the new credential's public key and attestation information. + * + * @see {@link https://w3c.github.io/webauthn/#registrationceremony W3C WebAuthn Spec - Registration} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredential MDN - PublicKeyCredential} + */ +export interface RegistrationCredential extends PublicKeyCredentialFuture { + response: AuthenticatorAttestationResponseFuture; +} +/** + * A slightly-modified RegistrationCredential to simplify working with ArrayBuffers that + * are Base64URL-encoded in the browser so that they can be sent as JSON to the server. + * + * @see {@link https://w3c.github.io/webauthn/#dictdef-registrationresponsejson W3C WebAuthn Spec - RegistrationResponseJSON} + */ +export interface RegistrationResponseJSON { + /** + * The credential ID (same as rawId for JSON). + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-id W3C - id} + */ + id: Base64URLString; + /** + * The raw credential ID in base64url format. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-rawid W3C - rawId} + */ + rawId: Base64URLString; + /** + * The authenticator's response to the client's request to create a credential. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-response W3C - response} + */ + response: AuthenticatorAttestationResponseJSON; + /** + * The authenticator attachment modality in effect at the time of credential creation. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-authenticatorattachment W3C - authenticatorAttachment} + */ + authenticatorAttachment?: AuthenticatorAttachment; + /** + * The results of processing client extensions. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-getclientextensionresults W3C - getClientExtensionResults} + */ + clientExtensionResults: AuthenticationExtensionsClientOutputs; + /** + * The type of the credential (always "public-key"). + * @see {@link https://w3c.github.io/webauthn/#dom-credential-type W3C - type} + */ + type: PublicKeyCredentialType; +} +/** + * The credential returned from navigator.credentials.get() during WebAuthn authentication. + * Contains the assertion signature proving possession of the private key. + * + * @see {@link https://w3c.github.io/webauthn/#authentication W3C WebAuthn Spec - Authentication} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredential MDN - PublicKeyCredential} + */ +export interface AuthenticationCredential extends PublicKeyCredentialFuture { + response: AuthenticatorAssertionResponse; +} +/** + * A slightly-modified AuthenticationCredential to simplify working with ArrayBuffers that + * are Base64URL-encoded in the browser so that they can be sent as JSON to the server. + * + * @see {@link https://w3c.github.io/webauthn/#dictdef-authenticationresponsejson W3C WebAuthn Spec - AuthenticationResponseJSON} + */ +export interface AuthenticationResponseJSON { + /** + * The credential ID (same as rawId for JSON). + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-id W3C - id} + */ + id: Base64URLString; + /** + * The raw credential ID in base64url format. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-rawid W3C - rawId} + */ + rawId: Base64URLString; + /** + * The authenticator's response to the client's request to authenticate. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-response W3C - response} + */ + response: AuthenticatorAssertionResponseJSON; + /** + * The authenticator attachment modality in effect at the time of authentication. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-authenticatorattachment W3C - authenticatorAttachment} + */ + authenticatorAttachment?: AuthenticatorAttachment; + /** + * The results of processing client extensions. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-getclientextensionresults W3C - getClientExtensionResults} + */ + clientExtensionResults: AuthenticationExtensionsClientOutputs; + /** + * The type of the credential (always "public-key"). + * @see {@link https://w3c.github.io/webauthn/#dom-credential-type W3C - type} + */ + type: PublicKeyCredentialType; +} +/** + * A slightly-modified AuthenticatorAttestationResponse to simplify working with ArrayBuffers that + * are Base64URL-encoded in the browser so that they can be sent as JSON to the server. + * + * @see {@link https://w3c.github.io/webauthn/#dictdef-authenticatorattestationresponsejson W3C WebAuthn Spec - AuthenticatorAttestationResponseJSON} + */ +export interface AuthenticatorAttestationResponseJSON { + /** + * JSON-serialized client data passed to the authenticator. + * @see {@link https://w3c.github.io/webauthn/#dom-authenticatorresponse-clientdatajson W3C - clientDataJSON} + */ + clientDataJSON: Base64URLString; + /** + * The attestation object in base64url format. + * @see {@link https://w3c.github.io/webauthn/#dom-authenticatorattestationresponse-attestationobject W3C - attestationObject} + */ + attestationObject: Base64URLString; + /** + * The authenticator data contained within the attestation object. + * Optional in L2, but becomes required in L3. Play it safe until L3 becomes Recommendation + * @see {@link https://w3c.github.io/webauthn/#dom-authenticatorattestationresponse-getauthenticatordata W3C - getAuthenticatorData} + */ + authenticatorData?: Base64URLString; + /** + * The transports that the authenticator supports. + * Optional in L2, but becomes required in L3. Play it safe until L3 becomes Recommendation + * @see {@link https://w3c.github.io/webauthn/#dom-authenticatorattestationresponse-gettransports W3C - getTransports} + */ + transports?: AuthenticatorTransportFuture[]; + /** + * The COSEAlgorithmIdentifier for the public key. + * Optional in L2, but becomes required in L3. Play it safe until L3 becomes Recommendation + * @see {@link https://w3c.github.io/webauthn/#dom-authenticatorattestationresponse-getpublickeyalgorithm W3C - getPublicKeyAlgorithm} + */ + publicKeyAlgorithm?: COSEAlgorithmIdentifier; + /** + * The public key in base64url format. + * @see {@link https://w3c.github.io/webauthn/#dom-authenticatorattestationresponse-getpublickey W3C - getPublicKey} + */ + publicKey?: Base64URLString; +} +/** + * A slightly-modified AuthenticatorAssertionResponse to simplify working with ArrayBuffers that + * are Base64URL-encoded in the browser so that they can be sent as JSON to the server. + * + * @see {@link https://w3c.github.io/webauthn/#dictdef-authenticatorassertionresponsejson W3C WebAuthn Spec - AuthenticatorAssertionResponseJSON} + */ +export interface AuthenticatorAssertionResponseJSON { + /** + * JSON-serialized client data passed to the authenticator. + * @see {@link https://w3c.github.io/webauthn/#dom-authenticatorresponse-clientdatajson W3C - clientDataJSON} + */ + clientDataJSON: Base64URLString; + /** + * The authenticator data returned by the authenticator. + * @see {@link https://w3c.github.io/webauthn/#dom-authenticatorassertionresponse-authenticatordata W3C - authenticatorData} + */ + authenticatorData: Base64URLString; + /** + * The signature generated by the authenticator. + * @see {@link https://w3c.github.io/webauthn/#dom-authenticatorassertionresponse-signature W3C - signature} + */ + signature: Base64URLString; + /** + * The user handle returned by the authenticator, if any. + * @see {@link https://w3c.github.io/webauthn/#dom-authenticatorassertionresponse-userhandle W3C - userHandle} + */ + userHandle?: Base64URLString; +} +/** + * Public key credential information needed to verify authentication responses. + * Stores the credential's public key and metadata for server-side verification. + * + * @see {@link https://w3c.github.io/webauthn/#sctn-credential-storage-modality W3C WebAuthn Spec - Credential Storage} + */ +export type WebAuthnCredential = { + /** + * The credential ID in base64url format. + * @see {@link https://w3c.github.io/webauthn/#credential-id W3C - Credential ID} + */ + id: Base64URLString; + /** + * The credential's public key. + * @see {@link https://w3c.github.io/webauthn/#credential-public-key W3C - Credential Public Key} + */ + publicKey: Uint8Array_; + /** + * Number of times this authenticator is expected to have been used. + * @see {@link https://w3c.github.io/webauthn/#signature-counter W3C - Signature Counter} + */ + counter: number; + /** + * The transports that the authenticator supports. + * From browser's `startRegistration()` -> RegistrationCredentialJSON.transports (API L2 and up) + * @see {@link https://w3c.github.io/webauthn/#dom-authenticatorattestationresponse-gettransports W3C - getTransports} + */ + transports?: AuthenticatorTransportFuture[]; +}; +/** + * An attempt to communicate that this isn't just any string, but a Base64URL-encoded string. + * Base64URL encoding is used throughout WebAuthn for binary data transmission. + * + * @see {@link https://datatracker.ietf.org/doc/html/rfc4648#section-5 RFC 4648 - Base64URL Encoding} + */ +export type Base64URLString = string; +/** + * AuthenticatorAttestationResponse in TypeScript's DOM lib is outdated (up through v3.9.7). + * Maintain an augmented version here so we can implement additional properties as the WebAuthn + * spec evolves. + * + * Properties marked optional are not supported in all browsers. + * + * @see {@link https://www.w3.org/TR/webauthn-2/#iface-authenticatorattestationresponse W3C WebAuthn Spec - AuthenticatorAttestationResponse} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AuthenticatorAttestationResponse MDN - AuthenticatorAttestationResponse} + */ +export interface AuthenticatorAttestationResponseFuture extends AuthenticatorAttestationResponse { + /** + * Returns the transports that the authenticator supports. + * @see {@link https://w3c.github.io/webauthn/#dom-authenticatorattestationresponse-gettransports W3C - getTransports} + */ + getTransports(): AuthenticatorTransportFuture[]; +} +/** + * A super class of TypeScript's `AuthenticatorTransport` that includes support for the latest + * transports. Should eventually be replaced by TypeScript's when TypeScript gets updated to + * know about it (sometime after 4.6.3) + * + * @see {@link https://w3c.github.io/webauthn/#enum-transport W3C WebAuthn Spec - AuthenticatorTransport} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AuthenticatorAttestationResponse/getTransports MDN - getTransports} + */ +export type AuthenticatorTransportFuture = 'ble' | 'cable' | 'hybrid' | 'internal' | 'nfc' | 'smart-card' | 'usb'; +/** + * A super class of TypeScript's `PublicKeyCredentialDescriptor` that knows about the latest + * transports. Should eventually be replaced by TypeScript's when TypeScript gets updated to + * know about it (sometime after 4.6.3) + * + * @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialdescriptor W3C WebAuthn Spec - PublicKeyCredentialDescriptor} + */ +export interface PublicKeyCredentialDescriptorFuture extends Omit { + /** + * How the authenticator communicates with clients. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialdescriptor-transports W3C - transports} + */ + transports?: AuthenticatorTransportFuture[]; +} +/** + * Enhanced PublicKeyCredentialCreationOptions that knows about the latest features. + * Used for WebAuthn registration ceremonies. + * + * @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialcreationoptions W3C WebAuthn Spec - PublicKeyCredentialCreationOptions} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions MDN - PublicKeyCredentialCreationOptions} + */ +export interface PublicKeyCredentialCreationOptionsFuture extends StrictOmit { + /** + * Credentials that the authenticator should not create a new credential for. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-excludecredentials W3C - excludeCredentials} + */ + excludeCredentials?: PublicKeyCredentialDescriptorFuture[]; + /** + * Information about the user account for which the credential is being created. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-user W3C - user} + */ + user: PublicKeyCredentialUserEntity; + /** + * Hints about what types of authenticators the user might want to use. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-hints W3C - hints} + */ + hints?: PublicKeyCredentialHint[]; + /** + * Criteria for authenticator selection. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-authenticatorselection W3C - authenticatorSelection} + */ + authenticatorSelection?: AuthenticatorSelectionCriteria; + /** + * Information about desired properties of the credential to be created. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-pubkeycredparams W3C - pubKeyCredParams} + */ + pubKeyCredParams: PublicKeyCredentialParameters[]; + /** + * Information about the Relying Party responsible for the request. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-rp W3C - rp} + */ + rp: PublicKeyCredentialRpEntity; +} +/** + * Enhanced PublicKeyCredentialRequestOptions that knows about the latest features. + * Used for WebAuthn authentication ceremonies. + * + * @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialrequestoptions W3C WebAuthn Spec - PublicKeyCredentialRequestOptions} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialRequestOptions MDN - PublicKeyCredentialRequestOptions} + */ +export interface PublicKeyCredentialRequestOptionsFuture extends StrictOmit { + /** + * A list of credentials acceptable for authentication. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialrequestoptions-allowcredentials W3C - allowCredentials} + */ + allowCredentials?: PublicKeyCredentialDescriptorFuture[]; + /** + * Hints about what types of authenticators the user might want to use. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialrequestoptions-hints W3C - hints} + */ + hints?: PublicKeyCredentialHint[]; + /** + * The attestation conveyance preference for the authentication ceremony. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-attestation W3C - attestation} + */ + attestation?: AttestationConveyancePreference; +} +/** + * Union type for all WebAuthn credential responses in JSON format. + * Can be either a registration response (for new credentials) or authentication response (for existing credentials). + */ +export type PublicKeyCredentialJSON = RegistrationResponseJSON | AuthenticationResponseJSON; +/** + * A super class of TypeScript's `PublicKeyCredential` that knows about upcoming WebAuthn features. + * Includes WebAuthn Level 3 methods for JSON serialization and parsing. + * + * @see {@link https://w3c.github.io/webauthn/#publickeycredential W3C WebAuthn Spec - PublicKeyCredential} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredential MDN - PublicKeyCredential} + */ +export interface PublicKeyCredentialFuture extends PublicKeyCredential { + /** + * The type of the credential (always "public-key"). + * @see {@link https://w3c.github.io/webauthn/#dom-credential-type W3C - type} + */ + type: PublicKeyCredentialType; + /** + * Checks if conditional mediation is available. + * @see {@link https://github.com/w3c/webauthn/issues/1745 GitHub - Conditional Mediation} + */ + isConditionalMediationAvailable?(): Promise; + /** + * Parses JSON to create PublicKeyCredentialCreationOptions. + * @see {@link https://w3c.github.io/webauthn/#sctn-parseCreationOptionsFromJSON W3C - parseCreationOptionsFromJSON} + */ + parseCreationOptionsFromJSON(options: PublicKeyCredentialCreationOptionsJSON): PublicKeyCredentialCreationOptionsFuture; + /** + * Parses JSON to create PublicKeyCredentialRequestOptions. + * @see {@link https://w3c.github.io/webauthn/#sctn-parseRequestOptionsFromJSON W3C - parseRequestOptionsFromJSON} + */ + parseRequestOptionsFromJSON(options: PublicKeyCredentialRequestOptionsJSON): PublicKeyCredentialRequestOptionsFuture; + /** + * Serializes the credential to JSON format. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-tojson W3C - toJSON} + */ + toJSON(): T; +} +/** + * The two types of credentials as defined by bit 3 ("Backup Eligibility") in authenticator data: + * - `"singleDevice"` credentials will never be backed up + * - `"multiDevice"` credentials can be backed up + * + * @see {@link https://w3c.github.io/webauthn/#sctn-authenticator-data W3C WebAuthn Spec - Authenticator Data} + */ +export type CredentialDeviceType = 'singleDevice' | 'multiDevice'; +/** + * Categories of authenticators that Relying Parties can pass along to browsers during + * registration. Browsers that understand these values can optimize their modal experience to + * start the user off in a particular registration flow: + * + * - `hybrid`: A platform authenticator on a mobile device + * - `security-key`: A portable FIDO2 authenticator capable of being used on multiple devices via a USB or NFC connection + * - `client-device`: The device that WebAuthn is being called on. Typically synonymous with platform authenticators + * + * These values are less strict than `authenticatorAttachment` + * + * @see {@link https://w3c.github.io/webauthn/#enumdef-publickeycredentialhint W3C WebAuthn Spec - PublicKeyCredentialHint} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions#hints MDN - hints} + */ +export type PublicKeyCredentialHint = 'hybrid' | 'security-key' | 'client-device'; +/** + * Values for an attestation object's `fmt`. + * Defines the format of the attestation statement from the authenticator. + * + * @see {@link https://www.iana.org/assignments/webauthn/webauthn.xhtml#webauthn-attestation-statement-format-ids IANA - WebAuthn Attestation Statement Format Identifiers} + * @see {@link https://w3c.github.io/webauthn/#sctn-attestation-formats W3C WebAuthn Spec - Attestation Statement Formats} + */ +export type AttestationFormat = 'fido-u2f' | 'packed' | 'android-safetynet' | 'android-key' | 'tpm' | 'apple' | 'none'; +/** + * Equivalent to `Uint8Array` before TypeScript 5.7, and `Uint8Array` in TypeScript 5.7 + * and beyond. + * + * **Context** + * + * `Uint8Array` became a generic type in TypeScript 5.7, requiring types defined simply as + * `Uint8Array` to be refactored to `Uint8Array` starting in Deno 2.2. `Uint8Array` is + * _not_ generic in Deno 2.1.x and earlier, though, so this type helps bridge this gap. + * + * Inspired by Deno's std library: + * + * https://github.com/denoland/std/blob/b5a5fe4f96b91c1fe8dba5cc0270092dd11d3287/bytes/_types.ts#L11 + */ +export type Uint8Array_ = ReturnType; +/** + * Specifies the preferred authenticator attachment modality. + * - `platform`: A platform authenticator attached to the client device (e.g., Touch ID, Windows Hello) + * - `cross-platform`: A roaming authenticator not attached to the client device (e.g., USB security key) + * + * @see {@link https://w3c.github.io/webauthn/#enum-attachment W3C WebAuthn Spec - AuthenticatorAttachment} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions/authenticatorSelection#authenticatorattachment MDN - authenticatorAttachment} + */ +export type AuthenticatorAttachment = 'cross-platform' | 'platform'; +//# sourceMappingURL=webauthn.dom.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/webauthn.dom.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/main/lib/webauthn.dom.d.ts.map new file mode 100644 index 0000000..d9d3aeb --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/webauthn.dom.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"webauthn.dom.d.ts","sourceRoot":"","sources":["../../../src/lib/webauthn.dom.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AAEpC;;;;;;;;GAQG;AACH,MAAM,WAAW,sCAAsC;IACrD;;;OAGG;IACH,EAAE,EAAE,2BAA2B,CAAA;IAC/B;;;OAGG;IACH,IAAI,EAAE,iCAAiC,CAAA;IACvC;;;OAGG;IACH,SAAS,EAAE,eAAe,CAAA;IAC1B;;;OAGG;IACH,gBAAgB,EAAE,6BAA6B,EAAE,CAAA;IACjD;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB;;;OAGG;IACH,kBAAkB,CAAC,EAAE,iCAAiC,EAAE,CAAA;IACxD;;;OAGG;IACH,sBAAsB,CAAC,EAAE,8BAA8B,CAAA;IACvD;;;OAGG;IACH,KAAK,CAAC,EAAE,uBAAuB,EAAE,CAAA;IACjC;;;OAGG;IACH,WAAW,CAAC,EAAE,+BAA+B,CAAA;IAC7C;;;OAGG;IACH,kBAAkB,CAAC,EAAE,iBAAiB,EAAE,CAAA;IACxC;;;OAGG;IACH,UAAU,CAAC,EAAE,oCAAoC,CAAA;CAClD;AAED;;;;;GAKG;AACH,MAAM,WAAW,qCAAqC;IACpD;;;OAGG;IACH,SAA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AK,CAAC,EAAE,uBAAuB,EAAE,CAAA;IACjC;;;OAGG;IACH,WAAW,CAAC,EAAE,+BAA+B,CAAA;CAC9C;AAED;;;GAGG;AACH,MAAM,MAAM,uBAAuB,GAAG,wBAAwB,GAAG,0BAA0B,CAAA;AAE3F;;;;;;GAMG;AACH,MAAM,WAAW,yBAAyB,CACxC,CAAC,SAAS,uBAAuB,GAAG,uBAAuB,CAC3D,SAAQ,mBAAmB;IAC3B;;;OAGG;IACH,IAAI,EAAE,uBAAuB,CAAA;IAC7B;;;OAGG;IACH,+BAA+B,CAAC,IAAI,OAAO,CAAC,OAAO,CAAC,CAAA;IACpD;;;OAGG;IACH,4BAA4B,CAC1B,OAAO,EAAE,sCAAsC,GAC9C,wCAAwC,CAAA;IAC3C;;;OAGG;IACH,2BAA2B,CACzB,OAAO,EAAE,qCAAqC,GAC7C,uCAAuC,CAAA;IAC1C;;;OAGG;IACH,MAAM,IAAI,CAAC,CAAA;CACZ;AAED;;;;;;GAMG;AACH,MAAM,MAAM,oBAAoB,GAAG,cAAc,GAAG,aAAa,CAAA;AAEjE;;;;;;;;;;;;;GAaG;AACH,MAAM,MAAM,uBAAuB,GAAG,QAAQ,GAAG,cAAc,GAAG,eAAe,CAAA;AAEjF;;;;;;GAMG;AACH,MAAM,MAAM,iBAAiB,GACzB,UAAU,GACV,QAAQ,GACR,mBAAmB,GACnB,aAAa,GACb,KAAK,GACL,OAAO,GACP,MAAM,CAAA;AAEV;;;;;;;;;;;;;GAaG;AACH,MAAM,MAAM,WAAW,GAAG,UAAU,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAA;AAEzD;;;;;;;GAOG;AACH,MAAM,MAAM,uBAAuB,GAAG,gBAAgB,GAAG,UAAU,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/webauthn.dom.js b/backend/node_modules/@supabase/auth-js/dist/main/lib/webauthn.dom.js new file mode 100644 index 0000000..9d4c49a --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/webauthn.dom.js @@ -0,0 +1,4 @@ +"use strict"; +// from https://github.com/MasterKale/SimpleWebAuthn/blob/master/packages/browser/src/types/index.ts +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=webauthn.dom.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/webauthn.dom.js.map b/backend/node_modules/@supabase/auth-js/dist/main/lib/webauthn.dom.js.map new file mode 100644 index 0000000..d0f8a73 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/webauthn.dom.js.map @@ -0,0 +1 @@ +{"version":3,"file":"webauthn.dom.js","sourceRoot":"","sources":["../../../src/lib/webauthn.dom.ts"],"names":[],"mappings":";AAAA,oGAAoG"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/webauthn.errors.d.ts b/backend/node_modules/@supabase/auth-js/dist/main/lib/webauthn.errors.d.ts new file mode 100644 index 0000000..5fe8218 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/webauthn.errors.d.ts @@ -0,0 +1,80 @@ +import { StrictOmit } from './types'; +import { PublicKeyCredentialCreationOptionsFuture, PublicKeyCredentialRequestOptionsFuture } from './webauthn.dom'; +/** + * A custom Error used to return a more nuanced error detailing _why_ one of the eight documented + * errors in the spec was raised after calling `navigator.credentials.create()` or + * `navigator.credentials.get()`: + * + * - `AbortError` + * - `ConstraintError` + * - `InvalidStateError` + * - `NotAllowedError` + * - `NotSupportedError` + * - `SecurityError` + * - `TypeError` + * - `UnknownError` + * + * Error messages were determined through investigation of the spec to determine under which + * scenarios a given error would be raised. + */ +export declare class WebAuthnError extends Error { + code: WebAuthnErrorCode; + protected __isWebAuthnError: boolean; + constructor({ message, code, cause, name, }: { + message: string; + code: WebAuthnErrorCode; + cause?: Error | unknown; + name?: string; + }); +} +/** + * Error class for unknown WebAuthn errors. + * Wraps unexpected errors that don't match known WebAuthn error conditions. + */ +export declare class WebAuthnUnknownError extends WebAuthnError { + originalError: unknown; + constructor(message: string, originalError: unknown); +} +/** + * Type guard to check if an error is a WebAuthnError. + * @param {unknown} error - The error to check + * @returns {boolean} True if the error is a WebAuthnError + */ +export declare function isWebAuthnError(error: unknown): error is WebAuthnError; +/** + * Error codes for WebAuthn operations. + * These codes provide specific information about why a WebAuthn ceremony failed. + * @see {@link https://w3c.github.io/webauthn/#sctn-defined-errors W3C WebAuthn Spec - Defined Errors} + */ +export type WebAuthnErrorCode = 'ERROR_CEREMONY_ABORTED' | 'ERROR_INVALID_DOMAIN' | 'ERROR_INVALID_RP_ID' | 'ERROR_INVALID_USER_ID_LENGTH' | 'ERROR_MALFORMED_PUBKEYCREDPARAMS' | 'ERROR_AUTHENTICATOR_GENERAL_ERROR' | 'ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT' | 'ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT' | 'ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED' | 'ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG' | 'ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE' | 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY'; +/** + * Attempt to intuit _why_ an error was raised after calling `navigator.credentials.create()`. + * Maps browser errors to specific WebAuthn error codes for better debugging. + * @param {Object} params - Error identification parameters + * @param {Error} params.error - The error thrown by the browser + * @param {CredentialCreationOptions} params.options - The options passed to credentials.create() + * @returns {WebAuthnError} A WebAuthnError with a specific error code + * @see {@link https://w3c.github.io/webauthn/#sctn-createCredential W3C WebAuthn Spec - Create Credential} + */ +export declare function identifyRegistrationError({ error, options, }: { + error: Error; + options: StrictOmit & { + publicKey: PublicKeyCredentialCreationOptionsFuture; + }; +}): WebAuthnError; +/** + * Attempt to intuit _why_ an error was raised after calling `navigator.credentials.get()`. + * Maps browser errors to specific WebAuthn error codes for better debugging. + * @param {Object} params - Error identification parameters + * @param {Error} params.error - The error thrown by the browser + * @param {CredentialRequestOptions} params.options - The options passed to credentials.get() + * @returns {WebAuthnError} A WebAuthnError with a specific error code + * @see {@link https://w3c.github.io/webauthn/#sctn-getAssertion W3C WebAuthn Spec - Get Assertion} + */ +export declare function identifyAuthenticationError({ error, options, }: { + error: Error; + options: StrictOmit & { + publicKey: PublicKeyCredentialRequestOptionsFuture; + }; +}): WebAuthnError; +//# sourceMappingURL=webauthn.errors.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/webauthn.errors.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/main/lib/webauthn.errors.d.ts.map new file mode 100644 index 0000000..0c057a6 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/webauthn.errors.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"webauthn.errors.d.ts","sourceRoot":"","sources":["../../../src/lib/webauthn.errors.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AAEpC,OAAO,EACL,wCAAwC,EACxC,uCAAuC,EACxC,MAAM,gBAAgB,CAAA;AAEvB;;;;;;;;;;;;;;;;GAgBG;AACH,qBAAa,aAAc,SAAQ,KAAK;IACtC,IAAI,EAAE,iBAAiB,CAAA;IAEvB,SAAS,CAAC,iBAAiB,UAAO;gBAEtB,EACV,OAAO,EACP,IAAI,EACJ,KAAK,EACL,IAAI,GACL,EAAE;QACD,OAAO,EAAE,MAAM,CAAA;QACf,IAAI,EAAE,iBAAiB,CAAA;QACvB,KAAK,CAAC,EAAE,KAAK,GAAG,OAAO,CAAA;QACvB,IAAI,CAAC,EAAE,MAAM,CAAA;KACd;CAMF;AAED;;;GAGG;AACH,qBAAa,oBAAqB,SAAQ,aAAa;IACrD,aAAa,EAAE,OAAO,CAAA;gBAEV,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,OAAO;CASpD;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,aAAa,CAEtE;AAED;;;;GAIG;AACH,MAAM,MAAM,iBAAiB,GACzB,wBAAwB,GACxB,sBAAsB,GACtB,qBAAqB,GACrB,8BAA8B,GAC9B,kCAAkC,GAClC,mCAAmC,GACnC,6DAA6D,GAC7D,uDAAuD,GACvD,2CAA2C,GAC3C,uDAAuD,GACvD,+CAA+C,GAC/C,sCAAsC,CAAA;AAE1C;;;;;;;;GAQG;AACH,wBAAgB,yBAAyB,CAAC,EACxC,KAAK,EACL,OAAO,GACR,EAAE;IACD,KAAK,EAAE,KAAK,CAAA;IACZ,OAAO,EAAE,UAAU,CAAC,yBAAyB,EAAE,WAAW,CAAC,GAAG;QAC5D,SAAS,EAAE,wCAAwC,CAAA;KACpD,CAAA;CACF,GAAG,aAAa,CA8HhB;AAED;;;;;;;;GAQG;AACH,wBAAgB,2BAA2B,CAAC,EAC1C,KAAK,EACL,OAAO,GACR,EAAE;IACD,KAAK,EAAE,KAAK,CAAA;IACZ,OAAO,EAAE,UAAU,CAAC,wBAAwB,EAAE,WAAW,CAAC,GAAG;QAC3D,SAAS,EAAE,uCAAuC,CAAA;KACnD,CAAA;CACF,GAAG,aAAa,CA2DhB"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/webauthn.errors.js b/backend/node_modules/@supabase/auth-js/dist/main/lib/webauthn.errors.js new file mode 100644 index 0000000..3987ae5 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/webauthn.errors.js @@ -0,0 +1,265 @@ +"use strict"; +/* eslint-disable @typescript-eslint/ban-ts-comment */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WebAuthnUnknownError = exports.WebAuthnError = void 0; +exports.isWebAuthnError = isWebAuthnError; +exports.identifyRegistrationError = identifyRegistrationError; +exports.identifyAuthenticationError = identifyAuthenticationError; +const webauthn_1 = require("./webauthn"); +/** + * A custom Error used to return a more nuanced error detailing _why_ one of the eight documented + * errors in the spec was raised after calling `navigator.credentials.create()` or + * `navigator.credentials.get()`: + * + * - `AbortError` + * - `ConstraintError` + * - `InvalidStateError` + * - `NotAllowedError` + * - `NotSupportedError` + * - `SecurityError` + * - `TypeError` + * - `UnknownError` + * + * Error messages were determined through investigation of the spec to determine under which + * scenarios a given error would be raised. + */ +class WebAuthnError extends Error { + constructor({ message, code, cause, name, }) { + var _a; + // @ts-ignore: help Rollup understand that `cause` is okay to set + super(message, { cause }); + this.__isWebAuthnError = true; + this.name = (_a = name !== null && name !== void 0 ? name : (cause instanceof Error ? cause.name : undefined)) !== null && _a !== void 0 ? _a : 'Unknown Error'; + this.code = code; + } +} +exports.WebAuthnError = WebAuthnError; +/** + * Error class for unknown WebAuthn errors. + * Wraps unexpected errors that don't match known WebAuthn error conditions. + */ +class WebAuthnUnknownError extends WebAuthnError { + constructor(message, originalError) { + super({ + code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY', + cause: originalError, + message, + }); + this.name = 'WebAuthnUnknownError'; + this.originalError = originalError; + } +} +exports.WebAuthnUnknownError = WebAuthnUnknownError; +/** + * Type guard to check if an error is a WebAuthnError. + * @param {unknown} error - The error to check + * @returns {boolean} True if the error is a WebAuthnError + */ +function isWebAuthnError(error) { + return typeof error === 'object' && error !== null && '__isWebAuthnError' in error; +} +/** + * Attempt to intuit _why_ an error was raised after calling `navigator.credentials.create()`. + * Maps browser errors to specific WebAuthn error codes for better debugging. + * @param {Object} params - Error identification parameters + * @param {Error} params.error - The error thrown by the browser + * @param {CredentialCreationOptions} params.options - The options passed to credentials.create() + * @returns {WebAuthnError} A WebAuthnError with a specific error code + * @see {@link https://w3c.github.io/webauthn/#sctn-createCredential W3C WebAuthn Spec - Create Credential} + */ +function identifyRegistrationError({ error, options, }) { + var _a, _b, _c; + const { publicKey } = options; + if (!publicKey) { + throw Error('options was missing required publicKey property'); + } + if (error.name === 'AbortError') { + if (options.signal instanceof AbortSignal) { + // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 16) + return new WebAuthnError({ + message: 'Registration ceremony was sent an abort signal', + code: 'ERROR_CEREMONY_ABORTED', + cause: error, + }); + } + } + else if (error.name === 'ConstraintError') { + if (((_a = publicKey.authenticatorSelection) === null || _a === void 0 ? void 0 : _a.requireResidentKey) === true) { + // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 4) + return new WebAuthnError({ + message: 'Discoverable credentials were required but no available authenticator supported it', + code: 'ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT', + cause: error, + }); + } + else if ( + // @ts-ignore: `mediation` doesn't yet exist on CredentialCreationOptions but it's possible as of Sept 2024 + options.mediation === 'conditional' && + ((_b = publicKey.authenticatorSelection) === null || _b === void 0 ? void 0 : _b.userVerification) === 'required') { + // https://w3c.github.io/webauthn/#sctn-createCredential (Step 22.4) + return new WebAuthnError({ + message: 'User verification was required during automatic registration but it could not be performed', + code: 'ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE', + cause: error, + }); + } + else if (((_c = publicKey.authenticatorSelection) === null || _c === void 0 ? void 0 : _c.userVerification) === 'required') { + // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 5) + return new WebAuthnError({ + message: 'User verification was required but no available authenticator supported it', + code: 'ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT', + cause: error, + }); + } + } + else if (error.name === 'InvalidStateError') { + // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 20) + // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 3) + return new WebAuthnError({ + message: 'The authenticator was previously registered', + code: 'ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED', + cause: error, + }); + } + else if (error.name === 'NotAllowedError') { + /** + * Pass the error directly through. Platforms are overloading this error beyond what the spec + * defines and we don't want to overwrite potentially useful error messages. + */ + return new WebAuthnError({ + message: error.message, + code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY', + cause: error, + }); + } + else if (error.name === 'NotSupportedError') { + const validPubKeyCredParams = publicKey.pubKeyCredParams.filter((param) => param.type === 'public-key'); + if (validPubKeyCredParams.length === 0) { + // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 10) + return new WebAuthnError({ + message: 'No entry in pubKeyCredParams was of type "public-key"', + code: 'ERROR_MALFORMED_PUBKEYCREDPARAMS', + cause: error, + }); + } + // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 2) + return new WebAuthnError({ + message: 'No available authenticator supported any of the specified pubKeyCredParams algorithms', + code: 'ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG', + cause: error, + }); + } + else if (error.name === 'SecurityError') { + const effectiveDomain = window.location.hostname; + if (!(0, webauthn_1.isValidDomain)(effectiveDomain)) { + // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 7) + return new WebAuthnError({ + message: `${window.location.hostname} is an invalid domain`, + code: 'ERROR_INVALID_DOMAIN', + cause: error, + }); + } + else if (publicKey.rp.id !== effectiveDomain) { + // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 8) + return new WebAuthnError({ + message: `The RP ID "${publicKey.rp.id}" is invalid for this domain`, + code: 'ERROR_INVALID_RP_ID', + cause: error, + }); + } + } + else if (error.name === 'TypeError') { + if (publicKey.user.id.byteLength < 1 || publicKey.user.id.byteLength > 64) { + // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 5) + return new WebAuthnError({ + message: 'User ID was not between 1 and 64 characters', + code: 'ERROR_INVALID_USER_ID_LENGTH', + cause: error, + }); + } + } + else if (error.name === 'UnknownError') { + // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 1) + // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 8) + return new WebAuthnError({ + message: 'The authenticator was unable to process the specified options, or could not create a new credential', + code: 'ERROR_AUTHENTICATOR_GENERAL_ERROR', + cause: error, + }); + } + return new WebAuthnError({ + message: 'a Non-Webauthn related error has occurred', + code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY', + cause: error, + }); +} +/** + * Attempt to intuit _why_ an error was raised after calling `navigator.credentials.get()`. + * Maps browser errors to specific WebAuthn error codes for better debugging. + * @param {Object} params - Error identification parameters + * @param {Error} params.error - The error thrown by the browser + * @param {CredentialRequestOptions} params.options - The options passed to credentials.get() + * @returns {WebAuthnError} A WebAuthnError with a specific error code + * @see {@link https://w3c.github.io/webauthn/#sctn-getAssertion W3C WebAuthn Spec - Get Assertion} + */ +function identifyAuthenticationError({ error, options, }) { + const { publicKey } = options; + if (!publicKey) { + throw Error('options was missing required publicKey property'); + } + if (error.name === 'AbortError') { + if (options.signal instanceof AbortSignal) { + // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 16) + return new WebAuthnError({ + message: 'Authentication ceremony was sent an abort signal', + code: 'ERROR_CEREMONY_ABORTED', + cause: error, + }); + } + } + else if (error.name === 'NotAllowedError') { + /** + * Pass the error directly through. Platforms are overloading this error beyond what the spec + * defines and we don't want to overwrite potentially useful error messages. + */ + return new WebAuthnError({ + message: error.message, + code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY', + cause: error, + }); + } + else if (error.name === 'SecurityError') { + const effectiveDomain = window.location.hostname; + if (!(0, webauthn_1.isValidDomain)(effectiveDomain)) { + // https://www.w3.org/TR/webauthn-2/#sctn-discover-from-external-source (Step 5) + return new WebAuthnError({ + message: `${window.location.hostname} is an invalid domain`, + code: 'ERROR_INVALID_DOMAIN', + cause: error, + }); + } + else if (publicKey.rpId !== effectiveDomain) { + // https://www.w3.org/TR/webauthn-2/#sctn-discover-from-external-source (Step 6) + return new WebAuthnError({ + message: `The RP ID "${publicKey.rpId}" is invalid for this domain`, + code: 'ERROR_INVALID_RP_ID', + cause: error, + }); + } + } + else if (error.name === 'UnknownError') { + // https://www.w3.org/TR/webauthn-2/#sctn-op-get-assertion (Step 1) + // https://www.w3.org/TR/webauthn-2/#sctn-op-get-assertion (Step 12) + return new WebAuthnError({ + message: 'The authenticator was unable to process the specified options, or could not create a new assertion signature', + code: 'ERROR_AUTHENTICATOR_GENERAL_ERROR', + cause: error, + }); + } + return new WebAuthnError({ + message: 'a Non-Webauthn related error has occurred', + code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY', + cause: error, + }); +} +//# sourceMappingURL=webauthn.errors.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/webauthn.errors.js.map b/backend/node_modules/@supabase/auth-js/dist/main/lib/webauthn.errors.js.map new file mode 100644 index 0000000..182a20c --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/webauthn.errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"webauthn.errors.js","sourceRoot":"","sources":["../../../src/lib/webauthn.errors.ts"],"names":[],"mappings":";AAAA,sDAAsD;;;AAwEtD,0CAEC;AA8BD,8DAsIC;AAWD,kEAmEC;AAzTD,yCAA0C;AAM1C;;;;;;;;;;;;;;;;GAgBG;AACH,MAAa,aAAc,SAAQ,KAAK;IAKtC,YAAY,EACV,OAAO,EACP,IAAI,EACJ,KAAK,EACL,IAAI,GAML;;QACC,iEAAiE;QACjE,KAAK,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,CAAC,CAAA;QAdjB,sBAAiB,GAAG,IAAI,CAAA;QAehC,IAAI,CAAC,IAAI,GAAG,MAAA,IAAI,aAAJ,IAAI,cAAJ,IAAI,GAAI,CAAC,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,mCAAI,eAAe,CAAA;QACxF,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;IAClB,CAAC;CACF;AArBD,sCAqBC;AAED;;;GAGG;AACH,MAAa,oBAAqB,SAAQ,aAAa;IAGrD,YAAY,OAAe,EAAE,aAAsB;QACjD,KAAK,CAAC;YACJ,IAAI,EAAE,sCAAsC;YAC5C,KAAK,EAAE,aAAa;YACpB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AAG,MAAM,CAAC,QAAQ,CAAC,QAAQ,uBAAuB;gBAC3D,IAAI,EAAE,sBAAsB;gBAC5B,KAAK,EAAE,KAAK;aACb,CAAC,CAAA;QACJ,CAAC;aAAM,IAAI,SAAS,CAAC,IAAI,KAAK,eAAe,EAAE,CAAC;YAC9C,gFAAgF;YAChF,OAAO,IAAI,aAAa,CAAC;gBACvB,OAAO,EAAE,cAAc,SAAS,CAAC,IAAI,8BAA8B;gBACnE,IAAI,EAAE,qBAAqB;gBAC3B,KAAK,EAAE,KAAK;aACb,CAAC,CAAA;QACJ,CAAC;IACH,CAAC;SAAM,IAAI,KAAK,CAAC,IAAI,KAAK,cAAc,EAAE,CAAC;QACzC,mEAAmE;QACnE,oEAAoE;QACpE,OAAO,IAAI,aAAa,CAAC;YACvB,OAAO,EACL,8GAA8G;YAChH,IAAI,EAAE,mCAAmC;YACzC,KAAK,EAAE,KAAK;SACb,CAAC,CAAA;IACJ,CAAC;IAED,OAAO,IAAI,aAAa,CAAC;QACvB,OAAO,EAAE,2CAA2C;QACpD,IAAI,EAAE,sCAAsC;QAC5C,KAAK,EAAE,KAAK;KACb,CAAC,CAAA;AACJ,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/webauthn.js b/backend/node_modules/@supabase/auth-js/dist/main/lib/webauthn.js new file mode 100644 index 0000000..3be70ad --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/webauthn.js @@ -0,0 +1,693 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WebAuthnApi = exports.DEFAULT_REQUEST_OPTIONS = exports.DEFAULT_CREATION_OPTIONS = exports.webAuthnAbortService = exports.WebAuthnAbortService = exports.identifyAuthenticationError = exports.identifyRegistrationError = exports.isWebAuthnError = exports.WebAuthnError = void 0; +exports.deserializeCredentialCreationOptions = deserializeCredentialCreationOptions; +exports.deserializeCredentialRequestOptions = deserializeCredentialRequestOptions; +exports.serializeCredentialCreationResponse = serializeCredentialCreationResponse; +exports.serializeCredentialRequestResponse = serializeCredentialRequestResponse; +exports.isValidDomain = isValidDomain; +exports.createCredential = createCredential; +exports.getCredential = getCredential; +exports.mergeCredentialCreationOptions = mergeCredentialCreationOptions; +exports.mergeCredentialRequestOptions = mergeCredentialRequestOptions; +const tslib_1 = require("tslib"); +const base64url_1 = require("./base64url"); +const errors_1 = require("./errors"); +const helpers_1 = require("./helpers"); +const webauthn_errors_1 = require("./webauthn.errors"); +Object.defineProperty(exports, "identifyAuthenticationError", { enumerable: true, get: function () { return webauthn_errors_1.identifyAuthenticationError; } }); +Object.defineProperty(exports, "identifyRegistrationError", { enumerable: true, get: function () { return webauthn_errors_1.identifyRegistrationError; } }); +Object.defineProperty(exports, "isWebAuthnError", { enumerable: true, get: function () { return webauthn_errors_1.isWebAuthnError; } }); +Object.defineProperty(exports, "WebAuthnError", { enumerable: true, get: function () { return webauthn_errors_1.WebAuthnError; } }); +/** + * WebAuthn abort service to manage ceremony cancellation. + * Ensures only one WebAuthn ceremony is active at a time to prevent "operation already in progress" errors. + * + * @experimental This class is experimental and may change in future releases + * @see {@link https://w3c.github.io/webauthn/#sctn-automation-webdriver-capability W3C WebAuthn Spec - Aborting Ceremonies} + */ +class WebAuthnAbortService { + /** + * Create an abort signal for a new WebAuthn operation. + * Automatically cancels any existing operation. + * + * @returns {AbortSignal} Signal to pass to navigator.credentials.create() or .get() + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal MDN - AbortSignal} + */ + createNewAbortSignal() { + // Abort any existing calls to navigator.credentials.create() or navigator.credentials.get() + if (this.controller) { + const abortError = new Error('Cancelling existing WebAuthn API call for new one'); + abortError.name = 'AbortError'; + this.controller.abort(abortError); + } + const newController = new AbortController(); + this.controller = newController; + return newController.signal; + } + /** + * Manually cancel the current WebAuthn operation. + * Useful for cleaning up when user cancels or navigates away. + * + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort MDN - AbortController.abort} + */ + cancelCeremony() { + if (this.controller) { + const abortError = new Error('Manually cancelling existing WebAuthn API call'); + abortError.name = 'AbortError'; + this.controller.abort(abortError); + this.controller = undefined; + } + } +} +exports.WebAuthnAbortService = WebAuthnAbortService; +/** + * Singleton instance to ensure only one WebAuthn ceremony is active at a time. + * This prevents "operation already in progress" errors when retrying WebAuthn operations. + * + * @experimental This instance is experimental and may change in future releases + */ +exports.webAuthnAbortService = new WebAuthnAbortService(); +/** + * Convert base64url encoded strings in WebAuthn credential creation options to ArrayBuffers + * as required by the WebAuthn browser API. + * Supports both native WebAuthn Level 3 parseCreationOptionsFromJSON and manual fallback. + * + * @param {ServerCredentialCreationOptions} options - JSON options from server with base64url encoded fields + * @returns {PublicKeyCredentialCreationOptionsFuture} Options ready for navigator.credentials.create() + * @see {@link https://w3c.github.io/webauthn/#sctn-parseCreationOptionsFromJSON W3C WebAuthn Spec - parseCreationOptionsFromJSON} + */ +function deserializeCredentialCreationOptions(options) { + if (!options) { + throw new Error('Credential creation options are required'); + } + // Check if the native parseCreationOptionsFromJSON method is available + if (typeof PublicKeyCredential !== 'undefined' && + 'parseCreationOptionsFromJSON' in PublicKeyCredential && + typeof PublicKeyCredential + .parseCreationOptionsFromJSON === 'function') { + // Use the native WebAuthn Level 3 method + return PublicKeyCredential.parseCreationOptionsFromJSON( + /** we assert the options here as typescript still doesn't know about future webauthn types */ + options); + } + // Fallback to manual parsing for browsers that don't support the native method + // Destructure to separate fields that need transformation + const { challenge: challengeStr, user: userOpts, excludeCredentials } = options, restOptions = tslib_1.__rest(options + // Convert challenge from base64url to ArrayBuffer + , ["challenge", "user", "excludeCredentials"]); + // Convert challenge from base64url to ArrayBuffer + const challenge = (0, base64url_1.base64UrlToUint8Array)(challengeStr).buffer; + // Convert user.id from base64url to ArrayBuffer + const user = Object.assign(Object.assign({}, userOpts), { id: (0, base64url_1.base64UrlToUint8Array)(userOpts.id).buffer }); + // Build the result object + const result = Object.assign(Object.assign({}, restOptions), { challenge, + user }); + // Only add excludeCredentials if it exists + if (excludeCredentials && excludeCredentials.length > 0) { + result.excludeCredentials = new Array(excludeCredentials.length); + for (let i = 0; i < excludeCredentials.length; i++) { + const cred = excludeCredentials[i]; + result.excludeCredentials[i] = Object.assign(Object.assign({}, cred), { id: (0, base64url_1.base64UrlToUint8Array)(cred.id).buffer, type: cred.type || 'public-key', + // Cast transports to handle future transport types like "cable" + transports: cred.transports }); + } + } + return result; +} +/** + * Convert base64url encoded strings in WebAuthn credential request options to ArrayBuffers + * as required by the WebAuthn browser API. + * Supports both native WebAuthn Level 3 parseRequestOptionsFromJSON and manual fallback. + * + * @param {ServerCredentialRequestOptions} options - JSON options from server with base64url encoded fields + * @returns {PublicKeyCredentialRequestOptionsFuture} Options ready for navigator.credentials.get() + * @see {@link https://w3c.github.io/webauthn/#sctn-parseRequestOptionsFromJSON W3C WebAuthn Spec - parseRequestOptionsFromJSON} + */ +function deserializeCredentialRequestOptions(options) { + if (!options) { + throw new Error('Credential request options are required'); + } + // Check if the native parseRequestOptionsFromJSON method is available + if (typeof PublicKeyCredential !== 'undefined' && + 'parseRequestOptionsFromJSON' in PublicKeyCredential && + typeof PublicKeyCredential + .parseRequestOptionsFromJSON === 'function') { + // Use the native WebAuthn Level 3 method + return PublicKeyCredential.parseRequestOptionsFromJSON(options); + } + // Fallback to manual parsing for browsers that don't support the native method + // Destructure to separate fields that need transformation + const { challenge: challengeStr, allowCredentials } = options, restOptions = tslib_1.__rest(options + // Convert challenge from base64url to ArrayBuffer + , ["challenge", "allowCredentials"]); + // Convert challenge from base64url to ArrayBuffer + const challenge = (0, base64url_1.base64UrlToUint8Array)(challengeStr).buffer; + // Build the result object + const result = Object.assign(Object.assign({}, restOptions), { challenge }); + // Only add allowCredentials if it exists + if (allowCredentials && allowCredentials.length > 0) { + result.allowCredentials = new Array(allowCredentials.length); + for (let i = 0; i < allowCredentials.length; i++) { + const cred = allowCredentials[i]; + result.allowCredentials[i] = Object.assign(Object.assign({}, cred), { id: (0, base64url_1.base64UrlToUint8Array)(cred.id).buffer, type: cred.type || 'public-key', + // Cast transports to handle future transport types like "cable" + transports: cred.transports }); + } + } + return result; +} +/** + * Convert a registration/enrollment credential response to server format. + * Serializes binary fields to base64url for JSON transmission. + * Supports both native WebAuthn Level 3 toJSON and manual fallback. + * + * @param {RegistrationCredential} credential - Credential from navigator.credentials.create() + * @returns {RegistrationResponseJSON} JSON-serializable credential for server + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-tojson W3C WebAuthn Spec - toJSON} + */ +function serializeCredentialCreationResponse(credential) { + var _a; + // Check if the credential instance has the toJSON method + if ('toJSON' in credential && typeof credential.toJSON === 'function') { + // Use the native WebAuthn Level 3 method + return credential.toJSON(); + } + const credentialWithAttachment = credential; + return { + id: credential.id, + rawId: credential.id, + response: { + attestationObject: (0, base64url_1.bytesToBase64URL)(new Uint8Array(credential.response.attestationObject)), + clientDataJSON: (0, base64url_1.bytesToBase64URL)(new Uint8Array(credential.response.clientDataJSON)), + }, + type: 'public-key', + clientExtensionResults: credential.getClientExtensionResults(), + // Convert null to undefined and cast to AuthenticatorAttachment type + authenticatorAttachment: ((_a = credentialWithAttachment.authenticatorAttachment) !== null && _a !== void 0 ? _a : undefined), + }; +} +/** + * Convert an authentication/verification credential response to server format. + * Serializes binary fields to base64url for JSON transmission. + * Supports both native WebAuthn Level 3 toJSON and manual fallback. + * + * @param {AuthenticationCredential} credential - Credential from navigator.credentials.get() + * @returns {AuthenticationResponseJSON} JSON-serializable credential for server + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-tojson W3C WebAuthn Spec - toJSON} + */ +function serializeCredentialRequestResponse(credential) { + var _a; + // Check if the credential instance has the toJSON method + if ('toJSON' in credential && typeof credential.toJSON === 'function') { + // Use the native WebAuthn Level 3 method + return credential.toJSON(); + } + // Fallback to manual conversion for browsers that don't support toJSON + // Access authenticatorAttachment via type assertion to handle TypeScript version differences + // @simplewebauthn/types includes this property but base TypeScript 4.7.4 doesn't + const credentialWithAttachment = credential; + const clientExtensionResults = credential.getClientExtensionResults(); + const assertionResponse = credential.response; + return { + id: credential.id, + rawId: credential.id, // W3C spec expects rawId to match id for JSON format + response: { + authenticatorData: (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.authenticatorData)), + clientDataJSON: (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.clientDataJSON)), + signature: (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.signature)), + userHandle: assertionResponse.userHandle + ? (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.userHandle)) + : undefined, + }, + type: 'public-key', + clientExtensionResults, + // Convert null to undefined and cast to AuthenticatorAttachment type + authenticatorAttachment: ((_a = credentialWithAttachment.authenticatorAttachment) !== null && _a !== void 0 ? _a : undefined), + }; +} +/** + * A simple test to determine if a hostname is a properly-formatted domain name. + * Considers localhost valid for development environments. + * + * A "valid domain" is defined here: https://url.spec.whatwg.org/#valid-domain + * + * Regex sourced from here: + * https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch08s15.html + * + * @param {string} hostname - The hostname to validate + * @returns {boolean} True if valid domain or localhost + * @see {@link https://url.spec.whatwg.org/#valid-domain WHATWG URL Spec - Valid Domain} + */ +function isValidDomain(hostname) { + return ( + // Consider localhost valid as well since it's okay wrt Secure Contexts + hostname === 'localhost' || /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(hostname)); +} +/** + * Determine if the browser is capable of WebAuthn. + * Checks for necessary Web APIs: PublicKeyCredential and Credential Management. + * + * @returns {boolean} True if browser supports WebAuthn + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredential#browser_compatibility MDN - PublicKeyCredential Browser Compatibility} + */ +function browserSupportsWebAuthn() { + var _a, _b; + return !!((0, helpers_1.isBrowser)() && + 'PublicKeyCredential' in window && + window.PublicKeyCredential && + 'credentials' in navigator && + typeof ((_a = navigator === null || navigator === void 0 ? void 0 : navigator.credentials) === null || _a === void 0 ? void 0 : _a.create) === 'function' && + typeof ((_b = navigator === null || navigator === void 0 ? void 0 : navigator.credentials) === null || _b === void 0 ? void 0 : _b.get) === 'function'); +} +/** + * Create a WebAuthn credential using the browser's credentials API. + * Wraps navigator.credentials.create() with error handling. + * + * @param {CredentialCreationOptions} options - Options including publicKey parameters + * @returns {Promise>} Created credential or error + * @see {@link https://w3c.github.io/webauthn/#sctn-createCredential W3C WebAuthn Spec - Create Credential} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/create MDN - credentials.create} + */ +async function createCredential(options) { + try { + const response = await navigator.credentials.create( + /** we assert the type here until typescript types are updated */ + options); + if (!response) { + return { + data: null, + error: new webauthn_errors_1.WebAuthnUnknownError('Empty credential response', response), + }; + } + if (!(response instanceof PublicKeyCredential)) { + return { + data: null, + error: new webauthn_errors_1.WebAuthnUnknownError('Browser returned unexpected credential type', response), + }; + } + return { data: response, error: null }; + } + catch (err) { + return { + data: null, + error: (0, webauthn_errors_1.identifyRegistrationError)({ + error: err, + options, + }), + }; + } +} +/** + * Get a WebAuthn credential using the browser's credentials API. + * Wraps navigator.credentials.get() with error handling. + * + * @param {CredentialRequestOptions} options - Options including publicKey parameters + * @returns {Promise>} Retrieved credential or error + * @see {@link https://w3c.github.io/webauthn/#sctn-getAssertion W3C WebAuthn Spec - Get Assertion} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/get MDN - credentials.get} + */ +async function getCredential(options) { + try { + const response = await navigator.credentials.get( + /** we assert the type here until typescript types are updated */ + options); + if (!response) { + return { + data: null, + error: new webauthn_errors_1.WebAuthnUnknownError('Empty credential response', response), + }; + } + if (!(response instanceof PublicKeyCredential)) { + return { + data: null, + error: new webauthn_errors_1.WebAuthnUnknownError('Browser returned unexpected credential type', response), + }; + } + return { data: response, error: null }; + } + catch (err) { + return { + data: null, + error: (0, webauthn_errors_1.identifyAuthenticationError)({ + error: err, + options, + }), + }; + } +} +exports.DEFAULT_CREATION_OPTIONS = { + hints: ['security-key'], + authenticatorSelection: { + authenticatorAttachment: 'cross-platform', + requireResidentKey: false, + /** set to preferred because older yubikeys don't have PIN/Biometric */ + userVerification: 'preferred', + residentKey: 'discouraged', + }, + attestation: 'direct', +}; +exports.DEFAULT_REQUEST_OPTIONS = { + /** set to preferred because older yubikeys don't have PIN/Biometric */ + userVerification: 'preferred', + hints: ['security-key'], + attestation: 'direct', +}; +function deepMerge(...sources) { + const isObject = (val) => val !== null && typeof val === 'object' && !Array.isArray(val); + const isArrayBufferLike = (val) => val instanceof ArrayBuffer || ArrayBuffer.isView(val); + const result = {}; + for (const source of sources) { + if (!source) + continue; + for (const key in source) { + const value = source[key]; + if (value === undefined) + continue; + if (Array.isArray(value)) { + // preserve array reference, including unions like AuthenticatorTransport[] + result[key] = value; + } + else if (isArrayBufferLike(value)) { + result[key] = value; + } + else if (isObject(value)) { + const existing = result[key]; + if (isObject(existing)) { + result[key] = deepMerge(existing, value); + } + else { + result[key] = deepMerge(value); + } + } + else { + result[key] = value; + } + } + } + return result; +} +/** + * Merges WebAuthn credential creation options with overrides. + * Sets sensible defaults for authenticator selection and extensions. + * + * @param {PublicKeyCredentialCreationOptionsFuture} baseOptions - The base options from the server + * @param {PublicKeyCredentialCreationOptionsFuture} overrides - Optional overrides to apply + * @param {string} friendlyName - Optional friendly name for the credential + * @returns {PublicKeyCredentialCreationOptionsFuture} Merged credential creation options + * @see {@link https://w3c.github.io/webauthn/#dictdef-authenticatorselectioncriteria W3C WebAuthn Spec - AuthenticatorSelectionCriteria} + */ +function mergeCredentialCreationOptions(baseOptions, overrides) { + return deepMerge(exports.DEFAULT_CREATION_OPTIONS, baseOptions, overrides || {}); +} +/** + * Merges WebAuthn credential request options with overrides. + * Sets sensible defaults for user verification and hints. + * + * @param {PublicKeyCredentialRequestOptionsFuture} baseOptions - The base options from the server + * @param {PublicKeyCredentialRequestOptionsFuture} overrides - Optional overrides to apply + * @returns {PublicKeyCredentialRequestOptionsFuture} Merged credential request options + * @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialrequestoptions W3C WebAuthn Spec - PublicKeyCredentialRequestOptions} + */ +function mergeCredentialRequestOptions(baseOptions, overrides) { + return deepMerge(exports.DEFAULT_REQUEST_OPTIONS, baseOptions, overrides || {}); +} +/** + * WebAuthn API wrapper for Supabase Auth. + * Provides methods for enrolling, challenging, verifying, authenticating, and registering WebAuthn credentials. + * + * @experimental This API is experimental and may change in future releases + * @see {@link https://w3c.github.io/webauthn/ W3C WebAuthn Specification} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API MDN - Web Authentication API} + */ +class WebAuthnApi { + constructor(client) { + this.client = client; + // Bind all methods so they can be destructured + this.enroll = this._enroll.bind(this); + this.challenge = this._challenge.bind(this); + this.verify = this._verify.bind(this); + this.authenticate = this._authenticate.bind(this); + this.register = this._register.bind(this); + } + /** + * Enroll a new WebAuthn factor. + * Creates an unverified WebAuthn factor that must be verified with a credential. + * + * @experimental This method is experimental and may change in future releases + * @param {Omit} params - Enrollment parameters (friendlyName required) + * @returns {Promise} Enrolled factor details or error + * @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registering a New Credential} + */ + async _enroll(params) { + return this.client.mfa.enroll(Object.assign(Object.assign({}, params), { factorType: 'webauthn' })); + } + /** + * Challenge for WebAuthn credential creation or authentication. + * Combines server challenge with browser credential operations. + * Handles both registration (create) and authentication (request) flows. + * + * @experimental This method is experimental and may change in future releases + * @param {MFAChallengeWebauthnParams & { friendlyName?: string; signal?: AbortSignal }} params - Challenge parameters including factorId + * @param {Object} overrides - Allows you to override the parameters passed to navigator.credentials + * @param {PublicKeyCredentialCreationOptionsFuture} overrides.create - Override options for credential creation + * @param {PublicKeyCredentialRequestOptionsFuture} overrides.request - Override options for credential request + * @returns {Promise} Challenge response with credential or error + * @see {@link https://w3c.github.io/webauthn/#sctn-credential-creation W3C WebAuthn Spec - Credential Creation} + * @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying Assertion} + */ + async _challenge({ factorId, webauthn, friendlyName, signal, }, overrides) { + try { + // Get challenge from server using the client's MFA methods + const { data: challengeResponse, error: challengeError } = await this.client.mfa.challenge({ + factorId, + webauthn, + }); + if (!challengeResponse) { + return { data: null, error: challengeError }; + } + const abortSignal = signal !== null && signal !== void 0 ? signal : exports.webAuthnAbortService.createNewAbortSignal(); + /** webauthn will fail if either of the name/displayname are blank */ + if (challengeResponse.webauthn.type === 'create') { + const { user } = challengeResponse.webauthn.credential_options.publicKey; + if (!user.name) { + user.name = `${user.id}:${friendlyName}`; + } + if (!user.displayName) { + user.displayName = user.name; + } + } + switch (challengeResponse.webauthn.type) { + case 'create': { + const options = mergeCredentialCreationOptions(challengeResponse.webauthn.credential_options.publicKey, overrides === null || overrides === void 0 ? void 0 : overrides.create); + const { data, error } = await createCredential({ + publicKey: options, + signal: abortSignal, + }); + if (data) { + return { + data: { + factorId, + challengeId: challengeResponse.id, + webauthn: { + type: challengeResponse.webauthn.type, + credential_response: data, + }, + }, + error: null, + }; + } + return { data: null, error }; + } + case 'request': { + const options = mergeCredentialRequestOptions(challengeResponse.webauthn.credential_options.publicKey, overrides === null || overrides === void 0 ? void 0 : overrides.request); + const { data, error } = await getCredential(Object.assign(Object.assign({}, challengeResponse.webauthn.credential_options), { publicKey: options, signal: abortSignal })); + if (data) { + return { + data: { + factorId, + challengeId: challengeResponse.id, + webauthn: { + type: challengeResponse.webauthn.type, + credential_response: data, + }, + }, + error: null, + }; + } + return { data: null, error }; + } + } + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + return { + data: null, + error: new errors_1.AuthUnknownError('Unexpected error in challenge', error), + }; + } + } + /** + * Verify a WebAuthn credential with the server. + * Completes the WebAuthn ceremony by sending the credential to the server for verification. + * + * @experimental This method is experimental and may change in future releases + * @param {Object} params - Verification parameters + * @param {string} params.challengeId - ID of the challenge being verified + * @param {string} params.factorId - ID of the WebAuthn factor + * @param {MFAVerifyWebauthnParams['webauthn']} params.webauthn - WebAuthn credential response + * @returns {Promise} Verification result with session or error + * @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying an Authentication Assertion} + * */ + async _verify({ challengeId, factorId, webauthn, }) { + return this.client.mfa.verify({ + factorId, + challengeId, + webauthn: webauthn, + }); + } + /** + * Complete WebAuthn authentication flow. + * Performs challenge and verification in a single operation for existing credentials. + * + * @experimental This method is experimental and may change in future releases + * @param {Object} params - Authentication parameters + * @param {string} params.factorId - ID of the WebAuthn factor to authenticate with + * @param {Object} params.webauthn - WebAuthn configuration + * @param {string} params.webauthn.rpId - Relying Party ID (defaults to current hostname) + * @param {string[]} params.webauthn.rpOrigins - Allowed origins (defaults to current origin) + * @param {AbortSignal} params.webauthn.signal - Optional abort signal + * @param {PublicKeyCredentialRequestOptionsFuture} overrides - Override options for navigator.credentials.get + * @returns {Promise>} Authentication result + * @see {@link https://w3c.github.io/webauthn/#sctn-authentication W3C WebAuthn Spec - Authentication Ceremony} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialRequestOptions MDN - PublicKeyCredentialRequestOptions} + */ + async _authenticate({ factorId, webauthn: { rpId = typeof window !== 'undefined' ? window.location.hostname : undefined, rpOrigins = typeof window !== 'undefined' ? [window.location.origin] : undefined, signal, } = {}, }, overrides) { + if (!rpId) { + return { + data: null, + error: new errors_1.AuthError('rpId is required for WebAuthn authentication'), + }; + } + try { + if (!browserSupportsWebAuthn()) { + return { + data: null, + error: new errors_1.AuthUnknownError('Browser does not support WebAuthn', null), + }; + } + // Get challenge and credential + const { data: challengeResponse, error: challengeError } = await this.challenge({ + factorId, + webauthn: { rpId, rpOrigins }, + signal, + }, { request: overrides }); + if (!challengeResponse) { + return { data: null, error: challengeError }; + } + const { webauthn } = challengeResponse; + // Verify credential + return this._verify({ + factorId, + challengeId: challengeResponse.challengeId, + webauthn: { + type: webauthn.type, + rpId, + rpOrigins, + credential_response: webauthn.credential_response, + }, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + return { + data: null, + error: new errors_1.AuthUnknownError('Unexpected error in authenticate', error), + }; + } + } + /** + * Complete WebAuthn registration flow. + * Performs enrollment, challenge, and verification in a single operation for new credentials. + * + * @experimental This method is experimental and may change in future releases + * @param {Object} params - Registration parameters + * @param {string} params.friendlyName - User-friendly name for the credential + * @param {string} params.rpId - Relying Party ID (defaults to current hostname) + * @param {string[]} params.rpOrigins - Allowed origins (defaults to current origin) + * @param {AbortSignal} params.signal - Optional abort signal + * @param {PublicKeyCredentialCreationOptionsFuture} overrides - Override options for navigator.credentials.create + * @returns {Promise>} Registration result + * @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registration Ceremony} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions MDN - PublicKeyCredentialCreationOptions} + */ + async _register({ friendlyName, webauthn: { rpId = typeof window !== 'undefined' ? window.location.hostname : undefined, rpOrigins = typeof window !== 'undefined' ? [window.location.origin] : undefined, signal, } = {}, }, overrides) { + if (!rpId) { + return { + data: null, + error: new errors_1.AuthError('rpId is required for WebAuthn registration'), + }; + } + try { + if (!browserSupportsWebAuthn()) { + return { + data: null, + error: new errors_1.AuthUnknownError('Browser does not support WebAuthn', null), + }; + } + // Enroll factor + const { data: factor, error: enrollError } = await this._enroll({ + friendlyName, + }); + if (!factor) { + await this.client.mfa + .listFactors() + .then((factors) => { + var _a; + return (_a = factors.data) === null || _a === void 0 ? void 0 : _a.all.find((v) => v.factor_type === 'webauthn' && + v.friendly_name === friendlyName && + v.status !== 'unverified'); + }) + .then((factor) => (factor ? this.client.mfa.unenroll({ factorId: factor === null || factor === void 0 ? void 0 : factor.id }) : void 0)); + return { data: null, error: enrollError }; + } + // Get challenge and create credential + const { data: challengeResponse, error: challengeError } = await this._challenge({ + factorId: factor.id, + friendlyName: factor.friendly_name, + webauthn: { rpId, rpOrigins }, + signal, + }, { + create: overrides, + }); + if (!challengeResponse) { + return { data: null, error: challengeError }; + } + return this._verify({ + factorId: factor.id, + challengeId: challengeResponse.challengeId, + webauthn: { + rpId, + rpOrigins, + type: challengeResponse.webauthn.type, + credential_response: challengeResponse.webauthn.credential_response, + }, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + return { + data: null, + error: new errors_1.AuthUnknownError('Unexpected error in register', error), + }; + } + } +} +exports.WebAuthnApi = WebAuthnApi; +//# sourceMappingURL=webauthn.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/main/lib/webauthn.js.map b/backend/node_modules/@supabase/auth-js/dist/main/lib/webauthn.js.map new file mode 100644 index 0000000..737bc61 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/main/lib/webauthn.js.map @@ -0,0 +1 @@ +{"version":3,"file":"webauthn.js","sourceRoot":"","sources":["../../../src/lib/webauthn.ts"],"names":[],"mappings":";;;AAmHA,oFA4DC;AAWD,kFAkDC;AAiBD,kFA2BC;AAWD,gFAsCC;AAeD,sCAKC;AA6BD,4CAgCC;AAWD,sCAgCC;AAoED,wEAKC;AAWD,sEAKC;;AA7hBD,2CAAqE;AACrE,qCAAmE;AAYnE,uCAAqC;AAcrC,uDAM0B;AAE0C,4GAPlE,6CAA2B,OAOkE;AAAtD,0GANvC,2CAAyB,OAMuC;AAA1C,gGALtB,iCAAe,OAKsB;AAA9B,8FAJP,+BAAa,OAIO;AAItB;;;;;;GAMG;AACH,MAAa,oBAAoB;IAG/B;;;;;;OAMG;IACH,oBAAoB;QAClB,4FAA4F;QAC5F,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;YACpB,MAAM,UAAU,GAAG,IAAI,KAAK,CAAC,mDAAmD,CAAC,CAAA;YACjF,UAAU,CAAC,IAAI,GAAG,YAAY,CAAA;YAC9B,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,UAAU,CAAC,CAAA;QAC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AC;gBACvB,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,CAAA;YAC9B,CAAC;YACD,OAAO;gBACL,IAAI,EAAE,IAAI;gBACV,KAAK,EAAE,IAAI,yBAAgB,CAAC,8BAA8B,EAAE,KAAK,CAAC;aACnE,CAAA;QACH,CAAC;IACH,CAAC;CACF;AA7XD,kCA6XC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/AuthAdminApi.d.ts b/backend/node_modules/@supabase/auth-js/dist/module/AuthAdminApi.d.ts new file mode 100644 index 0000000..aacb97d --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/AuthAdminApi.d.ts @@ -0,0 +1,4 @@ +import GoTrueAdminApi from './GoTrueAdminApi'; +declare const AuthAdminApi: typeof GoTrueAdminApi; +export default AuthAdminApi; +//# sourceMappingURL=AuthAdminApi.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/AuthAdminApi.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/module/AuthAdminApi.d.ts.map new file mode 100644 index 0000000..5c6efa8 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/AuthAdminApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"AuthAdminApi.d.ts","sourceRoot":"","sources":["../../src/AuthAdminApi.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,kBAAkB,CAAA;AAE7C,QAAA,MAAM,YAAY,uBAAiB,CAAA;AAEnC,eAAe,YAAY,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/AuthAdminApi.js b/backend/node_modules/@supabase/auth-js/dist/module/AuthAdminApi.js new file mode 100644 index 0000000..339c7ab --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/AuthAdminApi.js @@ -0,0 +1,4 @@ +import GoTrueAdminApi from './GoTrueAdminApi'; +const AuthAdminApi = GoTrueAdminApi; +export default AuthAdminApi; +//# sourceMappingURL=AuthAdminApi.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/AuthAdminApi.js.map b/backend/node_modules/@supabase/auth-js/dist/module/AuthAdminApi.js.map new file mode 100644 index 0000000..bef3377 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/AuthAdminApi.js.map @@ -0,0 +1 @@ +{"version":3,"file":"AuthAdminApi.js","sourceRoot":"","sources":["../../src/AuthAdminApi.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,kBAAkB,CAAA;AAE7C,MAAM,YAAY,GAAG,cAAc,CAAA;AAEnC,eAAe,YAAY,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/AuthClient.d.ts b/backend/node_modules/@supabase/auth-js/dist/module/AuthClient.d.ts new file mode 100644 index 0000000..596eec9 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/AuthClient.d.ts @@ -0,0 +1,4 @@ +import GoTrueClient from './GoTrueClient'; +declare const AuthClient: typeof GoTrueClient; +export default AuthClient; +//# sourceMappingURL=AuthClient.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/AuthClient.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/module/AuthClient.d.ts.map new file mode 100644 index 0000000..503d802 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/AuthClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"AuthClient.d.ts","sourceRoot":"","sources":["../../src/AuthClient.ts"],"names":[],"mappings":"AAAA,OAAO,YAAY,MAAM,gBAAgB,CAAA;AAEzC,QAAA,MAAM,UAAU,qBAAe,CAAA;AAE/B,eAAe,UAAU,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/AuthClient.js b/backend/node_modules/@supabase/auth-js/dist/module/AuthClient.js new file mode 100644 index 0000000..03bd60d --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/AuthClient.js @@ -0,0 +1,4 @@ +import GoTrueClient from './GoTrueClient'; +const AuthClient = GoTrueClient; +export default AuthClient; +//# sourceMappingURL=AuthClient.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/AuthClient.js.map b/backend/node_modules/@supabase/auth-js/dist/module/AuthClient.js.map new file mode 100644 index 0000000..aebb401 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/AuthClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"AuthClient.js","sourceRoot":"","sources":["../../src/AuthClient.ts"],"names":[],"mappings":"AAAA,OAAO,YAAY,MAAM,gBAAgB,CAAA;AAEzC,MAAM,UAAU,GAAG,YAAY,CAAA;AAE/B,eAAe,UAAU,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/GoTrueAdminApi.d.ts b/backend/node_modules/@supabase/auth-js/dist/module/GoTrueAdminApi.d.ts new file mode 100644 index 0000000..036f90b --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/GoTrueAdminApi.d.ts @@ -0,0 +1,159 @@ +import { Fetch } from './lib/fetch'; +import { AdminUserAttributes, GenerateLinkParams, GenerateLinkResponse, Pagination, User, UserResponse, GoTrueAdminMFAApi, PageParams, SignOutScope, GoTrueAdminOAuthApi } from './lib/types'; +import { AuthError } from './lib/errors'; +export default class GoTrueAdminApi { + /** Contains all MFA administration methods. */ + mfa: GoTrueAdminMFAApi; + /** + * Contains all OAuth client administration methods. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ + oauth: GoTrueAdminOAuthApi; + protected url: string; + protected headers: { + [key: string]: string; + }; + protected fetch: Fetch; + /** + * Creates an admin API client that can be used to manage users and OAuth clients. + * + * @example + * ```ts + * import { GoTrueAdminApi } from '@supabase/auth-js' + * + * const admin = new GoTrueAdminApi({ + * url: 'https://xyzcompany.supabase.co/auth/v1', + * headers: { Authorization: `Bearer ${process.env.SUPABASE_SERVICE_ROLE_KEY}` }, + * }) + * ``` + */ + constructor({ url, headers, fetch, }: { + url: string; + headers?: { + [key: string]: string; + }; + fetch?: Fetch; + }); + /** + * Removes a logged-in session. + * @param jwt A valid, logged-in JWT. + * @param scope The logout sope. + */ + signOut(jwt: string, scope?: SignOutScope): Promise<{ + data: null; + error: AuthError | null; + }>; + /** + * Sends an invite link to an email address. + * @param email The email address of the user. + * @param options Additional options to be included when inviting. + */ + inviteUserByEmail(email: string, options?: { + /** A custom data object to store additional metadata about the user. This maps to the `auth.users.user_metadata` column. */ + data?: object; + /** The URL which will be appended to the email link sent to the user's email address. Once clicked the user will end up on this URL. */ + redirectTo?: string; + }): Promise; + /** + * Generates email links and OTPs to be sent via a custom email provider. + * @param email The user's email. + * @param options.password User password. For signup only. + * @param options.data Optional user metadata. For signup only. + * @param options.redirectTo The redirect url which should be appended to the generated link + */ + generateLink(params: GenerateLinkParams): Promise; + /** + * Creates a new user. + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + createUser(attributes: AdminUserAttributes): Promise; + /** + * Get a list of users. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + * @param params An object which supports `page` and `perPage` as numbers, to alter the paginated results. + */ + listUsers(params?: PageParams): Promise<{ + data: { + users: User[]; + aud: string; + } & Pagination; + error: null; + } | { + data: { + users: []; + }; + error: AuthError; + }>; + /** + * Get user by id. + * + * @param uid The user's unique identifier + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + getUserById(uid: string): Promise; + /** + * Updates the user data. + * + * @param attributes The data you want to update. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + updateUserById(uid: string, attributes: AdminUserAttributes): Promise; + /** + * Delete a user. Requires a `service_role` key. + * + * @param id The user id you want to remove. + * @param shouldSoftDelete If true, then the user will be soft-deleted from the auth schema. Soft deletion allows user identification from the hashed user ID but is not reversible. + * Defaults to false for backward compatibility. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + deleteUser(id: string, shouldSoftDelete?: boolean): Promise; + private _listFactors; + private _deleteFactor; + /** + * Lists all OAuth clients with optional pagination. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + private _listOAuthClients; + /** + * Creates a new OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + private _createOAuthClient; + /** + * Gets details of a specific OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + private _getOAuthClient; + /** + * Updates an existing OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + private _updateOAuthClient; + /** + * Deletes an OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + private _deleteOAuthClient; + /** + * Regenerates the secret for an OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + private _regenerateOAuthClientSecret; +} +//# sourceMappingURL=GoTrueAdminApi.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/GoTrueAdminApi.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/module/GoTrueAdminApi.d.ts.map new file mode 100644 index 0000000..88941da --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/GoTrueAdminApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"GoTrueAdminApi.d.ts","sourceRoot":"","sources":["../../src/GoTrueAdminApi.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,EAKN,MAAM,aAAa,CAAA;AAEpB,OAAO,EACL,mBAAmB,EACnB,kBAAkB,EAClB,oBAAoB,EACpB,UAAU,EACV,IAAI,EACJ,YAAY,EACZ,iBAAiB,EAKjB,UAAU,EAEV,YAAY,EACZ,mBAAmB,EAKpB,MAA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AAE,IAAI,EAAE;YAAE,KAAK,EAAE,IAAI,EAAE,CAAC;YAAC,GAAG,EAAE,MAAM,CAAA;SAAE,GAAG,UAAU,CAAC;QAAC,KAAK,EAAE,IAAI,CAAA;KAAE,GAClE;QAAE,IAAI,EAAE;YAAE,KAAK,EAAE,EAAE,CAAA;SAAE,CAAC;QAAC,KAAK,EAAE,SAAS,CAAA;KAAE,CAC5C;IAmCD;;;;;;OAMG;IACG,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,CAAC;IAiBrD;;;;;;OAMG;IACG,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,UAAU,EAAE,mBAAmB,GAAG,OAAO,CAAC,YAAY,CAAC;IAkBzF;;;;;;;;OAQG;IACG,UAAU,CAAC,EAAE,EAAE,MAAM,EAAE,gBAAgB,UAAQ,GAAG,OAAO,CAAC,YAAY,CAAC;YAoB/D,YAAY;YA2BZ,aAAa;IA0B3B;;;;;OAKG;YACW,iBAAiB;IAmC/B;;;;;OAKG;YACW,kBAAkB;IAkBhC;;;;;OAKG;YACW,eAAe;IAiB7B;;;;;OAKG;YACW,kBAAkB;IAqBhC;;;;;OAKG;YACW,kBAAkB;IAkBhC;;;;;OAKG;YACW,4BAA4B;CAqB3C"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/GoTrueAdminApi.js b/backend/node_modules/@supabase/auth-js/dist/module/GoTrueAdminApi.js new file mode 100644 index 0000000..1a4e22b --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/GoTrueAdminApi.js @@ -0,0 +1,438 @@ +import { __rest } from "tslib"; +import { _generateLinkResponse, _noResolveJsonResponse, _request, _userResponse, } from './lib/fetch'; +import { resolveFetch, validateUUID } from './lib/helpers'; +import { SIGN_OUT_SCOPES, } from './lib/types'; +import { isAuthError } from './lib/errors'; +export default class GoTrueAdminApi { + /** + * Creates an admin API client that can be used to manage users and OAuth clients. + * + * @example + * ```ts + * import { GoTrueAdminApi } from '@supabase/auth-js' + * + * const admin = new GoTrueAdminApi({ + * url: 'https://xyzcompany.supabase.co/auth/v1', + * headers: { Authorization: `Bearer ${process.env.SUPABASE_SERVICE_ROLE_KEY}` }, + * }) + * ``` + */ + constructor({ url = '', headers = {}, fetch, }) { + this.url = url; + this.headers = headers; + this.fetch = resolveFetch(fetch); + this.mfa = { + listFactors: this._listFactors.bind(this), + deleteFactor: this._deleteFactor.bind(this), + }; + this.oauth = { + listClients: this._listOAuthClients.bind(this), + createClient: this._createOAuthClient.bind(this), + getClient: this._getOAuthClient.bind(this), + updateClient: this._updateOAuthClient.bind(this), + deleteClient: this._deleteOAuthClient.bind(this), + regenerateClientSecret: this._regenerateOAuthClientSecret.bind(this), + }; + } + /** + * Removes a logged-in session. + * @param jwt A valid, logged-in JWT. + * @param scope The logout sope. + */ + async signOut(jwt, scope = SIGN_OUT_SCOPES[0]) { + if (SIGN_OUT_SCOPES.indexOf(scope) < 0) { + throw new Error(`@supabase/auth-js: Parameter scope must be one of ${SIGN_OUT_SCOPES.join(', ')}`); + } + try { + await _request(this.fetch, 'POST', `${this.url}/logout?scope=${scope}`, { + headers: this.headers, + jwt, + noResolveJson: true, + }); + return { data: null, error: null }; + } + catch (error) { + if (isAuthError(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Sends an invite link to an email address. + * @param email The email address of the user. + * @param options Additional options to be included when inviting. + */ + async inviteUserByEmail(email, options = {}) { + try { + return await _request(this.fetch, 'POST', `${this.url}/invite`, { + body: { email, data: options.data }, + headers: this.headers, + redirectTo: options.redirectTo, + xform: _userResponse, + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + /** + * Generates email links and OTPs to be sent via a custom email provider. + * @param email The user's email. + * @param options.password User password. For signup only. + * @param options.data Optional user metadata. For signup only. + * @param options.redirectTo The redirect url which should be appended to the generated link + */ + async generateLink(params) { + try { + const { options } = params, rest = __rest(params, ["options"]); + const body = Object.assign(Object.assign({}, rest), options); + if ('newEmail' in rest) { + // replace newEmail with new_email in request body + body.new_email = rest === null || rest === void 0 ? void 0 : rest.newEmail; + delete body['newEmail']; + } + return await _request(this.fetch, 'POST', `${this.url}/admin/generate_link`, { + body: body, + headers: this.headers, + xform: _generateLinkResponse, + redirectTo: options === null || options === void 0 ? void 0 : options.redirectTo, + }); + } + catch (error) { + if (isAuthError(error)) { + return { + data: { + properties: null, + user: null, + }, + error, + }; + } + throw error; + } + } + // User Admin API + /** + * Creates a new user. + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async createUser(attributes) { + try { + return await _request(this.fetch, 'POST', `${this.url}/admin/users`, { + body: attributes, + headers: this.headers, + xform: _userResponse, + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + /** + * Get a list of users. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + * @param params An object which supports `page` and `perPage` as numbers, to alter the paginated results. + */ + async listUsers(params) { + var _a, _b, _c, _d, _e, _f, _g; + try { + const pagination = { nextPage: null, lastPage: 0, total: 0 }; + const response = await _request(this.fetch, 'GET', `${this.url}/admin/users`, { + headers: this.headers, + noResolveJson: true, + query: { + page: (_b = (_a = params === null || params === void 0 ? void 0 : params.page) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : '', + per_page: (_d = (_c = params === null || params === void 0 ? void 0 : params.perPage) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : '', + }, + xform: _noResolveJsonResponse, + }); + if (response.error) + throw response.error; + const users = await response.json(); + const total = (_e = response.headers.get('x-total-count')) !== null && _e !== void 0 ? _e : 0; + const links = (_g = (_f = response.headers.get('link')) === null || _f === void 0 ? void 0 : _f.split(',')) !== null && _g !== void 0 ? _g : []; + if (links.length > 0) { + links.forEach((link) => { + const page = parseInt(link.split(';')[0].split('=')[1].substring(0, 1)); + const rel = JSON.parse(link.split(';')[1].split('=')[1]); + pagination[`${rel}Page`] = page; + }); + pagination.total = parseInt(total); + } + return { data: Object.assign(Object.assign({}, users), pagination), error: null }; + } + catch (error) { + if (isAuthError(error)) { + return { data: { users: [] }, error }; + } + throw error; + } + } + /** + * Get user by id. + * + * @param uid The user's unique identifier + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async getUserById(uid) { + validateUUID(uid); + try { + return await _request(this.fetch, 'GET', `${this.url}/admin/users/${uid}`, { + headers: this.headers, + xform: _userResponse, + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + /** + * Updates the user data. + * + * @param attributes The data you want to update. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async updateUserById(uid, attributes) { + validateUUID(uid); + try { + return await _request(this.fetch, 'PUT', `${this.url}/admin/users/${uid}`, { + body: attributes, + headers: this.headers, + xform: _userResponse, + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + /** + * Delete a user. Requires a `service_role` key. + * + * @param id The user id you want to remove. + * @param shouldSoftDelete If true, then the user will be soft-deleted from the auth schema. Soft deletion allows user identification from the hashed user ID but is not reversible. + * Defaults to false for backward compatibility. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async deleteUser(id, shouldSoftDelete = false) { + validateUUID(id); + try { + return await _request(this.fetch, 'DELETE', `${this.url}/admin/users/${id}`, { + headers: this.headers, + body: { + should_soft_delete: shouldSoftDelete, + }, + xform: _userResponse, + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + async _listFactors(params) { + validateUUID(params.userId); + try { + const { data, error } = await _request(this.fetch, 'GET', `${this.url}/admin/users/${params.userId}/factors`, { + headers: this.headers, + xform: (factors) => { + return { data: { factors }, error: null }; + }, + }); + return { data, error }; + } + catch (error) { + if (isAuthError(error)) { + return { data: null, error }; + } + throw error; + } + } + async _deleteFactor(params) { + validateUUID(params.userId); + validateUUID(params.id); + try { + const data = await _request(this.fetch, 'DELETE', `${this.url}/admin/users/${params.userId}/factors/${params.id}`, { + headers: this.headers, + }); + return { data, error: null }; + } + catch (error) { + if (isAuthError(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Lists all OAuth clients with optional pagination. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async _listOAuthClients(params) { + var _a, _b, _c, _d, _e, _f, _g; + try { + const pagination = { nextPage: null, lastPage: 0, total: 0 }; + const response = await _request(this.fetch, 'GET', `${this.url}/admin/oauth/clients`, { + headers: this.headers, + noResolveJson: true, + query: { + page: (_b = (_a = params === null || params === void 0 ? void 0 : params.page) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : '', + per_page: (_d = (_c = params === null || params === void 0 ? void 0 : params.perPage) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : '', + }, + xform: _noResolveJsonResponse, + }); + if (response.error) + throw response.error; + const clients = await response.json(); + const total = (_e = response.headers.get('x-total-count')) !== null && _e !== void 0 ? _e : 0; + const links = (_g = (_f = response.headers.get('link')) === null || _f === void 0 ? void 0 : _f.split(',')) !== null && _g !== void 0 ? _g : []; + if (links.length > 0) { + links.forEach((link) => { + const page = parseInt(link.split(';')[0].split('=')[1].substring(0, 1)); + const rel = JSON.parse(link.split(';')[1].split('=')[1]); + pagination[`${rel}Page`] = page; + }); + pagination.total = parseInt(total); + } + return { data: Object.assign(Object.assign({}, clients), pagination), error: null }; + } + catch (error) { + if (isAuthError(error)) { + return { data: { clients: [] }, error }; + } + throw error; + } + } + /** + * Creates a new OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async _createOAuthClient(params) { + try { + return await _request(this.fetch, 'POST', `${this.url}/admin/oauth/clients`, { + body: params, + headers: this.headers, + xform: (client) => { + return { data: client, error: null }; + }, + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Gets details of a specific OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async _getOAuthClient(clientId) { + try { + return await _request(this.fetch, 'GET', `${this.url}/admin/oauth/clients/${clientId}`, { + headers: this.headers, + xform: (client) => { + return { data: client, error: null }; + }, + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Updates an existing OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async _updateOAuthClient(clientId, params) { + try { + return await _request(this.fetch, 'PUT', `${this.url}/admin/oauth/clients/${clientId}`, { + body: params, + headers: this.headers, + xform: (client) => { + return { data: client, error: null }; + }, + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Deletes an OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async _deleteOAuthClient(clientId) { + try { + await _request(this.fetch, 'DELETE', `${this.url}/admin/oauth/clients/${clientId}`, { + headers: this.headers, + noResolveJson: true, + }); + return { data: null, error: null }; + } + catch (error) { + if (isAuthError(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Regenerates the secret for an OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async _regenerateOAuthClientSecret(clientId) { + try { + return await _request(this.fetch, 'POST', `${this.url}/admin/oauth/clients/${clientId}/regenerate_secret`, { + headers: this.headers, + xform: (client) => { + return { data: client, error: null }; + }, + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: null, error }; + } + throw error; + } + } +} +//# sourceMappingURL=GoTrueAdminApi.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/GoTrueAdminApi.js.map b/backend/node_modules/@supabase/auth-js/dist/module/GoTrueAdminApi.js.map new file mode 100644 index 0000000..61736eb --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/GoTrueAdminApi.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GoTrueAdminApi.js","sourceRoot":"","sources":["../../src/GoTrueAdminApi.ts"],"names":[],"mappings":";AAAA,OAAO,EAEL,qBAAqB,EACrB,sBAAsB,EACtB,QAAQ,EACR,aAAa,GACd,MAAM,aAAa,CAAA;AACpB,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,eAAe,CAAA;AAC1D,OAAO,EAaL,eAAe,GAOhB,MAAM,aAAa,CAAA;AACpB,OAAO,EAAa,WAAW,EAAE,MAAM,cAAc,CAAA;AAErD,MAAM,CAAC,OAAO,OAAO,cAAc;IAgBjC;;;;;;;;;;;;OAYG;IACH,YAAY,EACV,GAAG,GAAG,EAAE,EACR,OAAO,GAAG,EAAE,EACZ,KAAK,GAON;QACC,IAAI,CAAC,GAAG,GAAG,GAAG,CAAA;QACd,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;QACtB,IAAI,CAAC,KAAK,GAAG,YAAY,CAAC,KAAK,CAAC,CAAA;QAChC,IAAI,CAAC,GAAG,GAAG;YACT,WAAW,EAAE,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC;YACzC,YAAY,EAAE,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC;SAC5C,CAAA;QACD,IAAI,CAAC,KAAK,GAAG;YACX,WAAW,EAAE,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,IAAI,CAAC;YAC9C,YAAY,EAAE,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,IAAI,CAAC;YAChD,SAAS,EAAE,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,IAAI,CAAC;YAC1C,YAAY,EAAE,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,IAAI,CAAC;YAChD,YAAY,EAAE,IAAI,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MAAM,KAAK,CAAA;QACb,CAAC;IACH,CAAC;IAED;;;;;OAKG;IACK,KAAK,CAAC,4BAA4B,CAAC,QAAgB;QACzD,IAAI,CAAC;YACH,OAAO,MAAM,QAAQ,CACnB,IAAI,CAAC,KAAK,EACV,MAAM,EACN,GAAG,IAAI,CAAC,GAAG,wBAAwB,QAAQ,oBAAoB,EAC/D;gBACE,OAAO,EAAE,IAAI,CAAC,OAAO;gBACrB,KAAK,EAAE,CAAC,MAAW,EAAE,EAAE;oBACrB,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,CAAA;gBACtC,CAAC;aACF,CACF,CAAA;QACH,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,WAAW,CAAC,KAAK,CAAC,EAAE,CAAC;gBACvB,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,CAAA;YAC9B,CAAC;YAED,MAAM,KAAK,CAAA;QACb,CAAC;IACH,CAAC;CACF"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/GoTrueClient.d.ts b/backend/node_modules/@supabase/auth-js/dist/module/GoTrueClient.d.ts new file mode 100644 index 0000000..86030f0 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/GoTrueClient.d.ts @@ -0,0 +1,608 @@ +import GoTrueAdminApi from './GoTrueAdminApi'; +import { AuthError } from './lib/errors'; +import { Fetch } from './lib/fetch'; +import { Deferred } from './lib/helpers'; +import type { AuthChangeEvent, AuthFlowType, AuthOtpResponse, AuthResponse, AuthTokenResponse, AuthTokenResponsePassword, CallRefreshTokenResult, GoTrueClientOptions, GoTrueMFAApi, InitializeResult, JWK, JwtHeader, JwtPayload, LockFunc, OAuthResponse, AuthOAuthServerApi, ResendParams, Session, SignInAnonymouslyCredentials, SignInWithIdTokenCredentials, SignInWithOAuthCredentials, SignInWithPasswordCredentials, SignInWithPasswordlessCredentials, SignInWithSSO, SignOut, SignUpWithPasswordCredentials, SSOResponse, Subscription, SupportedStorage, User, UserAttributes, UserIdentity, UserResponse, VerifyOtpParams, Web3Credentials } from './lib/types'; +export default class GoTrueClient { + private static nextInstanceID; + private instanceID; + /** + * Namespace for the GoTrue admin methods. + * These methods should only be used in a trusted server-side environment. + */ + admin: GoTrueAdminApi; + /** + * Namespace for the MFA methods. + */ + mfa: GoTrueMFAApi; + /** + * Namespace for the OAuth 2.1 authorization server methods. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * Used to implement the authorization code flow on the consent page. + */ + oauth: AuthOAuthServerApi; + /** + * The storage key used to identify the values saved in localStorage + */ + protected storageKey: string; + protected flowType: AuthFlowType; + /** + * The JWKS used for verifying asymmetric JWTs + */ + protected get jwks(): { + keys: JWK[]; + }; + protected set jwks(value: { + keys: JWK[]; + }); + protected get jwks_cached_at(): number; + protected set jwks_cached_at(value: number); + protected autoRefreshToken: boolean; + protected persistSession: boolean; + protected storage: SupportedStorage; + /** + * @experimental + */ + protected userStorage: SupportedStorage | null; + protected memoryStorage: { + [key: string]: string; + } | null; + protected stateChangeEmitters: Map; + protected autoRefreshTicker: ReturnType | null; + protected visibilityChangedCallback: (() => Promise) | null; + protected refreshingDeferred: Deferred | null; + /** + * Keeps track of the async client initialization. + * When null or not yet resolved the auth state is `unknown` + * Once resolved the auth state is known and it's safe to call any further client methods. + * Keep extra care to never reject or throw uncaught errors + */ + protected initializePromise: Promise | null; + protected detectSessionInUrl: boolean; + protected url: string; + protected headers: { + [key: string]: string; + }; + protected hasCustomAuthorizationHeader: boolean; + protected suppressGetSessionWarning: boolean; + protected fetch: Fetch; + protected lock: LockFunc; + protected lockAcquired: boolean; + protected pendingInLock: Promise[]; + protected throwOnError: boolean; + /** + * Used to broadcast state change events to other tabs listening. + */ + protected broadcastChannel: BroadcastChannel | null; + protected logDebugMessages: boolean; + protected logger: (message: string, ...args: any[]) => void; + /** + * Create a new client for use in the browser. + * + * @example + * ```ts + * import { GoTrueClient } from '@supabase/auth-js' + * + * const auth = new GoTrueClient({ + * url: 'https://xyzcompany.supabase.co/auth/v1', + * headers: { apikey: 'public-anon-key' }, + * storageKey: 'supabase-auth', + * }) + * ``` + */ + constructor(options: GoTrueClientOptions); + /** + * Returns whether error throwing mode is enabled for this client. + */ + isThrowOnErrorEnabled(): boolean; + /** + * Centralizes return handling with optional error throwing. When `throwOnError` is enabled + * and the provided result contains a non-nullish error, the error is thrown instead of + * being returned. This ensures consistent behavior across all public API methods. + */ + private _returnResult; + private _logPrefix; + private _debug; + /** + * Initializes the client session either from the url or from storage. + * This method is automatically called when instantiating the client, but should also be called + * manually when checking for an error from an auth redirect (oauth, magiclink, password recovery, etc). + */ + initialize(): Promise; + /** + * IMPORTANT: + * 1. Never throw in this method, as it is called from the constructor + * 2. Never return a session from this method as it would be cached over + * the whole lifetime of the client + */ + private _initialize; + /** + * Creates a new anonymous user. + * + * @returns A session where the is_anonymous claim in the access token JWT set to true + */ + signInAnonymously(credentials?: SignInAnonymouslyCredentials): Promise; + /** + * Creates a new user. + * + * Be aware that if a user account exists in the system you may get back an + * error message that attempts to hide this information from the user. + * This method has support for PKCE via email signups. The PKCE flow cannot be used when autoconfirm is enabled. + * + * @returns A logged-in session if the server has "autoconfirm" ON + * @returns A user if the server has "autoconfirm" OFF + */ + signUp(credentials: SignUpWithPasswordCredentials): Promise; + /** + * Log in an existing user with an email and password or phone and password. + * + * Be aware that you may get back an error message that will not distinguish + * between the cases where the account does not exist or that the + * email/phone and password combination is wrong or that the account can only + * be accessed via social login. + */ + signInWithPassword(credentials: SignInWithPasswordCredentials): Promise; + /** + * Log in an existing user via a third-party provider. + * This method supports the PKCE flow. + */ + signInWithOAuth(credentials: SignInWithOAuthCredentials): Promise; + /** + * Log in an existing user by exchanging an Auth Code issued during the PKCE flow. + */ + exchangeCodeForSession(authCode: string): Promise; + /** + * Signs in a user by verifying a message signed by the user's private key. + * Supports Ethereum (via Sign-In-With-Ethereum) & Solana (Sign-In-With-Solana) standards, + * both of which derive from the EIP-4361 standard + * With slight variation on Solana's side. + * @reference https://eips.ethereum.org/EIPS/eip-4361 + */ + signInWithWeb3(credentials: Web3Credentials): Promise<{ + data: { + session: Session; + user: User; + }; + error: null; + } | { + data: { + session: null; + user: null; + }; + error: AuthError; + }>; + private signInWithEthereum; + private signInWithSolana; + private _exchangeCodeForSession; + /** + * Allows signing in with an OIDC ID token. The authentication provider used + * should be enabled and configured. + */ + signInWithIdToken(credentials: SignInWithIdTokenCredentials): Promise; + /** + * Log in a user using magiclink or a one-time password (OTP). + * + * If the `{{ .ConfirmationURL }}` variable is specified in the email template, a magiclink will be sent. + * If the `{{ .Token }}` variable is specified in the email template, an OTP will be sent. + * If you're using phone sign-ins, only an OTP will be sent. You won't be able to send a magiclink for phone sign-ins. + * + * Be aware that you may get back an error message that will not distinguish + * between the cases where the account does not exist or, that the account + * can only be accessed via social login. + * + * Do note that you will need to configure a Whatsapp sender on Twilio + * if you are using phone sign in with the 'whatsapp' channel. The whatsapp + * channel is not supported on other providers + * at this time. + * This method supports PKCE when an email is passed. + */ + signInWithOtp(credentials: SignInWithPasswordlessCredentials): Promise; + /** + * Log in a user given a User supplied OTP or TokenHash received through mobile or email. + */ + verifyOtp(params: VerifyOtpParams): Promise; + /** + * Attempts a single-sign on using an enterprise Identity Provider. A + * successful SSO attempt will redirect the current page to the identity + * provider authorization page. The redirect URL is implementation and SSO + * protocol specific. + * + * You can use it by providing a SSO domain. Typically you can extract this + * domain by asking users for their email address. If this domain is + * registered on the Auth instance the redirect will use that organization's + * currently active SSO Identity Provider for the login. + * + * If you have built an organization-specific login page, you can use the + * organization's SSO Identity Provider UUID directly instead. + */ + signInWithSSO(params: SignInWithSSO): Promise; + /** + * Sends a reauthentication OTP to the user's email or phone number. + * Requires the user to be signed-in. + */ + reauthenticate(): Promise; + private _reauthenticate; + /** + * Resends an existing signup confirmation email, email change email, SMS OTP or phone change OTP. + */ + resend(credentials: ResendParams): Promise; + /** + * Returns the session, refreshing it if necessary. + * + * The session returned can be null if the session is not detected which can happen in the event a user is not signed-in or has logged out. + * + * **IMPORTANT:** This method loads values directly from the storage attached + * to the client. If that storage is based on request cookies for example, + * the values in it may not be authentic and therefore it's strongly advised + * against using this method and its results in such circumstances. A warning + * will be emitted if this is detected. Use {@link #getUser()} instead. + */ + getSession(): Promise<{ + data: { + session: Session; + }; + error: null; + } | { + data: { + session: null; + }; + error: AuthError; + } | { + data: { + session: null; + }; + error: null; + }>; + /** + * Acquires a global lock based on the storage key. + */ + private _acquireLock; + /** + * Use instead of {@link #getSession} inside the library. It is + * semantically usually what you want, as getting a session involves some + * processing afterwards that requires only one client operating on the + * session at once across multiple tabs or processes. + */ + private _useSession; + /** + * NEVER USE DIRECTLY! + * + * Always use {@link #_useSession}. + */ + private __loadSession; + /** + * Gets the current user details if there is an existing session. This method + * performs a network request to the Supabase Auth server, so the returned + * value is authentic and can be used to base authorization rules on. + * + * @param jwt Takes in an optional access token JWT. If no JWT is provided, the JWT from the current session is used. + */ + getUser(jwt?: string): Promise; + private _getUser; + /** + * Updates user data for a logged in user. + */ + updateUser(attributes: UserAttributes, options?: { + emailRedirectTo?: string | undefined; + }): Promise; + protected _updateUser(attributes: UserAttributes, options?: { + emailRedirectTo?: string | undefined; + }): Promise; + /** + * Sets the session data from the current session. If the current session is expired, setSession will take care of refreshing it to obtain a new session. + * If the refresh token or access token in the current session is invalid, an error will be thrown. + * @param currentSession The current session that minimally contains an access token and refresh token. + */ + setSession(currentSession: { + access_token: string; + refresh_token: string; + }): Promise; + protected _setSession(currentSession: { + access_token: string; + refresh_token: string; + }): Promise; + /** + * Returns a new session, regardless of expiry status. + * Takes in an optional current session. If not passed in, then refreshSession() will attempt to retrieve it from getSession(). + * If the current session's refresh token is invalid, an error will be thrown. + * @param currentSession The current session. If passed in, it must contain a refresh token. + */ + refreshSession(currentSession?: { + refresh_token: string; + }): Promise; + protected _refreshSession(currentSession?: { + refresh_token: string; + }): Promise; + /** + * Gets the session data from a URL string + */ + private _getSessionFromURL; + /** + * Checks if the current URL contains parameters given by an implicit oauth grant flow (https://www.rfc-editor.org/rfc/rfc6749.html#section-4.2) + */ + private _isImplicitGrantCallback; + /** + * Checks if the current URL and backing storage contain parameters given by a PKCE flow + */ + private _isPKCECallback; + /** + * Inside a browser context, `signOut()` will remove the logged in user from the browser session and log them out - removing all items from localstorage and then trigger a `"SIGNED_OUT"` event. + * + * For server-side management, you can revoke all refresh tokens for a user by passing a user's JWT through to `auth.api.signOut(JWT: string)`. + * There is no way to revoke a user's access token jwt until it expires. It is recommended to set a shorter expiry on the jwt for this reason. + * + * If using `others` scope, no `SIGNED_OUT` event is fired! + */ + signOut(options?: SignOut): Promise<{ + error: AuthError | null; + }>; + protected _signOut({ scope }?: SignOut): Promise<{ + error: AuthError | null; + }>; + /** + * Receive a notification every time an auth event happens. + * Safe to use without an async function as callback. + * + * @param callback A callback function to be invoked when an auth event happens. + */ + onAuthStateChange(callback: (event: AuthChangeEvent, session: Session | null) => void): { + data: { + subscription: Subscription; + }; + }; + /** + * Avoid using an async function inside `onAuthStateChange` as you might end + * up with a deadlock. The callback function runs inside an exclusive lock, + * so calling other Supabase Client APIs that also try to acquire the + * exclusive lock, might cause a deadlock. This behavior is observable across + * tabs. In the next major library version, this behavior will not be supported. + * + * Receive a notification every time an auth event happens. + * + * @param callback A callback function to be invoked when an auth event happens. + * @deprecated Due to the possibility of deadlocks with async functions as callbacks, use the version without an async function. + */ + onAuthStateChange(callback: (event: AuthChangeEvent, session: Session | null) => Promise): { + data: { + subscription: Subscription; + }; + }; + private _emitInitialSession; + /** + * Sends a password reset request to an email address. This method supports the PKCE flow. + * + * @param email The email address of the user. + * @param options.redirectTo The URL to send the user to after they click the password reset link. + * @param options.captchaToken Verification token received when the user completes the captcha on the site. + */ + resetPasswordForEmail(email: string, options?: { + redirectTo?: string; + captchaToken?: string; + }): Promise<{ + data: {}; + error: null; + } | { + data: null; + error: AuthError; + }>; + /** + * Gets all the identities linked to a user. + */ + getUserIdentities(): Promise<{ + data: { + identities: UserIdentity[]; + }; + error: null; + } | { + data: null; + error: AuthError; + }>; + /** + * Links an oauth identity to an existing user. + * This method supports the PKCE flow. + */ + linkIdentity(credentials: SignInWithOAuthCredentials): Promise; + /** + * Links an OIDC identity to an existing user. + */ + linkIdentity(credentials: SignInWithIdTokenCredentials): Promise; + private linkIdentityOAuth; + private linkIdentityIdToken; + /** + * Unlinks an identity from a user by deleting it. The user will no longer be able to sign in with that identity once it's unlinked. + */ + unlinkIdentity(identity: UserIdentity): Promise<{ + data: {}; + error: null; + } | { + data: null; + error: AuthError; + }>; + /** + * Generates a new JWT. + * @param refreshToken A valid refresh token that was returned on login. + */ + private _refreshAccessToken; + private _isValidSession; + private _handleProviderSignIn; + /** + * Recovers the session from LocalStorage and refreshes the token + * Note: this method is async to accommodate for AsyncStorage e.g. in React native. + */ + private _recoverAndRefresh; + private _callRefreshToken; + private _notifyAllSubscribers; + /** + * set currentSession and currentUser + * process to _startAutoRefreshToken if possible + */ + private _saveSession; + private _removeSession; + /** + * Removes any registered visibilitychange callback. + * + * {@see #startAutoRefresh} + * {@see #stopAutoRefresh} + */ + private _removeVisibilityChangedCallback; + /** + * This is the private implementation of {@link #startAutoRefresh}. Use this + * within the library. + */ + private _startAutoRefresh; + /** + * This is the private implementation of {@link #stopAutoRefresh}. Use this + * within the library. + */ + private _stopAutoRefresh; + /** + * Starts an auto-refresh process in the background. The session is checked + * every few seconds. Close to the time of expiration a process is started to + * refresh the session. If refreshing fails it will be retried for as long as + * necessary. + * + * If you set the {@link GoTrueClientOptions#autoRefreshToken} you don't need + * to call this function, it will be called for you. + * + * On browsers the refresh process works only when the tab/window is in the + * foreground to conserve resources as well as prevent race conditions and + * flooding auth with requests. If you call this method any managed + * visibility change callback will be removed and you must manage visibility + * changes on your own. + * + * On non-browser platforms the refresh process works *continuously* in the + * background, which may not be desirable. You should hook into your + * platform's foreground indication mechanism and call these methods + * appropriately to conserve resources. + * + * {@see #stopAutoRefresh} + */ + startAutoRefresh(): Promise; + /** + * Stops an active auto refresh process running in the background (if any). + * + * If you call this method any managed visibility change callback will be + * removed and you must manage visibility changes on your own. + * + * See {@link #startAutoRefresh} for more details. + */ + stopAutoRefresh(): Promise; + /** + * Runs the auto refresh token tick. + */ + private _autoRefreshTokenTick; + /** + * Registers callbacks on the browser / platform, which in-turn run + * algorithms when the browser window/tab are in foreground. On non-browser + * platforms it assumes always foreground. + */ + private _handleVisibilityChange; + /** + * Callback registered with `window.addEventListener('visibilitychange')`. + */ + private _onVisibilityChanged; + /** + * Generates the relevant login URL for a third-party provider. + * @param options.redirectTo A URL or mobile address to send the user to after they are confirmed. + * @param options.scopes A space-separated list of scopes granted to the OAuth application. + * @param options.queryParams An object of key-value pairs containing query parameters granted to the OAuth application. + */ + private _getUrlForProvider; + private _unenroll; + /** + * {@see GoTrueMFAApi#enroll} + */ + private _enroll; + /** + * {@see GoTrueMFAApi#verify} + */ + private _verify; + /** + * {@see GoTrueMFAApi#challenge} + */ + private _challenge; + /** + * {@see GoTrueMFAApi#challengeAndVerify} + */ + private _challengeAndVerify; + /** + * {@see GoTrueMFAApi#listFactors} + */ + private _listFactors; + /** + * {@see GoTrueMFAApi#getAuthenticatorAssuranceLevel} + */ + private _getAuthenticatorAssuranceLevel; + /** + * Retrieves details about an OAuth authorization request. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * Returns authorization details including client info, scopes, and user information. + * If the API returns a redirect_uri, it means consent was already given - the caller + * should handle the redirect manually if needed. + */ + private _getAuthorizationDetails; + /** + * Approves an OAuth authorization request. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ + private _approveAuthorization; + /** + * Denies an OAuth authorization request. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ + private _denyAuthorization; + /** + * Lists all OAuth grants that the authenticated user has authorized. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ + private _listOAuthGrants; + /** + * Revokes a user's OAuth grant for a specific client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ + private _revokeOAuthGrant; + private fetchJwk; + /** + * Extracts the JWT claims present in the access token by first verifying the + * JWT against the server's JSON Web Key Set endpoint + * `/.well-known/jwks.json` which is often cached, resulting in significantly + * faster responses. Prefer this method over {@link #getUser} which always + * sends a request to the Auth server for each JWT. + * + * If the project is not using an asymmetric JWT signing key (like ECC or + * RSA) it always sends a request to the Auth server (similar to {@link + * #getUser}) to verify the JWT. + * + * @param jwt An optional specific JWT you wish to verify, not the one you + * can obtain from {@link #getSession}. + * @param options Various additional options that allow you to customize the + * behavior of this method. + */ + getClaims(jwt?: string, options?: { + /** + * @deprecated Please use options.jwks instead. + */ + keys?: JWK[]; + /** If set to `true` the `exp` claim will not be validated against the current time. */ + allowExpired?: boolean; + /** If set, this JSON Web Key Set is going to have precedence over the cached value available on the server. */ + jwks?: { + keys: JWK[]; + }; + }): Promise<{ + data: { + claims: JwtPayload; + header: JwtHeader; + signature: Uint8Array; + }; + error: null; + } | { + data: null; + error: AuthError; + } | { + data: null; + error: null; + }>; +} +//# sourceMappingURL=GoTrueClient.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/GoTrueClient.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/module/GoTrueClient.d.ts.map new file mode 100644 index 0000000..f01c185 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/GoTrueClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"GoTrueClient.d.ts","sourceRoot":"","sources":["../../src/GoTrueClient.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,kBAAkB,CAAA;AAU7C,OAAO,EACL,SAAS,EAaV,MAAM,cAAc,CAAA;AACrB,OAAO,EACL,KAAK,EAMN,MAAM,aAAa,CAAA;AACpB,OAAO,EAGL,QAAQ,EAgBT,MAAM,eAAe,CAAA;AAOtB,OAAO,KAAK,EACV,eAAe,EAEf,YAAY,EAcZ,eAAe,EACf,YAAY,EAEZ,iBAAiB,EACjB,yB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AyBrC;;OAEG;YACW,oBAAoB;IAwClC;;;;;OAKG;YACW,kBAAkB;YAwClB,SAAS;IAqBvB;;OAEG;YACW,OAAO;IA4CrB;;OAEG;YACW,OAAO;IAgFrB;;OAEG;YACW,UAAU;IAsFxB;;OAEG;YACW,mBAAmB;IAoBjC;;OAEG;YACW,YAAY;IA+B1B;;OAEG;YACW,+BAA+B;IAsC7C;;;;;;;OAOG;YACW,wBAAwB;IAsCtC;;;OAGG;YACW,qBAAqB;IAiDnC;;;OAGG;YACW,kBAAkB;IAiDhC;;;OAGG;YACW,gBAAgB;IA+B9B;;;OAGG;YACW,iBAAiB;YAmCjB,QAAQ;IAsCtB;;;;;;;;;;;;;;;OAeG;IACG,SAAS,CACb,GAAG,CAAC,EAAE,MAAM,EACZ,OAAO,GAAE;QACP;;WAEG;QACH,IAAI,CAAC,EAAE,GAAG,EAAE,CAAA;QAEZ,uFAAuF;QACvF,YAAY,CAAC,EAAE,OAAO,CAAA;QAEtB,+GAA+G;QAC/G,IAAI,CAAC,EAAE;YAAE,IAAI,EAAE,GAAG,EAAE,CAAA;SAAE,CAAA;KAClB,GACL,OAAO,CACN;QACE,IAAI,EAAE;YAAE,MAAM,EAAE,UAAU,CAAC;YAAC,MAAM,EAAE,SAAS,CAAC;YAAC,SAAS,EAAE,UAAU,CAAA;SAAE,CAAA;QACtE,KAAK,EAAE,IAAI,CAAA;KACZ,GACD;QAAE,IAAI,EAAE,IAAI,CAAC;QAAC,KAAK,EAAE,SAAS,CAAA;KAAE,GAChC;QAAE,IAAI,EAAE,IAAI,CAAC;QAAC,KAAK,EAAE,IAAI,CAAA;KAAE,CAC9B;CAmFF"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/GoTrueClient.js b/backend/node_modules/@supabase/auth-js/dist/module/GoTrueClient.js new file mode 100644 index 0000000..ad0f991 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/GoTrueClient.js @@ -0,0 +1,2786 @@ +import GoTrueAdminApi from './GoTrueAdminApi'; +import { AUTO_REFRESH_TICK_DURATION_MS, AUTO_REFRESH_TICK_THRESHOLD, DEFAULT_HEADERS, EXPIRY_MARGIN_MS, GOTRUE_URL, JWKS_TTL, STORAGE_KEY, } from './lib/constants'; +import { AuthImplicitGrantRedirectError, AuthInvalidCredentialsError, AuthInvalidJwtError, AuthInvalidTokenResponseError, AuthPKCEGrantCodeExchangeError, AuthSessionMissingError, AuthUnknownError, isAuthApiError, isAuthError, isAuthImplicitGrantRedirectError, isAuthRetryableFetchError, isAuthSessionMissingError, } from './lib/errors'; +import { _request, _sessionResponse, _sessionResponsePassword, _ssoResponse, _userResponse, } from './lib/fetch'; +import { decodeJWT, deepClone, Deferred, generateCallbackId, getAlgorithm, getCodeChallengeAndMethod, getItemAsync, insecureUserWarningProxy, isBrowser, parseParametersFromURL, removeItemAsync, resolveFetch, retryable, setItemAsync, sleep, supportsLocalStorage, userNotAvailableProxy, validateExp, } from './lib/helpers'; +import { memoryLocalStorageAdapter } from './lib/local-storage'; +import { LockAcquireTimeoutError, navigatorLock } from './lib/locks'; +import { polyfillGlobalThis } from './lib/polyfills'; +import { version } from './lib/version'; +import { bytesToBase64URL, stringToUint8Array } from './lib/base64url'; +import { createSiweMessage, fromHex, getAddress, toHex, } from './lib/web3/ethereum'; +import { deserializeCredentialCreationOptions, deserializeCredentialRequestOptions, serializeCredentialCreationResponse, serializeCredentialRequestResponse, WebAuthnApi, } from './lib/webauthn'; +polyfillGlobalThis(); // Make "globalThis" available +const DEFAULT_OPTIONS = { + url: GOTRUE_URL, + storageKey: STORAGE_KEY, + autoRefreshToken: true, + persistSession: true, + detectSessionInUrl: true, + headers: DEFAULT_HEADERS, + flowType: 'implicit', + debug: false, + hasCustomAuthorizationHeader: false, + throwOnError: false, +}; +async function lockNoOp(name, acquireTimeout, fn) { + return await fn(); +} +/** + * Caches JWKS values for all clients created in the same environment. This is + * especially useful for shared-memory execution environments such as Vercel's + * Fluid Compute, AWS Lambda or Supabase's Edge Functions. Regardless of how + * many clients are created, if they share the same storage key they will use + * the same JWKS cache, significantly speeding up getClaims() with asymmetric + * JWTs. + */ +const GLOBAL_JWKS = {}; +class GoTrueClient { + /** + * The JWKS used for verifying asymmetric JWTs + */ + get jwks() { + var _a, _b; + return (_b = (_a = GLOBAL_JWKS[this.storageKey]) === null || _a === void 0 ? void 0 : _a.jwks) !== null && _b !== void 0 ? _b : { keys: [] }; + } + set jwks(value) { + GLOBAL_JWKS[this.storageKey] = Object.assign(Object.assign({}, GLOBAL_JWKS[this.storageKey]), { jwks: value }); + } + get jwks_cached_at() { + var _a, _b; + return (_b = (_a = GLOBAL_JWKS[this.storageKey]) === null || _a === void 0 ? void 0 : _a.cachedAt) !== null && _b !== void 0 ? _b : Number.MIN_SAFE_INTEGER; + } + set jwks_cached_at(value) { + GLOBAL_JWKS[this.storageKey] = Object.assign(Object.assign({}, GLOBAL_JWKS[this.storageKey]), { cachedAt: value }); + } + /** + * Create a new client for use in the browser. + * + * @example + * ```ts + * import { GoTrueClient } from '@supabase/auth-js' + * + * const auth = new GoTrueClient({ + * url: 'https://xyzcompany.supabase.co/auth/v1', + * headers: { apikey: 'public-anon-key' }, + * storageKey: 'supabase-auth', + * }) + * ``` + */ + constructor(options) { + var _a, _b, _c; + /** + * @experimental + */ + this.userStorage = null; + this.memoryStorage = null; + this.stateChangeEmitters = new Map(); + this.autoRefreshTicker = null; + this.visibilityChangedCallback = null; + this.refreshingDeferred = null; + /** + * Keeps track of the async client initialization. + * When null or not yet resolved the auth state is `unknown` + * Once resolved the auth state is known and it's safe to call any further client methods. + * Keep extra care to never reject or throw uncaught errors + */ + this.initializePromise = null; + this.detectSessionInUrl = true; + this.hasCustomAuthorizationHeader = false; + this.suppressGetSessionWarning = false; + this.lockAcquired = false; + this.pendingInLock = []; + /** + * Used to broadcast state change events to other tabs listening. + */ + this.broadcastChannel = null; + this.logger = console.log; + const settings = Object.assign(Object.assign({}, DEFAULT_OPTIONS), options); + this.storageKey = settings.storageKey; + this.instanceID = (_a = GoTrueClient.nextInstanceID[this.storageKey]) !== null && _a !== void 0 ? _a : 0; + GoTrueClient.nextInstanceID[this.storageKey] = this.instanceID + 1; + this.logDebugMessages = !!settings.debug; + if (typeof settings.debug === 'function') { + this.logger = settings.debug; + } + if (this.instanceID > 0 && isBrowser()) { + const message = `${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`; + console.warn(message); + if (this.logDebugMessages) { + console.trace(message); + } + } + this.persistSession = settings.persistSession; + this.autoRefreshToken = settings.autoRefreshToken; + this.admin = new GoTrueAdminApi({ + url: settings.url, + headers: settings.headers, + fetch: settings.fetch, + }); + this.url = settings.url; + this.headers = settings.headers; + this.fetch = resolveFetch(settings.fetch); + this.lock = settings.lock || lockNoOp; + this.detectSessionInUrl = settings.detectSessionInUrl; + this.flowType = settings.flowType; + this.hasCustomAuthorizationHeader = settings.hasCustomAuthorizationHeader; + this.throwOnError = settings.throwOnError; + if (settings.lock) { + this.lock = settings.lock; + } + else if (this.persistSession && isBrowser() && ((_b = globalThis === null || globalThis === void 0 ? void 0 : globalThis.navigator) === null || _b === void 0 ? void 0 : _b.locks)) { + this.lock = navigatorLock; + } + else { + this.lock = lockNoOp; + } + if (!this.jwks) { + this.jwks = { keys: [] }; + this.jwks_cached_at = Number.MIN_SAFE_INTEGER; + } + this.mfa = { + verify: this._verify.bind(this), + enroll: this._enroll.bind(this), + unenroll: this._unenroll.bind(this), + challenge: this._challenge.bind(this), + listFactors: this._listFactors.bind(this), + challengeAndVerify: this._challengeAndVerify.bind(this), + getAuthenticatorAssuranceLevel: this._getAuthenticatorAssuranceLevel.bind(this), + webauthn: new WebAuthnApi(this), + }; + this.oauth = { + getAuthorizationDetails: this._getAuthorizationDetails.bind(this), + approveAuthorization: this._approveAuthorization.bind(this), + denyAuthorization: this._denyAuthorization.bind(this), + listGrants: this._listOAuthGrants.bind(this), + revokeGrant: this._revokeOAuthGrant.bind(this), + }; + if (this.persistSession) { + if (settings.storage) { + this.storage = settings.storage; + } + else { + if (supportsLocalStorage()) { + this.storage = globalThis.localStorage; + } + else { + this.memoryStorage = {}; + this.storage = memoryLocalStorageAdapter(this.memoryStorage); + } + } + if (settings.userStorage) { + this.userStorage = settings.userStorage; + } + } + else { + this.memoryStorage = {}; + this.storage = memoryLocalStorageAdapter(this.memoryStorage); + } + if (isBrowser() && globalThis.BroadcastChannel && this.persistSession && this.storageKey) { + try { + this.broadcastChannel = new globalThis.BroadcastChannel(this.storageKey); + } + catch (e) { + console.error('Failed to create a new BroadcastChannel, multi-tab state changes will not be available', e); + } + (_c = this.broadcastChannel) === null || _c === void 0 ? void 0 : _c.addEventListener('message', async (event) => { + this._debug('received broadcast notification from other tab or client', event); + await this._notifyAllSubscribers(event.data.event, event.data.session, false); // broadcast = false so we don't get an endless loop of messages + }); + } + this.initialize(); + } + /** + * Returns whether error throwing mode is enabled for this client. + */ + isThrowOnErrorEnabled() { + return this.throwOnError; + } + /** + * Centralizes return handling with optional error throwing. When `throwOnError` is enabled + * and the provided result contains a non-nullish error, the error is thrown instead of + * being returned. This ensures consistent behavior across all public API methods. + */ + _returnResult(result) { + if (this.throwOnError && result && result.error) { + throw result.error; + } + return result; + } + _logPrefix() { + return ('GoTrueClient@' + + `${this.storageKey}:${this.instanceID} (${version}) ${new Date().toISOString()}`); + } + _debug(...args) { + if (this.logDebugMessages) { + this.logger(this._logPrefix(), ...args); + } + return this; + } + /** + * Initializes the client session either from the url or from storage. + * This method is automatically called when instantiating the client, but should also be called + * manually when checking for an error from an auth redirect (oauth, magiclink, password recovery, etc). + */ + async initialize() { + if (this.initializePromise) { + return await this.initializePromise; + } + this.initializePromise = (async () => { + return await this._acquireLock(-1, async () => { + return await this._initialize(); + }); + })(); + return await this.initializePromise; + } + /** + * IMPORTANT: + * 1. Never throw in this method, as it is called from the constructor + * 2. Never return a session from this method as it would be cached over + * the whole lifetime of the client + */ + async _initialize() { + var _a; + try { + let params = {}; + let callbackUrlType = 'none'; + if (isBrowser()) { + params = parseParametersFromURL(window.location.href); + if (this._isImplicitGrantCallback(params)) { + callbackUrlType = 'implicit'; + } + else if (await this._isPKCECallback(params)) { + callbackUrlType = 'pkce'; + } + } + /** + * Attempt to get the session from the URL only if these conditions are fulfilled + * + * Note: If the URL isn't one of the callback url types (implicit or pkce), + * then there could be an existing session so we don't want to prematurely remove it + */ + if (isBrowser() && this.detectSessionInUrl && callbackUrlType !== 'none') { + const { data, error } = await this._getSessionFromURL(params, callbackUrlType); + if (error) { + this._debug('#_initialize()', 'error detecting session from URL', error); + if (isAuthImplicitGrantRedirectError(error)) { + const errorCode = (_a = error.details) === null || _a === void 0 ? void 0 : _a.code; + if (errorCode === 'identity_already_exists' || + errorCode === 'identity_not_found' || + errorCode === 'single_identity_not_deletable') { + return { error }; + } + } + // failed login attempt via url, + // remove old session as in verifyOtp, signUp and signInWith* + await this._removeSession(); + return { error }; + } + const { session, redirectType } = data; + this._debug('#_initialize()', 'detected session in URL', session, 'redirect type', redirectType); + await this._saveSession(session); + setTimeout(async () => { + if (redirectType === 'recovery') { + await this._notifyAllSubscribers('PASSWORD_RECOVERY', session); + } + else { + await this._notifyAllSubscribers('SIGNED_IN', session); + } + }, 0); + return { error: null }; + } + // no login attempt via callback url try to recover session from storage + await this._recoverAndRefresh(); + return { error: null }; + } + catch (error) { + if (isAuthError(error)) { + return this._returnResult({ error }); + } + return this._returnResult({ + error: new AuthUnknownError('Unexpected error during initialization', error), + }); + } + finally { + await this._handleVisibilityChange(); + this._debug('#_initialize()', 'end'); + } + } + /** + * Creates a new anonymous user. + * + * @returns A session where the is_anonymous claim in the access token JWT set to true + */ + async signInAnonymously(credentials) { + var _a, _b, _c; + try { + const res = await _request(this.fetch, 'POST', `${this.url}/signup`, { + headers: this.headers, + body: { + data: (_b = (_a = credentials === null || credentials === void 0 ? void 0 : credentials.options) === null || _a === void 0 ? void 0 : _a.data) !== null && _b !== void 0 ? _b : {}, + gotrue_meta_security: { captcha_token: (_c = credentials === null || credentials === void 0 ? void 0 : credentials.options) === null || _c === void 0 ? void 0 : _c.captchaToken }, + }, + xform: _sessionResponse, + }); + const { data, error } = res; + if (error || !data) { + return this._returnResult({ data: { user: null, session: null }, error: error }); + } + const session = data.session; + const user = data.user; + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', session); + } + return this._returnResult({ data: { user, session }, error: null }); + } + catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + /** + * Creates a new user. + * + * Be aware that if a user account exists in the system you may get back an + * error message that attempts to hide this information from the user. + * This method has support for PKCE via email signups. The PKCE flow cannot be used when autoconfirm is enabled. + * + * @returns A logged-in session if the server has "autoconfirm" ON + * @returns A user if the server has "autoconfirm" OFF + */ + async signUp(credentials) { + var _a, _b, _c; + try { + let res; + if ('email' in credentials) { + const { email, password, options } = credentials; + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === 'pkce') { + ; + [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(this.storage, this.storageKey); + } + res = await _request(this.fetch, 'POST', `${this.url}/signup`, { + headers: this.headers, + redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, + body: { + email, + password, + data: (_a = options === null || options === void 0 ? void 0 : options.data) !== null && _a !== void 0 ? _a : {}, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + code_challenge: codeChallenge, + code_challenge_method: codeChallengeMethod, + }, + xform: _sessionResponse, + }); + } + else if ('phone' in credentials) { + const { phone, password, options } = credentials; + res = await _request(this.fetch, 'POST', `${this.url}/signup`, { + headers: this.headers, + body: { + phone, + password, + data: (_b = options === null || options === void 0 ? void 0 : options.data) !== null && _b !== void 0 ? _b : {}, + channel: (_c = options === null || options === void 0 ? void 0 : options.channel) !== null && _c !== void 0 ? _c : 'sms', + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + xform: _sessionResponse, + }); + } + else { + throw new AuthInvalidCredentialsError('You must provide either an email or phone number and a password'); + } + const { data, error } = res; + if (error || !data) { + await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`); + return this._returnResult({ data: { user: null, session: null }, error: error }); + } + const session = data.session; + const user = data.user; + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', session); + } + return this._returnResult({ data: { user, session }, error: null }); + } + catch (error) { + await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`); + if (isAuthError(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + /** + * Log in an existing user with an email and password or phone and password. + * + * Be aware that you may get back an error message that will not distinguish + * between the cases where the account does not exist or that the + * email/phone and password combination is wrong or that the account can only + * be accessed via social login. + */ + async signInWithPassword(credentials) { + try { + let res; + if ('email' in credentials) { + const { email, password, options } = credentials; + res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=password`, { + headers: this.headers, + body: { + email, + password, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + xform: _sessionResponsePassword, + }); + } + else if ('phone' in credentials) { + const { phone, password, options } = credentials; + res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=password`, { + headers: this.headers, + body: { + phone, + password, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + xform: _sessionResponsePassword, + }); + } + else { + throw new AuthInvalidCredentialsError('You must provide either an email or phone number and a password'); + } + const { data, error } = res; + if (error) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + else if (!data || !data.session || !data.user) { + const invalidTokenError = new AuthInvalidTokenResponseError(); + return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError }); + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', data.session); + } + return this._returnResult({ + data: Object.assign({ user: data.user, session: data.session }, (data.weak_password ? { weakPassword: data.weak_password } : null)), + error, + }); + } + catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + /** + * Log in an existing user via a third-party provider. + * This method supports the PKCE flow. + */ + async signInWithOAuth(credentials) { + var _a, _b, _c, _d; + return await this._handleProviderSignIn(credentials.provider, { + redirectTo: (_a = credentials.options) === null || _a === void 0 ? void 0 : _a.redirectTo, + scopes: (_b = credentials.options) === null || _b === void 0 ? void 0 : _b.scopes, + queryParams: (_c = credentials.options) === null || _c === void 0 ? void 0 : _c.queryParams, + skipBrowserRedirect: (_d = credentials.options) === null || _d === void 0 ? void 0 : _d.skipBrowserRedirect, + }); + } + /** + * Log in an existing user by exchanging an Auth Code issued during the PKCE flow. + */ + async exchangeCodeForSession(authCode) { + await this.initializePromise; + return this._acquireLock(-1, async () => { + return this._exchangeCodeForSession(authCode); + }); + } + /** + * Signs in a user by verifying a message signed by the user's private key. + * Supports Ethereum (via Sign-In-With-Ethereum) & Solana (Sign-In-With-Solana) standards, + * both of which derive from the EIP-4361 standard + * With slight variation on Solana's side. + * @reference https://eips.ethereum.org/EIPS/eip-4361 + */ + async signInWithWeb3(credentials) { + const { chain } = credentials; + switch (chain) { + case 'ethereum': + return await this.signInWithEthereum(credentials); + case 'solana': + return await this.signInWithSolana(credentials); + default: + throw new Error(`@supabase/auth-js: Unsupported chain "${chain}"`); + } + } + async signInWithEthereum(credentials) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l; + // TODO: flatten type + let message; + let signature; + if ('message' in credentials) { + message = credentials.message; + signature = credentials.signature; + } + else { + const { chain, wallet, statement, options } = credentials; + let resolvedWallet; + if (!isBrowser()) { + if (typeof wallet !== 'object' || !(options === null || options === void 0 ? void 0 : options.url)) { + throw new Error('@supabase/auth-js: Both wallet and url must be specified in non-browser environments.'); + } + resolvedWallet = wallet; + } + else if (typeof wallet === 'object') { + resolvedWallet = wallet; + } + else { + const windowAny = window; + if ('ethereum' in windowAny && + typeof windowAny.ethereum === 'object' && + 'request' in windowAny.ethereum && + typeof windowAny.ethereum.request === 'function') { + resolvedWallet = windowAny.ethereum; + } + else { + throw new Error(`@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.`); + } + } + const url = new URL((_a = options === null || options === void 0 ? void 0 : options.url) !== null && _a !== void 0 ? _a : window.location.href); + const accounts = await resolvedWallet + .request({ + method: 'eth_requestAccounts', + }) + .then((accs) => accs) + .catch(() => { + throw new Error(`@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid`); + }); + if (!accounts || accounts.length === 0) { + throw new Error(`@supabase/auth-js: No accounts available. Please ensure the wallet is connected.`); + } + const address = getAddress(accounts[0]); + let chainId = (_b = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _b === void 0 ? void 0 : _b.chainId; + if (!chainId) { + const chainIdHex = await resolvedWallet.request({ + method: 'eth_chainId', + }); + chainId = fromHex(chainIdHex); + } + const siweMessage = { + domain: url.host, + address: address, + statement: statement, + uri: url.href, + version: '1', + chainId: chainId, + nonce: (_c = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _c === void 0 ? void 0 : _c.nonce, + issuedAt: (_e = (_d = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _d === void 0 ? void 0 : _d.issuedAt) !== null && _e !== void 0 ? _e : new Date(), + expirationTime: (_f = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _f === void 0 ? void 0 : _f.expirationTime, + notBefore: (_g = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _g === void 0 ? void 0 : _g.notBefore, + requestId: (_h = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _h === void 0 ? void 0 : _h.requestId, + resources: (_j = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _j === void 0 ? void 0 : _j.resources, + }; + message = createSiweMessage(siweMessage); + // Sign message + signature = (await resolvedWallet.request({ + method: 'personal_sign', + params: [toHex(message), address], + })); + } + try { + const { data, error } = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=web3`, { + headers: this.headers, + body: Object.assign({ chain: 'ethereum', message, + signature }, (((_k = credentials.options) === null || _k === void 0 ? void 0 : _k.captchaToken) + ? { gotrue_meta_security: { captcha_token: (_l = credentials.options) === null || _l === void 0 ? void 0 : _l.captchaToken } } + : null)), + xform: _sessionResponse, + }); + if (error) { + throw error; + } + if (!data || !data.session || !data.user) { + const invalidTokenError = new AuthInvalidTokenResponseError(); + return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError }); + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', data.session); + } + return this._returnResult({ data: Object.assign({}, data), error }); + } + catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + async signInWithSolana(credentials) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m; + let message; + let signature; + if ('message' in credentials) { + message = credentials.message; + signature = credentials.signature; + } + else { + const { chain, wallet, statement, options } = credentials; + let resolvedWallet; + if (!isBrowser()) { + if (typeof wallet !== 'object' || !(options === null || options === void 0 ? void 0 : options.url)) { + throw new Error('@supabase/auth-js: Both wallet and url must be specified in non-browser environments.'); + } + resolvedWallet = wallet; + } + else if (typeof wallet === 'object') { + resolvedWallet = wallet; + } + else { + const windowAny = window; + if ('solana' in windowAny && + typeof windowAny.solana === 'object' && + (('signIn' in windowAny.solana && typeof windowAny.solana.signIn === 'function') || + ('signMessage' in windowAny.solana && + typeof windowAny.solana.signMessage === 'function'))) { + resolvedWallet = windowAny.solana; + } + else { + throw new Error(`@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.`); + } + } + const url = new URL((_a = options === null || options === void 0 ? void 0 : options.url) !== null && _a !== void 0 ? _a : window.location.href); + if ('signIn' in resolvedWallet && resolvedWallet.signIn) { + const output = await resolvedWallet.signIn(Object.assign(Object.assign(Object.assign({ issuedAt: new Date().toISOString() }, options === null || options === void 0 ? void 0 : options.signInWithSolana), { + // non-overridable properties + version: '1', domain: url.host, uri: url.href }), (statement ? { statement } : null))); + let outputToProcess; + if (Array.isArray(output) && output[0] && typeof output[0] === 'object') { + outputToProcess = output[0]; + } + else if (output && + typeof output === 'object' && + 'signedMessage' in output && + 'signature' in output) { + outputToProcess = output; + } + else { + throw new Error('@supabase/auth-js: Wallet method signIn() returned unrecognized value'); + } + if ('signedMessage' in outputToProcess && + 'signature' in outputToProcess && + (typeof outputToProcess.signedMessage === 'string' || + outputToProcess.signedMessage instanceof Uint8Array) && + outputToProcess.signature instanceof Uint8Array) { + message = + typeof outputToProcess.signedMessage === 'string' + ? outputToProcess.signedMessage + : new TextDecoder().decode(outputToProcess.signedMessage); + signature = outputToProcess.signature; + } + else { + throw new Error('@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields'); + } + } + else { + if (!('signMessage' in resolvedWallet) || + typeof resolvedWallet.signMessage !== 'function' || + !('publicKey' in resolvedWallet) || + typeof resolvedWallet !== 'object' || + !resolvedWallet.publicKey || + !('toBase58' in resolvedWallet.publicKey) || + typeof resolvedWallet.publicKey.toBase58 !== 'function') { + throw new Error('@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API'); + } + message = [ + `${url.host} wants you to sign in with your Solana account:`, + resolvedWallet.publicKey.toBase58(), + ...(statement ? ['', statement, ''] : ['']), + 'Version: 1', + `URI: ${url.href}`, + `Issued At: ${(_c = (_b = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _b === void 0 ? void 0 : _b.issuedAt) !== null && _c !== void 0 ? _c : new Date().toISOString()}`, + ...(((_d = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _d === void 0 ? void 0 : _d.notBefore) + ? [`Not Before: ${options.signInWithSolana.notBefore}`] + : []), + ...(((_e = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _e === void 0 ? void 0 : _e.expirationTime) + ? [`Expiration Time: ${options.signInWithSolana.expirationTime}`] + : []), + ...(((_f = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _f === void 0 ? void 0 : _f.chainId) + ? [`Chain ID: ${options.signInWithSolana.chainId}`] + : []), + ...(((_g = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _g === void 0 ? void 0 : _g.nonce) ? [`Nonce: ${options.signInWithSolana.nonce}`] : []), + ...(((_h = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _h === void 0 ? void 0 : _h.requestId) + ? [`Request ID: ${options.signInWithSolana.requestId}`] + : []), + ...(((_k = (_j = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _j === void 0 ? void 0 : _j.resources) === null || _k === void 0 ? void 0 : _k.length) + ? [ + 'Resources', + ...options.signInWithSolana.resources.map((resource) => `- ${resource}`), + ] + : []), + ].join('\n'); + const maybeSignature = await resolvedWallet.signMessage(new TextEncoder().encode(message), 'utf8'); + if (!maybeSignature || !(maybeSignature instanceof Uint8Array)) { + throw new Error('@supabase/auth-js: Wallet signMessage() API returned an recognized value'); + } + signature = maybeSignature; + } + } + try { + const { data, error } = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=web3`, { + headers: this.headers, + body: Object.assign({ chain: 'solana', message, signature: bytesToBase64URL(signature) }, (((_l = credentials.options) === null || _l === void 0 ? void 0 : _l.captchaToken) + ? { gotrue_meta_security: { captcha_token: (_m = credentials.options) === null || _m === void 0 ? void 0 : _m.captchaToken } } + : null)), + xform: _sessionResponse, + }); + if (error) { + throw error; + } + if (!data || !data.session || !data.user) { + const invalidTokenError = new AuthInvalidTokenResponseError(); + return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError }); + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', data.session); + } + return this._returnResult({ data: Object.assign({}, data), error }); + } + catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + async _exchangeCodeForSession(authCode) { + const storageItem = await getItemAsync(this.storage, `${this.storageKey}-code-verifier`); + const [codeVerifier, redirectType] = (storageItem !== null && storageItem !== void 0 ? storageItem : '').split('/'); + try { + const { data, error } = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=pkce`, { + headers: this.headers, + body: { + auth_code: authCode, + code_verifier: codeVerifier, + }, + xform: _sessionResponse, + }); + await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`); + if (error) { + throw error; + } + if (!data || !data.session || !data.user) { + const invalidTokenError = new AuthInvalidTokenResponseError(); + return this._returnResult({ + data: { user: null, session: null, redirectType: null }, + error: invalidTokenError, + }); + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', data.session); + } + return this._returnResult({ data: Object.assign(Object.assign({}, data), { redirectType: redirectType !== null && redirectType !== void 0 ? redirectType : null }), error }); + } + catch (error) { + await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`); + if (isAuthError(error)) { + return this._returnResult({ + data: { user: null, session: null, redirectType: null }, + error, + }); + } + throw error; + } + } + /** + * Allows signing in with an OIDC ID token. The authentication provider used + * should be enabled and configured. + */ + async signInWithIdToken(credentials) { + try { + const { options, provider, token, access_token, nonce } = credentials; + const res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=id_token`, { + headers: this.headers, + body: { + provider, + id_token: token, + access_token, + nonce, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + xform: _sessionResponse, + }); + const { data, error } = res; + if (error) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + else if (!data || !data.session || !data.user) { + const invalidTokenError = new AuthInvalidTokenResponseError(); + return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError }); + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', data.session); + } + return this._returnResult({ data, error }); + } + catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + /** + * Log in a user using magiclink or a one-time password (OTP). + * + * If the `{{ .ConfirmationURL }}` variable is specified in the email template, a magiclink will be sent. + * If the `{{ .Token }}` variable is specified in the email template, an OTP will be sent. + * If you're using phone sign-ins, only an OTP will be sent. You won't be able to send a magiclink for phone sign-ins. + * + * Be aware that you may get back an error message that will not distinguish + * between the cases where the account does not exist or, that the account + * can only be accessed via social login. + * + * Do note that you will need to configure a Whatsapp sender on Twilio + * if you are using phone sign in with the 'whatsapp' channel. The whatsapp + * channel is not supported on other providers + * at this time. + * This method supports PKCE when an email is passed. + */ + async signInWithOtp(credentials) { + var _a, _b, _c, _d, _e; + try { + if ('email' in credentials) { + const { email, options } = credentials; + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === 'pkce') { + ; + [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(this.storage, this.storageKey); + } + const { error } = await _request(this.fetch, 'POST', `${this.url}/otp`, { + headers: this.headers, + body: { + email, + data: (_a = options === null || options === void 0 ? void 0 : options.data) !== null && _a !== void 0 ? _a : {}, + create_user: (_b = options === null || options === void 0 ? void 0 : options.shouldCreateUser) !== null && _b !== void 0 ? _b : true, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + code_challenge: codeChallenge, + code_challenge_method: codeChallengeMethod, + }, + redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, + }); + return this._returnResult({ data: { user: null, session: null }, error }); + } + if ('phone' in credentials) { + const { phone, options } = credentials; + const { data, error } = await _request(this.fetch, 'POST', `${this.url}/otp`, { + headers: this.headers, + body: { + phone, + data: (_c = options === null || options === void 0 ? void 0 : options.data) !== null && _c !== void 0 ? _c : {}, + create_user: (_d = options === null || options === void 0 ? void 0 : options.shouldCreateUser) !== null && _d !== void 0 ? _d : true, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + channel: (_e = options === null || options === void 0 ? void 0 : options.channel) !== null && _e !== void 0 ? _e : 'sms', + }, + }); + return this._returnResult({ + data: { user: null, session: null, messageId: data === null || data === void 0 ? void 0 : data.message_id }, + error, + }); + } + throw new AuthInvalidCredentialsError('You must provide either an email or phone number.'); + } + catch (error) { + await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`); + if (isAuthError(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + /** + * Log in a user given a User supplied OTP or TokenHash received through mobile or email. + */ + async verifyOtp(params) { + var _a, _b; + try { + let redirectTo = undefined; + let captchaToken = undefined; + if ('options' in params) { + redirectTo = (_a = params.options) === null || _a === void 0 ? void 0 : _a.redirectTo; + captchaToken = (_b = params.options) === null || _b === void 0 ? void 0 : _b.captchaToken; + } + const { data, error } = await _request(this.fetch, 'POST', `${this.url}/verify`, { + headers: this.headers, + body: Object.assign(Object.assign({}, params), { gotrue_meta_security: { captcha_token: captchaToken } }), + redirectTo, + xform: _sessionResponse, + }); + if (error) { + throw error; + } + if (!data) { + const tokenVerificationError = new Error('An error occurred on token verification.'); + throw tokenVerificationError; + } + const session = data.session; + const user = data.user; + if (session === null || session === void 0 ? void 0 : session.access_token) { + await this._saveSession(session); + await this._notifyAllSubscribers(params.type == 'recovery' ? 'PASSWORD_RECOVERY' : 'SIGNED_IN', session); + } + return this._returnResult({ data: { user, session }, error: null }); + } + catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + /** + * Attempts a single-sign on using an enterprise Identity Provider. A + * successful SSO attempt will redirect the current page to the identity + * provider authorization page. The redirect URL is implementation and SSO + * protocol specific. + * + * You can use it by providing a SSO domain. Typically you can extract this + * domain by asking users for their email address. If this domain is + * registered on the Auth instance the redirect will use that organization's + * currently active SSO Identity Provider for the login. + * + * If you have built an organization-specific login page, you can use the + * organization's SSO Identity Provider UUID directly instead. + */ + async signInWithSSO(params) { + var _a, _b, _c, _d, _e; + try { + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === 'pkce') { + ; + [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(this.storage, this.storageKey); + } + const result = await _request(this.fetch, 'POST', `${this.url}/sso`, { + body: Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, ('providerId' in params ? { provider_id: params.providerId } : null)), ('domain' in params ? { domain: params.domain } : null)), { redirect_to: (_b = (_a = params.options) === null || _a === void 0 ? void 0 : _a.redirectTo) !== null && _b !== void 0 ? _b : undefined }), (((_c = params === null || params === void 0 ? void 0 : params.options) === null || _c === void 0 ? void 0 : _c.captchaToken) + ? { gotrue_meta_security: { captcha_token: params.options.captchaToken } } + : null)), { skip_http_redirect: true, code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod }), + headers: this.headers, + xform: _ssoResponse, + }); + // Automatically redirect in browser unless skipBrowserRedirect is true + if (((_d = result.data) === null || _d === void 0 ? void 0 : _d.url) && isBrowser() && !((_e = params.options) === null || _e === void 0 ? void 0 : _e.skipBrowserRedirect)) { + window.location.assign(result.data.url); + } + return this._returnResult(result); + } + catch (error) { + await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`); + if (isAuthError(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + /** + * Sends a reauthentication OTP to the user's email or phone number. + * Requires the user to be signed-in. + */ + async reauthenticate() { + await this.initializePromise; + return await this._acquireLock(-1, async () => { + return await this._reauthenticate(); + }); + } + async _reauthenticate() { + try { + return await this._useSession(async (result) => { + const { data: { session }, error: sessionError, } = result; + if (sessionError) + throw sessionError; + if (!session) + throw new AuthSessionMissingError(); + const { error } = await _request(this.fetch, 'GET', `${this.url}/reauthenticate`, { + headers: this.headers, + jwt: session.access_token, + }); + return this._returnResult({ data: { user: null, session: null }, error }); + }); + } + catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + /** + * Resends an existing signup confirmation email, email change email, SMS OTP or phone change OTP. + */ + async resend(credentials) { + try { + const endpoint = `${this.url}/resend`; + if ('email' in credentials) { + const { email, type, options } = credentials; + const { error } = await _request(this.fetch, 'POST', endpoint, { + headers: this.headers, + body: { + email, + type, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, + }); + return this._returnResult({ data: { user: null, session: null }, error }); + } + else if ('phone' in credentials) { + const { phone, type, options } = credentials; + const { data, error } = await _request(this.fetch, 'POST', endpoint, { + headers: this.headers, + body: { + phone, + type, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + }); + return this._returnResult({ + data: { user: null, session: null, messageId: data === null || data === void 0 ? void 0 : data.message_id }, + error, + }); + } + throw new AuthInvalidCredentialsError('You must provide either an email or phone number and a type'); + } + catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + /** + * Returns the session, refreshing it if necessary. + * + * The session returned can be null if the session is not detected which can happen in the event a user is not signed-in or has logged out. + * + * **IMPORTANT:** This method loads values directly from the storage attached + * to the client. If that storage is based on request cookies for example, + * the values in it may not be authentic and therefore it's strongly advised + * against using this method and its results in such circumstances. A warning + * will be emitted if this is detected. Use {@link #getUser()} instead. + */ + async getSession() { + await this.initializePromise; + const result = await this._acquireLock(-1, async () => { + return this._useSession(async (result) => { + return result; + }); + }); + return result; + } + /** + * Acquires a global lock based on the storage key. + */ + async _acquireLock(acquireTimeout, fn) { + this._debug('#_acquireLock', 'begin', acquireTimeout); + try { + if (this.lockAcquired) { + const last = this.pendingInLock.length + ? this.pendingInLock[this.pendingInLock.length - 1] + : Promise.resolve(); + const result = (async () => { + await last; + return await fn(); + })(); + this.pendingInLock.push((async () => { + try { + await result; + } + catch (e) { + // we just care if it finished + } + })()); + return result; + } + return await this.lock(`lock:${this.storageKey}`, acquireTimeout, async () => { + this._debug('#_acquireLock', 'lock acquired for storage key', this.storageKey); + try { + this.lockAcquired = true; + const result = fn(); + this.pendingInLock.push((async () => { + try { + await result; + } + catch (e) { + // we just care if it finished + } + })()); + await result; + // keep draining the queue until there's nothing to wait on + while (this.pendingInLock.length) { + const waitOn = [...this.pendingInLock]; + await Promise.all(waitOn); + this.pendingInLock.splice(0, waitOn.length); + } + return await result; + } + finally { + this._debug('#_acquireLock', 'lock released for storage key', this.storageKey); + this.lockAcquired = false; + } + }); + } + finally { + this._debug('#_acquireLock', 'end'); + } + } + /** + * Use instead of {@link #getSession} inside the library. It is + * semantically usually what you want, as getting a session involves some + * processing afterwards that requires only one client operating on the + * session at once across multiple tabs or processes. + */ + async _useSession(fn) { + this._debug('#_useSession', 'begin'); + try { + // the use of __loadSession here is the only correct use of the function! + const result = await this.__loadSession(); + return await fn(result); + } + finally { + this._debug('#_useSession', 'end'); + } + } + /** + * NEVER USE DIRECTLY! + * + * Always use {@link #_useSession}. + */ + async __loadSession() { + this._debug('#__loadSession()', 'begin'); + if (!this.lockAcquired) { + this._debug('#__loadSession()', 'used outside of an acquired lock!', new Error().stack); + } + try { + let currentSession = null; + const maybeSession = await getItemAsync(this.storage, this.storageKey); + this._debug('#getSession()', 'session from storage', maybeSession); + if (maybeSession !== null) { + if (this._isValidSession(maybeSession)) { + currentSession = maybeSession; + } + else { + this._debug('#getSession()', 'session from storage is not valid'); + await this._removeSession(); + } + } + if (!currentSession) { + return { data: { session: null }, error: null }; + } + // A session is considered expired before the access token _actually_ + // expires. When the autoRefreshToken option is off (or when the tab is + // in the background), very eager users of getSession() -- like + // realtime-js -- might send a valid JWT which will expire by the time it + // reaches the server. + const hasExpired = currentSession.expires_at + ? currentSession.expires_at * 1000 - Date.now() < EXPIRY_MARGIN_MS + : false; + this._debug('#__loadSession()', `session has${hasExpired ? '' : ' not'} expired`, 'expires_at', currentSession.expires_at); + if (!hasExpired) { + if (this.userStorage) { + const maybeUser = (await getItemAsync(this.userStorage, this.storageKey + '-user')); + if (maybeUser === null || maybeUser === void 0 ? void 0 : maybeUser.user) { + currentSession.user = maybeUser.user; + } + else { + currentSession.user = userNotAvailableProxy(); + } + } + // Wrap the user object with a warning proxy on the server + // This warns when properties of the user are accessed, not when session.user itself is accessed + if (this.storage.isServer && + currentSession.user && + !currentSession.user.__isUserNotAvailableProxy) { + const suppressWarningRef = { value: this.suppressGetSessionWarning }; + currentSession.user = insecureUserWarningProxy(currentSession.user, suppressWarningRef); + // Update the client-level suppression flag when the proxy suppresses the warning + if (suppressWarningRef.value) { + this.suppressGetSessionWarning = true; + } + } + return { data: { session: currentSession }, error: null }; + } + const { data: session, error } = await this._callRefreshToken(currentSession.refresh_token); + if (error) { + return this._returnResult({ data: { session: null }, error }); + } + return this._returnResult({ data: { session }, error: null }); + } + finally { + this._debug('#__loadSession()', 'end'); + } + } + /** + * Gets the current user details if there is an existing session. This method + * performs a network request to the Supabase Auth server, so the returned + * value is authentic and can be used to base authorization rules on. + * + * @param jwt Takes in an optional access token JWT. If no JWT is provided, the JWT from the current session is used. + */ + async getUser(jwt) { + if (jwt) { + return await this._getUser(jwt); + } + await this.initializePromise; + const result = await this._acquireLock(-1, async () => { + return await this._getUser(); + }); + if (result.data.user) { + this.suppressGetSessionWarning = true; + } + return result; + } + async _getUser(jwt) { + try { + if (jwt) { + return await _request(this.fetch, 'GET', `${this.url}/user`, { + headers: this.headers, + jwt: jwt, + xform: _userResponse, + }); + } + return await this._useSession(async (result) => { + var _a, _b, _c; + const { data, error } = result; + if (error) { + throw error; + } + // returns an error if there is no access_token or custom authorization header + if (!((_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) && !this.hasCustomAuthorizationHeader) { + return { data: { user: null }, error: new AuthSessionMissingError() }; + } + return await _request(this.fetch, 'GET', `${this.url}/user`, { + headers: this.headers, + jwt: (_c = (_b = data.session) === null || _b === void 0 ? void 0 : _b.access_token) !== null && _c !== void 0 ? _c : undefined, + xform: _userResponse, + }); + }); + } + catch (error) { + if (isAuthError(error)) { + if (isAuthSessionMissingError(error)) { + // JWT contains a `session_id` which does not correspond to an active + // session in the database, indicating the user is signed out. + await this._removeSession(); + await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`); + } + return this._returnResult({ data: { user: null }, error }); + } + throw error; + } + } + /** + * Updates user data for a logged in user. + */ + async updateUser(attributes, options = {}) { + await this.initializePromise; + return await this._acquireLock(-1, async () => { + return await this._updateUser(attributes, options); + }); + } + async _updateUser(attributes, options = {}) { + try { + return await this._useSession(async (result) => { + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + throw sessionError; + } + if (!sessionData.session) { + throw new AuthSessionMissingError(); + } + const session = sessionData.session; + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === 'pkce' && attributes.email != null) { + ; + [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(this.storage, this.storageKey); + } + const { data, error: userError } = await _request(this.fetch, 'PUT', `${this.url}/user`, { + headers: this.headers, + redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, + body: Object.assign(Object.assign({}, attributes), { code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod }), + jwt: session.access_token, + xform: _userResponse, + }); + if (userError) { + throw userError; + } + session.user = data.user; + await this._saveSession(session); + await this._notifyAllSubscribers('USER_UPDATED', session); + return this._returnResult({ data: { user: session.user }, error: null }); + }); + } + catch (error) { + await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`); + if (isAuthError(error)) { + return this._returnResult({ data: { user: null }, error }); + } + throw error; + } + } + /** + * Sets the session data from the current session. If the current session is expired, setSession will take care of refreshing it to obtain a new session. + * If the refresh token or access token in the current session is invalid, an error will be thrown. + * @param currentSession The current session that minimally contains an access token and refresh token. + */ + async setSession(currentSession) { + await this.initializePromise; + return await this._acquireLock(-1, async () => { + return await this._setSession(currentSession); + }); + } + async _setSession(currentSession) { + try { + if (!currentSession.access_token || !currentSession.refresh_token) { + throw new AuthSessionMissingError(); + } + const timeNow = Date.now() / 1000; + let expiresAt = timeNow; + let hasExpired = true; + let session = null; + const { payload } = decodeJWT(currentSession.access_token); + if (payload.exp) { + expiresAt = payload.exp; + hasExpired = expiresAt <= timeNow; + } + if (hasExpired) { + const { data: refreshedSession, error } = await this._callRefreshToken(currentSession.refresh_token); + if (error) { + return this._returnResult({ data: { user: null, session: null }, error: error }); + } + if (!refreshedSession) { + return { data: { user: null, session: null }, error: null }; + } + session = refreshedSession; + } + else { + const { data, error } = await this._getUser(currentSession.access_token); + if (error) { + throw error; + } + session = { + access_token: currentSession.access_token, + refresh_token: currentSession.refresh_token, + user: data.user, + token_type: 'bearer', + expires_in: expiresAt - timeNow, + expires_at: expiresAt, + }; + await this._saveSession(session); + await this._notifyAllSubscribers('SIGNED_IN', session); + } + return this._returnResult({ data: { user: session.user, session }, error: null }); + } + catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: { session: null, user: null }, error }); + } + throw error; + } + } + /** + * Returns a new session, regardless of expiry status. + * Takes in an optional current session. If not passed in, then refreshSession() will attempt to retrieve it from getSession(). + * If the current session's refresh token is invalid, an error will be thrown. + * @param currentSession The current session. If passed in, it must contain a refresh token. + */ + async refreshSession(currentSession) { + await this.initializePromise; + return await this._acquireLock(-1, async () => { + return await this._refreshSession(currentSession); + }); + } + async _refreshSession(currentSession) { + try { + return await this._useSession(async (result) => { + var _a; + if (!currentSession) { + const { data, error } = result; + if (error) { + throw error; + } + currentSession = (_a = data.session) !== null && _a !== void 0 ? _a : undefined; + } + if (!(currentSession === null || currentSession === void 0 ? void 0 : currentSession.refresh_token)) { + throw new AuthSessionMissingError(); + } + const { data: session, error } = await this._callRefreshToken(currentSession.refresh_token); + if (error) { + return this._returnResult({ data: { user: null, session: null }, error: error }); + } + if (!session) { + return this._returnResult({ data: { user: null, session: null }, error: null }); + } + return this._returnResult({ data: { user: session.user, session }, error: null }); + }); + } + catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + /** + * Gets the session data from a URL string + */ + async _getSessionFromURL(params, callbackUrlType) { + try { + if (!isBrowser()) + throw new AuthImplicitGrantRedirectError('No browser detected.'); + // If there's an error in the URL, it doesn't matter what flow it is, we just return the error. + if (params.error || params.error_description || params.error_code) { + // The error class returned implies that the redirect is from an implicit grant flow + // but it could also be from a redirect error from a PKCE flow. + throw new AuthImplicitGrantRedirectError(params.error_description || 'Error in URL with unspecified error_description', { + error: params.error || 'unspecified_error', + code: params.error_code || 'unspecified_code', + }); + } + // Checks for mismatches between the flowType initialised in the client and the URL parameters + switch (callbackUrlType) { + case 'implicit': + if (this.flowType === 'pkce') { + throw new AuthPKCEGrantCodeExchangeError('Not a valid PKCE flow url.'); + } + break; + case 'pkce': + if (this.flowType === 'implicit') { + throw new AuthImplicitGrantRedirectError('Not a valid implicit grant flow url.'); + } + break; + default: + // there's no mismatch so we continue + } + // Since this is a redirect for PKCE, we attempt to retrieve the code from the URL for the code exchange + if (callbackUrlType === 'pkce') { + this._debug('#_initialize()', 'begin', 'is PKCE flow', true); + if (!params.code) + throw new AuthPKCEGrantCodeExchangeError('No code detected.'); + const { data, error } = await this._exchangeCodeForSession(params.code); + if (error) + throw error; + const url = new URL(window.location.href); + url.searchParams.delete('code'); + window.history.replaceState(window.history.state, '', url.toString()); + return { data: { session: data.session, redirectType: null }, error: null }; + } + const { provider_token, provider_refresh_token, access_token, refresh_token, expires_in, expires_at, token_type, } = params; + if (!access_token || !expires_in || !refresh_token || !token_type) { + throw new AuthImplicitGrantRedirectError('No session defined in URL'); + } + const timeNow = Math.round(Date.now() / 1000); + const expiresIn = parseInt(expires_in); + let expiresAt = timeNow + expiresIn; + if (expires_at) { + expiresAt = parseInt(expires_at); + } + const actuallyExpiresIn = expiresAt - timeNow; + if (actuallyExpiresIn * 1000 <= AUTO_REFRESH_TICK_DURATION_MS) { + console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${actuallyExpiresIn}s, should have been closer to ${expiresIn}s`); + } + const issuedAt = expiresAt - expiresIn; + if (timeNow - issuedAt >= 120) { + console.warn('@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale', issuedAt, expiresAt, timeNow); + } + else if (timeNow - issuedAt < 0) { + console.warn('@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew', issuedAt, expiresAt, timeNow); + } + const { data, error } = await this._getUser(access_token); + if (error) + throw error; + const session = { + provider_token, + provider_refresh_token, + access_token, + expires_in: expiresIn, + expires_at: expiresAt, + refresh_token, + token_type: token_type, + user: data.user, + }; + // Remove tokens from URL + window.location.hash = ''; + this._debug('#_getSessionFromURL()', 'clearing window.location.hash'); + return this._returnResult({ data: { session, redirectType: params.type }, error: null }); + } + catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: { session: null, redirectType: null }, error }); + } + throw error; + } + } + /** + * Checks if the current URL contains parameters given by an implicit oauth grant flow (https://www.rfc-editor.org/rfc/rfc6749.html#section-4.2) + */ + _isImplicitGrantCallback(params) { + return Boolean(params.access_token || params.error_description); + } + /** + * Checks if the current URL and backing storage contain parameters given by a PKCE flow + */ + async _isPKCECallback(params) { + const currentStorageContent = await getItemAsync(this.storage, `${this.storageKey}-code-verifier`); + return !!(params.code && currentStorageContent); + } + /** + * Inside a browser context, `signOut()` will remove the logged in user from the browser session and log them out - removing all items from localstorage and then trigger a `"SIGNED_OUT"` event. + * + * For server-side management, you can revoke all refresh tokens for a user by passing a user's JWT through to `auth.api.signOut(JWT: string)`. + * There is no way to revoke a user's access token jwt until it expires. It is recommended to set a shorter expiry on the jwt for this reason. + * + * If using `others` scope, no `SIGNED_OUT` event is fired! + */ + async signOut(options = { scope: 'global' }) { + await this.initializePromise; + return await this._acquireLock(-1, async () => { + return await this._signOut(options); + }); + } + async _signOut({ scope } = { scope: 'global' }) { + return await this._useSession(async (result) => { + var _a; + const { data, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ error: sessionError }); + } + const accessToken = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token; + if (accessToken) { + const { error } = await this.admin.signOut(accessToken, scope); + if (error) { + // ignore 404s since user might not exist anymore + // ignore 401s since an invalid or expired JWT should sign out the current session + if (!(isAuthApiError(error) && + (error.status === 404 || error.status === 401 || error.status === 403))) { + return this._returnResult({ error }); + } + } + } + if (scope !== 'others') { + await this._removeSession(); + await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`); + } + return this._returnResult({ error: null }); + }); + } + onAuthStateChange(callback) { + const id = generateCallbackId(); + const subscription = { + id, + callback, + unsubscribe: () => { + this._debug('#unsubscribe()', 'state change callback with id removed', id); + this.stateChangeEmitters.delete(id); + }, + }; + this._debug('#onAuthStateChange()', 'registered callback with id', id); + this.stateChangeEmitters.set(id, subscription); + (async () => { + await this.initializePromise; + await this._acquireLock(-1, async () => { + this._emitInitialSession(id); + }); + })(); + return { data: { subscription } }; + } + async _emitInitialSession(id) { + return await this._useSession(async (result) => { + var _a, _b; + try { + const { data: { session }, error, } = result; + if (error) + throw error; + await ((_a = this.stateChangeEmitters.get(id)) === null || _a === void 0 ? void 0 : _a.callback('INITIAL_SESSION', session)); + this._debug('INITIAL_SESSION', 'callback id', id, 'session', session); + } + catch (err) { + await ((_b = this.stateChangeEmitters.get(id)) === null || _b === void 0 ? void 0 : _b.callback('INITIAL_SESSION', null)); + this._debug('INITIAL_SESSION', 'callback id', id, 'error', err); + console.error(err); + } + }); + } + /** + * Sends a password reset request to an email address. This method supports the PKCE flow. + * + * @param email The email address of the user. + * @param options.redirectTo The URL to send the user to after they click the password reset link. + * @param options.captchaToken Verification token received when the user completes the captcha on the site. + */ + async resetPasswordForEmail(email, options = {}) { + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === 'pkce') { + ; + [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(this.storage, this.storageKey, true // isPasswordRecovery + ); + } + try { + return await _request(this.fetch, 'POST', `${this.url}/recover`, { + body: { + email, + code_challenge: codeChallenge, + code_challenge_method: codeChallengeMethod, + gotrue_meta_security: { captcha_token: options.captchaToken }, + }, + headers: this.headers, + redirectTo: options.redirectTo, + }); + } + catch (error) { + await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`); + if (isAuthError(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + /** + * Gets all the identities linked to a user. + */ + async getUserIdentities() { + var _a; + try { + const { data, error } = await this.getUser(); + if (error) + throw error; + return this._returnResult({ data: { identities: (_a = data.user.identities) !== null && _a !== void 0 ? _a : [] }, error: null }); + } + catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + async linkIdentity(credentials) { + if ('token' in credentials) { + return this.linkIdentityIdToken(credentials); + } + return this.linkIdentityOAuth(credentials); + } + async linkIdentityOAuth(credentials) { + var _a; + try { + const { data, error } = await this._useSession(async (result) => { + var _a, _b, _c, _d, _e; + const { data, error } = result; + if (error) + throw error; + const url = await this._getUrlForProvider(`${this.url}/user/identities/authorize`, credentials.provider, { + redirectTo: (_a = credentials.options) === null || _a === void 0 ? void 0 : _a.redirectTo, + scopes: (_b = credentials.options) === null || _b === void 0 ? void 0 : _b.scopes, + queryParams: (_c = credentials.options) === null || _c === void 0 ? void 0 : _c.queryParams, + skipBrowserRedirect: true, + }); + return await _request(this.fetch, 'GET', url, { + headers: this.headers, + jwt: (_e = (_d = data.session) === null || _d === void 0 ? void 0 : _d.access_token) !== null && _e !== void 0 ? _e : undefined, + }); + }); + if (error) + throw error; + if (isBrowser() && !((_a = credentials.options) === null || _a === void 0 ? void 0 : _a.skipBrowserRedirect)) { + window.location.assign(data === null || data === void 0 ? void 0 : data.url); + } + return this._returnResult({ + data: { provider: credentials.provider, url: data === null || data === void 0 ? void 0 : data.url }, + error: null, + }); + } + catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: { provider: credentials.provider, url: null }, error }); + } + throw error; + } + } + async linkIdentityIdToken(credentials) { + return await this._useSession(async (result) => { + var _a; + try { + const { error: sessionError, data: { session }, } = result; + if (sessionError) + throw sessionError; + const { options, provider, token, access_token, nonce } = credentials; + const res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=id_token`, { + headers: this.headers, + jwt: (_a = session === null || session === void 0 ? void 0 : session.access_token) !== null && _a !== void 0 ? _a : undefined, + body: { + provider, + id_token: token, + access_token, + nonce, + link_identity: true, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + xform: _sessionResponse, + }); + const { data, error } = res; + if (error) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + else if (!data || !data.session || !data.user) { + return this._returnResult({ + data: { user: null, session: null }, + error: new AuthInvalidTokenResponseError(), + }); + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('USER_UPDATED', data.session); + } + return this._returnResult({ data, error }); + } + catch (error) { + await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`); + if (isAuthError(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + }); + } + /** + * Unlinks an identity from a user by deleting it. The user will no longer be able to sign in with that identity once it's unlinked. + */ + async unlinkIdentity(identity) { + try { + return await this._useSession(async (result) => { + var _a, _b; + const { data, error } = result; + if (error) { + throw error; + } + return await _request(this.fetch, 'DELETE', `${this.url}/user/identities/${identity.identity_id}`, { + headers: this.headers, + jwt: (_b = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) !== null && _b !== void 0 ? _b : undefined, + }); + }); + } + catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + /** + * Generates a new JWT. + * @param refreshToken A valid refresh token that was returned on login. + */ + async _refreshAccessToken(refreshToken) { + const debugName = `#_refreshAccessToken(${refreshToken.substring(0, 5)}...)`; + this._debug(debugName, 'begin'); + try { + const startedAt = Date.now(); + // will attempt to refresh the token with exponential backoff + return await retryable(async (attempt) => { + if (attempt > 0) { + await sleep(200 * Math.pow(2, attempt - 1)); // 200, 400, 800, ... + } + this._debug(debugName, 'refreshing attempt', attempt); + return await _request(this.fetch, 'POST', `${this.url}/token?grant_type=refresh_token`, { + body: { refresh_token: refreshToken }, + headers: this.headers, + xform: _sessionResponse, + }); + }, (attempt, error) => { + const nextBackOffInterval = 200 * Math.pow(2, attempt); + return (error && + isAuthRetryableFetchError(error) && + // retryable only if the request can be sent before the backoff overflows the tick duration + Date.now() + nextBackOffInterval - startedAt < AUTO_REFRESH_TICK_DURATION_MS); + }); + } + catch (error) { + this._debug(debugName, 'error', error); + if (isAuthError(error)) { + return this._returnResult({ data: { session: null, user: null }, error }); + } + throw error; + } + finally { + this._debug(debugName, 'end'); + } + } + _isValidSession(maybeSession) { + const isValidSession = typeof maybeSession === 'object' && + maybeSession !== null && + 'access_token' in maybeSession && + 'refresh_token' in maybeSession && + 'expires_at' in maybeSession; + return isValidSession; + } + async _handleProviderSignIn(provider, options) { + const url = await this._getUrlForProvider(`${this.url}/authorize`, provider, { + redirectTo: options.redirectTo, + scopes: options.scopes, + queryParams: options.queryParams, + }); + this._debug('#_handleProviderSignIn()', 'provider', provider, 'options', options, 'url', url); + // try to open on the browser + if (isBrowser() && !options.skipBrowserRedirect) { + window.location.assign(url); + } + return { data: { provider, url }, error: null }; + } + /** + * Recovers the session from LocalStorage and refreshes the token + * Note: this method is async to accommodate for AsyncStorage e.g. in React native. + */ + async _recoverAndRefresh() { + var _a, _b; + const debugName = '#_recoverAndRefresh()'; + this._debug(debugName, 'begin'); + try { + const currentSession = (await getItemAsync(this.storage, this.storageKey)); + if (currentSession && this.userStorage) { + let maybeUser = (await getItemAsync(this.userStorage, this.storageKey + '-user')); + if (!this.storage.isServer && Object.is(this.storage, this.userStorage) && !maybeUser) { + // storage and userStorage are the same storage medium, for example + // window.localStorage if userStorage does not have the user from + // storage stored, store it first thereby migrating the user object + // from storage -> userStorage + maybeUser = { user: currentSession.user }; + await setItemAsync(this.userStorage, this.storageKey + '-user', maybeUser); + } + currentSession.user = (_a = maybeUser === null || maybeUser === void 0 ? void 0 : maybeUser.user) !== null && _a !== void 0 ? _a : userNotAvailableProxy(); + } + else if (currentSession && !currentSession.user) { + // user storage is not set, let's check if it was previously enabled so + // we bring back the storage as it should be + if (!currentSession.user) { + // test if userStorage was previously enabled and the storage medium was the same, to move the user back under the same key + const separateUser = (await getItemAsync(this.storage, this.storageKey + '-user')); + if (separateUser && (separateUser === null || separateUser === void 0 ? void 0 : separateUser.user)) { + currentSession.user = separateUser.user; + await removeItemAsync(this.storage, this.storageKey + '-user'); + await setItemAsync(this.storage, this.storageKey, currentSession); + } + else { + currentSession.user = userNotAvailableProxy(); + } + } + } + this._debug(debugName, 'session from storage', currentSession); + if (!this._isValidSession(currentSession)) { + this._debug(debugName, 'session is not valid'); + if (currentSession !== null) { + await this._removeSession(); + } + return; + } + const expiresWithMargin = ((_b = currentSession.expires_at) !== null && _b !== void 0 ? _b : Infinity) * 1000 - Date.now() < EXPIRY_MARGIN_MS; + this._debug(debugName, `session has${expiresWithMargin ? '' : ' not'} expired with margin of ${EXPIRY_MARGIN_MS}s`); + if (expiresWithMargin) { + if (this.autoRefreshToken && currentSession.refresh_token) { + const { error } = await this._callRefreshToken(currentSession.refresh_token); + if (error) { + console.error(error); + if (!isAuthRetryableFetchError(error)) { + this._debug(debugName, 'refresh failed with a non-retryable error, removing the session', error); + await this._removeSession(); + } + } + } + } + else if (currentSession.user && + currentSession.user.__isUserNotAvailableProxy === true) { + // If we have a proxy user, try to get the real user data + try { + const { data, error: userError } = await this._getUser(currentSession.access_token); + if (!userError && (data === null || data === void 0 ? void 0 : data.user)) { + currentSession.user = data.user; + await this._saveSession(currentSession); + await this._notifyAllSubscribers('SIGNED_IN', currentSession); + } + else { + this._debug(debugName, 'could not get user data, skipping SIGNED_IN notification'); + } + } + catch (getUserError) { + console.error('Error getting user data:', getUserError); + this._debug(debugName, 'error getting user data, skipping SIGNED_IN notification', getUserError); + } + } + else { + // no need to persist currentSession again, as we just loaded it from + // local storage; persisting it again may overwrite a value saved by + // another client with access to the same local storage + await this._notifyAllSubscribers('SIGNED_IN', currentSession); + } + } + catch (err) { + this._debug(debugName, 'error', err); + console.error(err); + return; + } + finally { + this._debug(debugName, 'end'); + } + } + async _callRefreshToken(refreshToken) { + var _a, _b; + if (!refreshToken) { + throw new AuthSessionMissingError(); + } + // refreshing is already in progress + if (this.refreshingDeferred) { + return this.refreshingDeferred.promise; + } + const debugName = `#_callRefreshToken(${refreshToken.substring(0, 5)}...)`; + this._debug(debugName, 'begin'); + try { + this.refreshingDeferred = new Deferred(); + const { data, error } = await this._refreshAccessToken(refreshToken); + if (error) + throw error; + if (!data.session) + throw new AuthSessionMissingError(); + await this._saveSession(data.session); + await this._notifyAllSubscribers('TOKEN_REFRESHED', data.session); + const result = { data: data.session, error: null }; + this.refreshingDeferred.resolve(result); + return result; + } + catch (error) { + this._debug(debugName, 'error', error); + if (isAuthError(error)) { + const result = { data: null, error }; + if (!isAuthRetryableFetchError(error)) { + await this._removeSession(); + } + (_a = this.refreshingDeferred) === null || _a === void 0 ? void 0 : _a.resolve(result); + return result; + } + (_b = this.refreshingDeferred) === null || _b === void 0 ? void 0 : _b.reject(error); + throw error; + } + finally { + this.refreshingDeferred = null; + this._debug(debugName, 'end'); + } + } + async _notifyAllSubscribers(event, session, broadcast = true) { + const debugName = `#_notifyAllSubscribers(${event})`; + this._debug(debugName, 'begin', session, `broadcast = ${broadcast}`); + try { + if (this.broadcastChannel && broadcast) { + this.broadcastChannel.postMessage({ event, session }); + } + const errors = []; + const promises = Array.from(this.stateChangeEmitters.values()).map(async (x) => { + try { + await x.callback(event, session); + } + catch (e) { + errors.push(e); + } + }); + await Promise.all(promises); + if (errors.length > 0) { + for (let i = 0; i < errors.length; i += 1) { + console.error(errors[i]); + } + throw errors[0]; + } + } + finally { + this._debug(debugName, 'end'); + } + } + /** + * set currentSession and currentUser + * process to _startAutoRefreshToken if possible + */ + async _saveSession(session) { + this._debug('#_saveSession()', session); + // _saveSession is always called whenever a new session has been acquired + // so we can safely suppress the warning returned by future getSession calls + this.suppressGetSessionWarning = true; + await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`); + // Create a shallow copy to work with, to avoid mutating the original session object if it's used elsewhere + const sessionToProcess = Object.assign({}, session); + const userIsProxy = sessionToProcess.user && sessionToProcess.user.__isUserNotAvailableProxy === true; + if (this.userStorage) { + if (!userIsProxy && sessionToProcess.user) { + // If it's a real user object, save it to userStorage. + await setItemAsync(this.userStorage, this.storageKey + '-user', { + user: sessionToProcess.user, + }); + } + else if (userIsProxy) { + // If it's the proxy, it means user was not found in userStorage. + // We should ensure no stale user data for this key exists in userStorage if we were to save null, + // or simply not save the proxy. For now, we don't save the proxy here. + // If there's a need to clear userStorage if user becomes proxy, that logic would go here. + } + // Prepare the main session data for primary storage: remove the user property before cloning + // This is important because the original session.user might be the proxy + const mainSessionData = Object.assign({}, sessionToProcess); + delete mainSessionData.user; // Remove user (real or proxy) before cloning for main storage + const clonedMainSessionData = deepClone(mainSessionData); + await setItemAsync(this.storage, this.storageKey, clonedMainSessionData); + } + else { + // No userStorage is configured. + // In this case, session.user should ideally not be a proxy. + // If it were, structuredClone would fail. This implies an issue elsewhere if user is a proxy here + const clonedSession = deepClone(sessionToProcess); // sessionToProcess still has its original user property + await setItemAsync(this.storage, this.storageKey, clonedSession); + } + } + async _removeSession() { + this._debug('#_removeSession()'); + this.suppressGetSessionWarning = false; + await removeItemAsync(this.storage, this.storageKey); + await removeItemAsync(this.storage, this.storageKey + '-code-verifier'); + await removeItemAsync(this.storage, this.storageKey + '-user'); + if (this.userStorage) { + await removeItemAsync(this.userStorage, this.storageKey + '-user'); + } + await this._notifyAllSubscribers('SIGNED_OUT', null); + } + /** + * Removes any registered visibilitychange callback. + * + * {@see #startAutoRefresh} + * {@see #stopAutoRefresh} + */ + _removeVisibilityChangedCallback() { + this._debug('#_removeVisibilityChangedCallback()'); + const callback = this.visibilityChangedCallback; + this.visibilityChangedCallback = null; + try { + if (callback && isBrowser() && (window === null || window === void 0 ? void 0 : window.removeEventListener)) { + window.removeEventListener('visibilitychange', callback); + } + } + catch (e) { + console.error('removing visibilitychange callback failed', e); + } + } + /** + * This is the private implementation of {@link #startAutoRefresh}. Use this + * within the library. + */ + async _startAutoRefresh() { + await this._stopAutoRefresh(); + this._debug('#_startAutoRefresh()'); + const ticker = setInterval(() => this._autoRefreshTokenTick(), AUTO_REFRESH_TICK_DURATION_MS); + this.autoRefreshTicker = ticker; + if (ticker && typeof ticker === 'object' && typeof ticker.unref === 'function') { + // ticker is a NodeJS Timeout object that has an `unref` method + // https://nodejs.org/api/timers.html#timeoutunref + // When auto refresh is used in NodeJS (like for testing) the + // `setInterval` is preventing the process from being marked as + // finished and tests run endlessly. This can be prevented by calling + // `unref()` on the returned object. + ticker.unref(); + // @ts-expect-error TS has no context of Deno + } + else if (typeof Deno !== 'undefined' && typeof Deno.unrefTimer === 'function') { + // similar like for NodeJS, but with the Deno API + // https://deno.land/api@latest?unstable&s=Deno.unrefTimer + // @ts-expect-error TS has no context of Deno + Deno.unrefTimer(ticker); + } + // run the tick immediately, but in the next pass of the event loop so that + // #_initialize can be allowed to complete without recursively waiting on + // itself + setTimeout(async () => { + await this.initializePromise; + await this._autoRefreshTokenTick(); + }, 0); + } + /** + * This is the private implementation of {@link #stopAutoRefresh}. Use this + * within the library. + */ + async _stopAutoRefresh() { + this._debug('#_stopAutoRefresh()'); + const ticker = this.autoRefreshTicker; + this.autoRefreshTicker = null; + if (ticker) { + clearInterval(ticker); + } + } + /** + * Starts an auto-refresh process in the background. The session is checked + * every few seconds. Close to the time of expiration a process is started to + * refresh the session. If refreshing fails it will be retried for as long as + * necessary. + * + * If you set the {@link GoTrueClientOptions#autoRefreshToken} you don't need + * to call this function, it will be called for you. + * + * On browsers the refresh process works only when the tab/window is in the + * foreground to conserve resources as well as prevent race conditions and + * flooding auth with requests. If you call this method any managed + * visibility change callback will be removed and you must manage visibility + * changes on your own. + * + * On non-browser platforms the refresh process works *continuously* in the + * background, which may not be desirable. You should hook into your + * platform's foreground indication mechanism and call these methods + * appropriately to conserve resources. + * + * {@see #stopAutoRefresh} + */ + async startAutoRefresh() { + this._removeVisibilityChangedCallback(); + await this._startAutoRefresh(); + } + /** + * Stops an active auto refresh process running in the background (if any). + * + * If you call this method any managed visibility change callback will be + * removed and you must manage visibility changes on your own. + * + * See {@link #startAutoRefresh} for more details. + */ + async stopAutoRefresh() { + this._removeVisibilityChangedCallback(); + await this._stopAutoRefresh(); + } + /** + * Runs the auto refresh token tick. + */ + async _autoRefreshTokenTick() { + this._debug('#_autoRefreshTokenTick()', 'begin'); + try { + await this._acquireLock(0, async () => { + try { + const now = Date.now(); + try { + return await this._useSession(async (result) => { + const { data: { session }, } = result; + if (!session || !session.refresh_token || !session.expires_at) { + this._debug('#_autoRefreshTokenTick()', 'no session'); + return; + } + // session will expire in this many ticks (or has already expired if <= 0) + const expiresInTicks = Math.floor((session.expires_at * 1000 - now) / AUTO_REFRESH_TICK_DURATION_MS); + this._debug('#_autoRefreshTokenTick()', `access token expires in ${expiresInTicks} ticks, a tick lasts ${AUTO_REFRESH_TICK_DURATION_MS}ms, refresh threshold is ${AUTO_REFRESH_TICK_THRESHOLD} ticks`); + if (expiresInTicks <= AUTO_REFRESH_TICK_THRESHOLD) { + await this._callRefreshToken(session.refresh_token); + } + }); + } + catch (e) { + console.error('Auto refresh tick failed with error. This is likely a transient error.', e); + } + } + finally { + this._debug('#_autoRefreshTokenTick()', 'end'); + } + }); + } + catch (e) { + if (e.isAcquireTimeout || e instanceof LockAcquireTimeoutError) { + this._debug('auto refresh token tick lock not available'); + } + else { + throw e; + } + } + } + /** + * Registers callbacks on the browser / platform, which in-turn run + * algorithms when the browser window/tab are in foreground. On non-browser + * platforms it assumes always foreground. + */ + async _handleVisibilityChange() { + this._debug('#_handleVisibilityChange()'); + if (!isBrowser() || !(window === null || window === void 0 ? void 0 : window.addEventListener)) { + if (this.autoRefreshToken) { + // in non-browser environments the refresh token ticker runs always + this.startAutoRefresh(); + } + return false; + } + try { + this.visibilityChangedCallback = async () => await this._onVisibilityChanged(false); + window === null || window === void 0 ? void 0 : window.addEventListener('visibilitychange', this.visibilityChangedCallback); + // now immediately call the visbility changed callback to setup with the + // current visbility state + await this._onVisibilityChanged(true); // initial call + } + catch (error) { + console.error('_handleVisibilityChange', error); + } + } + /** + * Callback registered with `window.addEventListener('visibilitychange')`. + */ + async _onVisibilityChanged(calledFromInitialize) { + const methodName = `#_onVisibilityChanged(${calledFromInitialize})`; + this._debug(methodName, 'visibilityState', document.visibilityState); + if (document.visibilityState === 'visible') { + if (this.autoRefreshToken) { + // in browser environments the refresh token ticker runs only on focused tabs + // which prevents race conditions + this._startAutoRefresh(); + } + if (!calledFromInitialize) { + // called when the visibility has changed, i.e. the browser + // transitioned from hidden -> visible so we need to see if the session + // should be recovered immediately... but to do that we need to acquire + // the lock first asynchronously + await this.initializePromise; + await this._acquireLock(-1, async () => { + if (document.visibilityState !== 'visible') { + this._debug(methodName, 'acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting'); + // visibility has changed while waiting for the lock, abort + return; + } + // recover the session + await this._recoverAndRefresh(); + }); + } + } + else if (document.visibilityState === 'hidden') { + if (this.autoRefreshToken) { + this._stopAutoRefresh(); + } + } + } + /** + * Generates the relevant login URL for a third-party provider. + * @param options.redirectTo A URL or mobile address to send the user to after they are confirmed. + * @param options.scopes A space-separated list of scopes granted to the OAuth application. + * @param options.queryParams An object of key-value pairs containing query parameters granted to the OAuth application. + */ + async _getUrlForProvider(url, provider, options) { + const urlParams = [`provider=${encodeURIComponent(provider)}`]; + if (options === null || options === void 0 ? void 0 : options.redirectTo) { + urlParams.push(`redirect_to=${encodeURIComponent(options.redirectTo)}`); + } + if (options === null || options === void 0 ? void 0 : options.scopes) { + urlParams.push(`scopes=${encodeURIComponent(options.scopes)}`); + } + if (this.flowType === 'pkce') { + const [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(this.storage, this.storageKey); + const flowParams = new URLSearchParams({ + code_challenge: `${encodeURIComponent(codeChallenge)}`, + code_challenge_method: `${encodeURIComponent(codeChallengeMethod)}`, + }); + urlParams.push(flowParams.toString()); + } + if (options === null || options === void 0 ? void 0 : options.queryParams) { + const query = new URLSearchParams(options.queryParams); + urlParams.push(query.toString()); + } + if (options === null || options === void 0 ? void 0 : options.skipBrowserRedirect) { + urlParams.push(`skip_http_redirect=${options.skipBrowserRedirect}`); + } + return `${url}?${urlParams.join('&')}`; + } + async _unenroll(params) { + try { + return await this._useSession(async (result) => { + var _a; + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + return await _request(this.fetch, 'DELETE', `${this.url}/factors/${params.factorId}`, { + headers: this.headers, + jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, + }); + }); + } + catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + async _enroll(params) { + try { + return await this._useSession(async (result) => { + var _a, _b; + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + const body = Object.assign({ friendly_name: params.friendlyName, factor_type: params.factorType }, (params.factorType === 'phone' + ? { phone: params.phone } + : params.factorType === 'totp' + ? { issuer: params.issuer } + : {})); + const { data, error } = (await _request(this.fetch, 'POST', `${this.url}/factors`, { + body, + headers: this.headers, + jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, + })); + if (error) { + return this._returnResult({ data: null, error }); + } + if (params.factorType === 'totp' && data.type === 'totp' && ((_b = data === null || data === void 0 ? void 0 : data.totp) === null || _b === void 0 ? void 0 : _b.qr_code)) { + data.totp.qr_code = `data:image/svg+xml;utf-8,${data.totp.qr_code}`; + } + return this._returnResult({ data, error: null }); + }); + } + catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + async _verify(params) { + return this._acquireLock(-1, async () => { + try { + return await this._useSession(async (result) => { + var _a; + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + const body = Object.assign({ challenge_id: params.challengeId }, ('webauthn' in params + ? { + webauthn: Object.assign(Object.assign({}, params.webauthn), { credential_response: params.webauthn.type === 'create' + ? serializeCredentialCreationResponse(params.webauthn.credential_response) + : serializeCredentialRequestResponse(params.webauthn.credential_response) }), + } + : { code: params.code })); + const { data, error } = await _request(this.fetch, 'POST', `${this.url}/factors/${params.factorId}/verify`, { + body, + headers: this.headers, + jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, + }); + if (error) { + return this._returnResult({ data: null, error }); + } + await this._saveSession(Object.assign({ expires_at: Math.round(Date.now() / 1000) + data.expires_in }, data)); + await this._notifyAllSubscribers('MFA_CHALLENGE_VERIFIED', data); + return this._returnResult({ data, error }); + }); + } + catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + }); + } + async _challenge(params) { + return this._acquireLock(-1, async () => { + try { + return await this._useSession(async (result) => { + var _a; + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + const response = (await _request(this.fetch, 'POST', `${this.url}/factors/${params.factorId}/challenge`, { + body: params, + headers: this.headers, + jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, + })); + if (response.error) { + return response; + } + const { data } = response; + if (data.type !== 'webauthn') { + return { data, error: null }; + } + switch (data.webauthn.type) { + case 'create': + return { + data: Object.assign(Object.assign({}, data), { webauthn: Object.assign(Object.assign({}, data.webauthn), { credential_options: Object.assign(Object.assign({}, data.webauthn.credential_options), { publicKey: deserializeCredentialCreationOptions(data.webauthn.credential_options.publicKey) }) }) }), + error: null, + }; + case 'request': + return { + data: Object.assign(Object.assign({}, data), { webauthn: Object.assign(Object.assign({}, data.webauthn), { credential_options: Object.assign(Object.assign({}, data.webauthn.credential_options), { publicKey: deserializeCredentialRequestOptions(data.webauthn.credential_options.publicKey) }) }) }), + error: null, + }; + } + }); + } + catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + }); + } + /** + * {@see GoTrueMFAApi#challengeAndVerify} + */ + async _challengeAndVerify(params) { + // both _challenge and _verify independently acquire the lock, so no need + // to acquire it here + const { data: challengeData, error: challengeError } = await this._challenge({ + factorId: params.factorId, + }); + if (challengeError) { + return this._returnResult({ data: null, error: challengeError }); + } + return await this._verify({ + factorId: params.factorId, + challengeId: challengeData.id, + code: params.code, + }); + } + /** + * {@see GoTrueMFAApi#listFactors} + */ + async _listFactors() { + var _a; + // use #getUser instead of #_getUser as the former acquires a lock + const { data: { user }, error: userError, } = await this.getUser(); + if (userError) { + return { data: null, error: userError }; + } + const data = { + all: [], + phone: [], + totp: [], + webauthn: [], + }; + // loop over the factors ONCE + for (const factor of (_a = user === null || user === void 0 ? void 0 : user.factors) !== null && _a !== void 0 ? _a : []) { + data.all.push(factor); + if (factor.status === 'verified') { + ; + data[factor.factor_type].push(factor); + } + } + return { + data, + error: null, + }; + } + /** + * {@see GoTrueMFAApi#getAuthenticatorAssuranceLevel} + */ + async _getAuthenticatorAssuranceLevel() { + var _a, _b; + const { data: { session }, error: sessionError, } = await this.getSession(); + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + if (!session) { + return { + data: { currentLevel: null, nextLevel: null, currentAuthenticationMethods: [] }, + error: null, + }; + } + const { payload } = decodeJWT(session.access_token); + let currentLevel = null; + if (payload.aal) { + currentLevel = payload.aal; + } + let nextLevel = currentLevel; + const verifiedFactors = (_b = (_a = session.user.factors) === null || _a === void 0 ? void 0 : _a.filter((factor) => factor.status === 'verified')) !== null && _b !== void 0 ? _b : []; + if (verifiedFactors.length > 0) { + nextLevel = 'aal2'; + } + const currentAuthenticationMethods = payload.amr || []; + return { data: { currentLevel, nextLevel, currentAuthenticationMethods }, error: null }; + } + /** + * Retrieves details about an OAuth authorization request. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * Returns authorization details including client info, scopes, and user information. + * If the API returns a redirect_uri, it means consent was already given - the caller + * should handle the redirect manually if needed. + */ + async _getAuthorizationDetails(authorizationId) { + try { + return await this._useSession(async (result) => { + const { data: { session }, error: sessionError, } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + if (!session) { + return this._returnResult({ data: null, error: new AuthSessionMissingError() }); + } + return await _request(this.fetch, 'GET', `${this.url}/oauth/authorizations/${authorizationId}`, { + headers: this.headers, + jwt: session.access_token, + xform: (data) => ({ data, error: null }), + }); + }); + } + catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + /** + * Approves an OAuth authorization request. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ + async _approveAuthorization(authorizationId, options) { + try { + return await this._useSession(async (result) => { + const { data: { session }, error: sessionError, } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + if (!session) { + return this._returnResult({ data: null, error: new AuthSessionMissingError() }); + } + const response = await _request(this.fetch, 'POST', `${this.url}/oauth/authorizations/${authorizationId}/consent`, { + headers: this.headers, + jwt: session.access_token, + body: { action: 'approve' }, + xform: (data) => ({ data, error: null }), + }); + if (response.data && response.data.redirect_url) { + // Automatically redirect in browser unless skipBrowserRedirect is true + if (isBrowser() && !(options === null || options === void 0 ? void 0 : options.skipBrowserRedirect)) { + window.location.assign(response.data.redirect_url); + } + } + return response; + }); + } + catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + /** + * Denies an OAuth authorization request. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ + async _denyAuthorization(authorizationId, options) { + try { + return await this._useSession(async (result) => { + const { data: { session }, error: sessionError, } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + if (!session) { + return this._returnResult({ data: null, error: new AuthSessionMissingError() }); + } + const response = await _request(this.fetch, 'POST', `${this.url}/oauth/authorizations/${authorizationId}/consent`, { + headers: this.headers, + jwt: session.access_token, + body: { action: 'deny' }, + xform: (data) => ({ data, error: null }), + }); + if (response.data && response.data.redirect_url) { + // Automatically redirect in browser unless skipBrowserRedirect is true + if (isBrowser() && !(options === null || options === void 0 ? void 0 : options.skipBrowserRedirect)) { + window.location.assign(response.data.redirect_url); + } + } + return response; + }); + } + catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + /** + * Lists all OAuth grants that the authenticated user has authorized. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ + async _listOAuthGrants() { + try { + return await this._useSession(async (result) => { + const { data: { session }, error: sessionError, } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + if (!session) { + return this._returnResult({ data: null, error: new AuthSessionMissingError() }); + } + return await _request(this.fetch, 'GET', `${this.url}/user/oauth/grants`, { + headers: this.headers, + jwt: session.access_token, + xform: (data) => ({ data, error: null }), + }); + }); + } + catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + /** + * Revokes a user's OAuth grant for a specific client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ + async _revokeOAuthGrant(options) { + try { + return await this._useSession(async (result) => { + const { data: { session }, error: sessionError, } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + if (!session) { + return this._returnResult({ data: null, error: new AuthSessionMissingError() }); + } + await _request(this.fetch, 'DELETE', `${this.url}/user/oauth/grants`, { + headers: this.headers, + jwt: session.access_token, + query: { client_id: options.clientId }, + noResolveJson: true, + }); + return { data: {}, error: null }; + }); + } + catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + async fetchJwk(kid, jwks = { keys: [] }) { + // try fetching from the supplied jwks + let jwk = jwks.keys.find((key) => key.kid === kid); + if (jwk) { + return jwk; + } + const now = Date.now(); + // try fetching from cache + jwk = this.jwks.keys.find((key) => key.kid === kid); + // jwk exists and jwks isn't stale + if (jwk && this.jwks_cached_at + JWKS_TTL > now) { + return jwk; + } + // jwk isn't cached in memory so we need to fetch it from the well-known endpoint + const { data, error } = await _request(this.fetch, 'GET', `${this.url}/.well-known/jwks.json`, { + headers: this.headers, + }); + if (error) { + throw error; + } + if (!data.keys || data.keys.length === 0) { + return null; + } + this.jwks = data; + this.jwks_cached_at = now; + // Find the signing key + jwk = data.keys.find((key) => key.kid === kid); + if (!jwk) { + return null; + } + return jwk; + } + /** + * Extracts the JWT claims present in the access token by first verifying the + * JWT against the server's JSON Web Key Set endpoint + * `/.well-known/jwks.json` which is often cached, resulting in significantly + * faster responses. Prefer this method over {@link #getUser} which always + * sends a request to the Auth server for each JWT. + * + * If the project is not using an asymmetric JWT signing key (like ECC or + * RSA) it always sends a request to the Auth server (similar to {@link + * #getUser}) to verify the JWT. + * + * @param jwt An optional specific JWT you wish to verify, not the one you + * can obtain from {@link #getSession}. + * @param options Various additional options that allow you to customize the + * behavior of this method. + */ + async getClaims(jwt, options = {}) { + try { + let token = jwt; + if (!token) { + const { data, error } = await this.getSession(); + if (error || !data.session) { + return this._returnResult({ data: null, error }); + } + token = data.session.access_token; + } + const { header, payload, signature, raw: { header: rawHeader, payload: rawPayload }, } = decodeJWT(token); + if (!(options === null || options === void 0 ? void 0 : options.allowExpired)) { + // Reject expired JWTs should only happen if jwt argument was passed + validateExp(payload.exp); + } + const signingKey = !header.alg || + header.alg.startsWith('HS') || + !header.kid || + !('crypto' in globalThis && 'subtle' in globalThis.crypto) + ? null + : await this.fetchJwk(header.kid, (options === null || options === void 0 ? void 0 : options.keys) ? { keys: options.keys } : options === null || options === void 0 ? void 0 : options.jwks); + // If symmetric algorithm or WebCrypto API is unavailable, fallback to getUser() + if (!signingKey) { + const { error } = await this.getUser(token); + if (error) { + throw error; + } + // getUser succeeds so the claims in the JWT can be trusted + return { + data: { + claims: payload, + header, + signature, + }, + error: null, + }; + } + const algorithm = getAlgorithm(header.alg); + // Convert JWK to CryptoKey + const publicKey = await crypto.subtle.importKey('jwk', signingKey, algorithm, true, [ + 'verify', + ]); + // Verify the signature + const isValid = await crypto.subtle.verify(algorithm, publicKey, signature, stringToUint8Array(`${rawHeader}.${rawPayload}`)); + if (!isValid) { + throw new AuthInvalidJwtError('Invalid JWT signature'); + } + // If verification succeeds, decode and return claims + return { + data: { + claims: payload, + header, + signature, + }, + error: null, + }; + } + catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } +} +GoTrueClient.nextInstanceID = {}; +export default GoTrueClient; +//# sourceMappingURL=GoTrueClient.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/GoTrueClient.js.map b/backend/node_modules/@supabase/auth-js/dist/module/GoTrueClient.js.map new file mode 100644 index 0000000..1e88d94 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/GoTrueClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GoTrueClient.js","sourceRoot":"","sources":["../../src/GoTrueClient.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,kBAAkB,CAAA;AAC7C,OAAO,EACL,6BAA6B,EAC7B,2BAA2B,EAC3B,eAAe,EACf,gBAAgB,EAChB,UAAU,EACV,QAAQ,EACR,WAAW,GACZ,MAAM,iBAAiB,CAAA;AACxB,OAAO,EAEL,8BAA8B,EAC9B,2BAA2B,EAC3B,mBAAmB,EACnB,6BAA6B,EAC7B,8BAA8B,EAC9B,uBAAuB,EACvB,gBAAgB,EAChB,cAAc,EACd,WAAW,EACX,gCAAgC,EAChC,yBAAyB,EACzB,yBAAyB,GAC1B,MAAM,cAAc,CAAA;AACrB,OAAO,EAEL,QAAQ,EACR,gBAAgB,EAChB,wBAAwB,EACxB,YAAY,EACZ,aAAa,GACd,MAAM,aAAa,CAAA;AACpB,OAAO,EACL,SAAS,EACT,SAAS,EACT,QAAQ,EACR,kBAAkB,EAClB,YAAY,EACZ,yBAAyB,EACzB,YAAY,EACZ,wBAAwB,EACxB,SAAS,EACT,sBAAsB,EACtB,eAAe,EACf,YAAY,EACZ,SAAS,EACT,YAAY,EAC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K,EAAE,IAAI;aACZ,CAAA;QACH,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,WAAW,CAAC,KAAK,CAAC,EAAE,CAAC;gBACvB,OAAO,IAAI,CAAC,aAAa,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAA;YAClD,CAAC;YACD,MAAM,KAAK,CAAA;QACb,CAAC;IACH,CAAC;;AAziHc,2BAAc,GAA2B,EAAE,AAA7B,CAA6B;eADvC,YAAY"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/index.d.ts b/backend/node_modules/@supabase/auth-js/dist/module/index.d.ts new file mode 100644 index 0000000..62b23d0 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/index.d.ts @@ -0,0 +1,9 @@ +import GoTrueAdminApi from './GoTrueAdminApi'; +import GoTrueClient from './GoTrueClient'; +import AuthAdminApi from './AuthAdminApi'; +import AuthClient from './AuthClient'; +export { GoTrueAdminApi, GoTrueClient, AuthAdminApi, AuthClient }; +export * from './lib/types'; +export * from './lib/errors'; +export { navigatorLock, NavigatorLockAcquireTimeoutError, internals as lockInternals, processLock, } from './lib/locks'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/index.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/module/index.d.ts.map new file mode 100644 index 0000000..884248d --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,kBAAkB,CAAA;AAC7C,OAAO,YAAY,MAAM,gBAAgB,CAAA;AACzC,OAAO,YAAY,MAAM,gBAAgB,CAAA;AACzC,OAAO,UAAU,MAAM,cAAc,CAAA;AACrC,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,YAAY,EAAE,UAAU,EAAE,CAAA;AACjE,cAAc,aAAa,CAAA;AAC3B,cAAc,cAAc,CAAA;AAC5B,OAAO,EACL,aAAa,EACb,gCAAgC,EAChC,SAAS,IAAI,aAAa,EAC1B,WAAW,GACZ,MAAM,aAAa,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/index.js b/backend/node_modules/@supabase/auth-js/dist/module/index.js new file mode 100644 index 0000000..01b965d --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/index.js @@ -0,0 +1,9 @@ +import GoTrueAdminApi from './GoTrueAdminApi'; +import GoTrueClient from './GoTrueClient'; +import AuthAdminApi from './AuthAdminApi'; +import AuthClient from './AuthClient'; +export { GoTrueAdminApi, GoTrueClient, AuthAdminApi, AuthClient }; +export * from './lib/types'; +export * from './lib/errors'; +export { navigatorLock, NavigatorLockAcquireTimeoutError, internals as lockInternals, processLock, } from './lib/locks'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/index.js.map b/backend/node_modules/@supabase/auth-js/dist/module/index.js.map new file mode 100644 index 0000000..a43605f --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,kBAAkB,CAAA;AAC7C,OAAO,YAAY,MAAM,gBAAgB,CAAA;AACzC,OAAO,YAAY,MAAM,gBAAgB,CAAA;AACzC,OAAO,UAAU,MAAM,cAAc,CAAA;AACrC,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,YAAY,EAAE,UAAU,EAAE,CAAA;AACjE,cAAc,aAAa,CAAA;AAC3B,cAAc,cAAc,CAAA;AAC5B,OAAO,EACL,aAAa,EACb,gCAAgC,EAChC,SAAS,IAAI,aAAa,EAC1B,WAAW,GACZ,MAAM,aAAa,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/base64url.d.ts b/backend/node_modules/@supabase/auth-js/dist/module/lib/base64url.d.ts new file mode 100644 index 0000000..62276a3 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/base64url.d.ts @@ -0,0 +1,76 @@ +/** + * Avoid modifying this file. It's part of + * https://github.com/supabase-community/base64url-js. Submit all fixes on + * that repo! + */ +import { Uint8Array_ } from './webauthn.dom'; +/** + * Converts a byte to a Base64-URL string. + * + * @param byte The byte to convert, or null to flush at the end of the byte sequence. + * @param state The Base64 conversion state. Pass an initial value of `{ queue: 0, queuedBits: 0 }`. + * @param emit A function called with the next Base64 character when ready. + */ +export declare function byteToBase64URL(byte: number | null, state: { + queue: number; + queuedBits: number; +}, emit: (char: string) => void): void; +/** + * Converts a String char code (extracted using `string.charCodeAt(position)`) to a sequence of Base64-URL characters. + * + * @param charCode The char code of the JavaScript string. + * @param state The Base64 state. Pass an initial value of `{ queue: 0, queuedBits: 0 }`. + * @param emit A function called with the next byte. + */ +export declare function byteFromBase64URL(charCode: number, state: { + queue: number; + queuedBits: number; +}, emit: (byte: number) => void): void; +/** + * Converts a JavaScript string (which may include any valid character) into a + * Base64-URL encoded string. The string is first encoded in UTF-8 which is + * then encoded as Base64-URL. + * + * @param str The string to convert. + */ +export declare function stringToBase64URL(str: string): string; +/** + * Converts a Base64-URL encoded string into a JavaScript string. It is assumed + * that the underlying string has been encoded as UTF-8. + * + * @param str The Base64-URL encoded string. + */ +export declare function stringFromBase64URL(str: string): string; +/** + * Converts a Unicode codepoint to a multi-byte UTF-8 sequence. + * + * @param codepoint The Unicode codepoint. + * @param emit Function which will be called for each UTF-8 byte that represents the codepoint. + */ +export declare function codepointToUTF8(codepoint: number, emit: (byte: number) => void): void; +/** + * Converts a JavaScript string to a sequence of UTF-8 bytes. + * + * @param str The string to convert to UTF-8. + * @param emit Function which will be called for each UTF-8 byte of the string. + */ +export declare function stringToUTF8(str: string, emit: (byte: number) => void): void; +/** + * Converts a UTF-8 byte to a Unicode codepoint. + * + * @param byte The UTF-8 byte next in the sequence. + * @param state The shared state between consecutive UTF-8 bytes in the + * sequence, an object with the shape `{ utf8seq: 0, codepoint: 0 }`. + * @param emit Function which will be called for each codepoint. + */ +export declare function stringFromUTF8(byte: number, state: { + utf8seq: number; + codepoint: number; +}, emit: (codepoint: number) => void): void; +/** + * Helper functions to convert different types of strings to Uint8Array + */ +export declare function base64UrlToUint8Array(str: string): Uint8Array_; +export declare function stringToUint8Array(str: string): Uint8Array_; +export declare function bytesToBase64URL(bytes: Uint8Array): string; +//# sourceMappingURL=base64url.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/base64url.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/module/lib/base64url.d.ts.map new file mode 100644 index 0000000..5a7591c --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/base64url.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"base64url.d.ts","sourceRoot":"","sources":["../../../src/lib/base64url.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA;AAoC5C;;;;;;GAMG;AACH,wBAAgB,eAAe,CAC7B,IAAI,EAAE,MAAM,GAAG,IAAI,EACnB,KAAK,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,EAC5C,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,QAqB7B;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAC/B,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,EAC5C,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,QAmB7B;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,MAAM,UAgB5C;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,MAAM,UAuB9C;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,QAsB9E;AAED;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,QAgBrE;AAED;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAC5B,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,EAC7C,IAAI,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,IAAI,QAuClC;AAED;;GAEG;AAEH,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,MAAM,GAAG,WAAW,CAa9D;AAED,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,GAAG,WAAW,CAI3D;AAED,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,UAAU,UAcjD"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/base64url.js b/backend/node_modules/@supabase/auth-js/dist/module/lib/base64url.js new file mode 100644 index 0000000..90e966f --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/base64url.js @@ -0,0 +1,257 @@ +/** + * Avoid modifying this file. It's part of + * https://github.com/supabase-community/base64url-js. Submit all fixes on + * that repo! + */ +/** + * An array of characters that encode 6 bits into a Base64-URL alphabet + * character. + */ +const TO_BASE64URL = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'.split(''); +/** + * An array of characters that can appear in a Base64-URL encoded string but + * should be ignored. + */ +const IGNORE_BASE64URL = ' \t\n\r='.split(''); +/** + * An array of 128 numbers that map a Base64-URL character to 6 bits, or if -2 + * used to skip the character, or if -1 used to error out. + */ +const FROM_BASE64URL = (() => { + const charMap = new Array(128); + for (let i = 0; i < charMap.length; i += 1) { + charMap[i] = -1; + } + for (let i = 0; i < IGNORE_BASE64URL.length; i += 1) { + charMap[IGNORE_BASE64URL[i].charCodeAt(0)] = -2; + } + for (let i = 0; i < TO_BASE64URL.length; i += 1) { + charMap[TO_BASE64URL[i].charCodeAt(0)] = i; + } + return charMap; +})(); +/** + * Converts a byte to a Base64-URL string. + * + * @param byte The byte to convert, or null to flush at the end of the byte sequence. + * @param state The Base64 conversion state. Pass an initial value of `{ queue: 0, queuedBits: 0 }`. + * @param emit A function called with the next Base64 character when ready. + */ +export function byteToBase64URL(byte, state, emit) { + if (byte !== null) { + state.queue = (state.queue << 8) | byte; + state.queuedBits += 8; + while (state.queuedBits >= 6) { + const pos = (state.queue >> (state.queuedBits - 6)) & 63; + emit(TO_BASE64URL[pos]); + state.queuedBits -= 6; + } + } + else if (state.queuedBits > 0) { + state.queue = state.queue << (6 - state.queuedBits); + state.queuedBits = 6; + while (state.queuedBits >= 6) { + const pos = (state.queue >> (state.queuedBits - 6)) & 63; + emit(TO_BASE64URL[pos]); + state.queuedBits -= 6; + } + } +} +/** + * Converts a String char code (extracted using `string.charCodeAt(position)`) to a sequence of Base64-URL characters. + * + * @param charCode The char code of the JavaScript string. + * @param state The Base64 state. Pass an initial value of `{ queue: 0, queuedBits: 0 }`. + * @param emit A function called with the next byte. + */ +export function byteFromBase64URL(charCode, state, emit) { + const bits = FROM_BASE64URL[charCode]; + if (bits > -1) { + // valid Base64-URL character + state.queue = (state.queue << 6) | bits; + state.queuedBits += 6; + while (state.queuedBits >= 8) { + emit((state.queue >> (state.queuedBits - 8)) & 0xff); + state.queuedBits -= 8; + } + } + else if (bits === -2) { + // ignore spaces, tabs, newlines, = + return; + } + else { + throw new Error(`Invalid Base64-URL character "${String.fromCharCode(charCode)}"`); + } +} +/** + * Converts a JavaScript string (which may include any valid character) into a + * Base64-URL encoded string. The string is first encoded in UTF-8 which is + * then encoded as Base64-URL. + * + * @param str The string to convert. + */ +export function stringToBase64URL(str) { + const base64 = []; + const emitter = (char) => { + base64.push(char); + }; + const state = { queue: 0, queuedBits: 0 }; + stringToUTF8(str, (byte) => { + byteToBase64URL(byte, state, emitter); + }); + byteToBase64URL(null, state, emitter); + return base64.join(''); +} +/** + * Converts a Base64-URL encoded string into a JavaScript string. It is assumed + * that the underlying string has been encoded as UTF-8. + * + * @param str The Base64-URL encoded string. + */ +export function stringFromBase64URL(str) { + const conv = []; + const utf8Emit = (codepoint) => { + conv.push(String.fromCodePoint(codepoint)); + }; + const utf8State = { + utf8seq: 0, + codepoint: 0, + }; + const b64State = { queue: 0, queuedBits: 0 }; + const byteEmit = (byte) => { + stringFromUTF8(byte, utf8State, utf8Emit); + }; + for (let i = 0; i < str.length; i += 1) { + byteFromBase64URL(str.charCodeAt(i), b64State, byteEmit); + } + return conv.join(''); +} +/** + * Converts a Unicode codepoint to a multi-byte UTF-8 sequence. + * + * @param codepoint The Unicode codepoint. + * @param emit Function which will be called for each UTF-8 byte that represents the codepoint. + */ +export function codepointToUTF8(codepoint, emit) { + if (codepoint <= 0x7f) { + emit(codepoint); + return; + } + else if (codepoint <= 0x7ff) { + emit(0xc0 | (codepoint >> 6)); + emit(0x80 | (codepoint & 0x3f)); + return; + } + else if (codepoint <= 0xffff) { + emit(0xe0 | (codepoint >> 12)); + emit(0x80 | ((codepoint >> 6) & 0x3f)); + emit(0x80 | (codepoint & 0x3f)); + return; + } + else if (codepoint <= 0x10ffff) { + emit(0xf0 | (codepoint >> 18)); + emit(0x80 | ((codepoint >> 12) & 0x3f)); + emit(0x80 | ((codepoint >> 6) & 0x3f)); + emit(0x80 | (codepoint & 0x3f)); + return; + } + throw new Error(`Unrecognized Unicode codepoint: ${codepoint.toString(16)}`); +} +/** + * Converts a JavaScript string to a sequence of UTF-8 bytes. + * + * @param str The string to convert to UTF-8. + * @param emit Function which will be called for each UTF-8 byte of the string. + */ +export function stringToUTF8(str, emit) { + for (let i = 0; i < str.length; i += 1) { + let codepoint = str.charCodeAt(i); + if (codepoint > 0xd7ff && codepoint <= 0xdbff) { + // most UTF-16 codepoints are Unicode codepoints, except values in this + // range where the next UTF-16 codepoint needs to be combined with the + // current one to get the Unicode codepoint + const highSurrogate = ((codepoint - 0xd800) * 0x400) & 0xffff; + const lowSurrogate = (str.charCodeAt(i + 1) - 0xdc00) & 0xffff; + codepoint = (lowSurrogate | highSurrogate) + 0x10000; + i += 1; + } + codepointToUTF8(codepoint, emit); + } +} +/** + * Converts a UTF-8 byte to a Unicode codepoint. + * + * @param byte The UTF-8 byte next in the sequence. + * @param state The shared state between consecutive UTF-8 bytes in the + * sequence, an object with the shape `{ utf8seq: 0, codepoint: 0 }`. + * @param emit Function which will be called for each codepoint. + */ +export function stringFromUTF8(byte, state, emit) { + if (state.utf8seq === 0) { + if (byte <= 0x7f) { + emit(byte); + return; + } + // count the number of 1 leading bits until you reach 0 + for (let leadingBit = 1; leadingBit < 6; leadingBit += 1) { + if (((byte >> (7 - leadingBit)) & 1) === 0) { + state.utf8seq = leadingBit; + break; + } + } + if (state.utf8seq === 2) { + state.codepoint = byte & 31; + } + else if (state.utf8seq === 3) { + state.codepoint = byte & 15; + } + else if (state.utf8seq === 4) { + state.codepoint = byte & 7; + } + else { + throw new Error('Invalid UTF-8 sequence'); + } + state.utf8seq -= 1; + } + else if (state.utf8seq > 0) { + if (byte <= 0x7f) { + throw new Error('Invalid UTF-8 sequence'); + } + state.codepoint = (state.codepoint << 6) | (byte & 63); + state.utf8seq -= 1; + if (state.utf8seq === 0) { + emit(state.codepoint); + } + } +} +/** + * Helper functions to convert different types of strings to Uint8Array + */ +export function base64UrlToUint8Array(str) { + const result = []; + const state = { queue: 0, queuedBits: 0 }; + const onByte = (byte) => { + result.push(byte); + }; + for (let i = 0; i < str.length; i += 1) { + byteFromBase64URL(str.charCodeAt(i), state, onByte); + } + return new Uint8Array(result); +} +export function stringToUint8Array(str) { + const result = []; + stringToUTF8(str, (byte) => result.push(byte)); + return new Uint8Array(result); +} +export function bytesToBase64URL(bytes) { + const result = []; + const state = { queue: 0, queuedBits: 0 }; + const onChar = (char) => { + result.push(char); + }; + bytes.forEach((byte) => byteToBase64URL(byte, state, onChar)); + // always call with `null` after processing all bytes + byteToBase64URL(null, state, onChar); + return result.join(''); +} +//# sourceMappingURL=base64url.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/base64url.js.map b/backend/node_modules/@supabase/auth-js/dist/module/lib/base64url.js.map new file mode 100644 index 0000000..e9cc74e --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/base64url.js.map @@ -0,0 +1 @@ +{"version":3,"file":"base64url.js","sourceRoot":"","sources":["../../../src/lib/base64url.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH;;;GAGG;AACH,MAAM,YAAY,GAAG,kEAAkE,CAAC,KAAK,CAAC,EAAE,CAAC,CAAA;AAEjG;;;GAGG;AACH,MAAM,gBAAgB,GAAG,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC,CAAA;AAE7C;;;GAGG;AACH,MAAM,cAAc,GAAG,CAAC,GAAG,EAAE;IAC3B,MAAM,OAAO,GAAa,IAAI,KAAK,CAAC,GAAG,CAAC,CAAA;IAExC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC;QAC3C,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAA;IACjB,CAAC;IAED,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,gBAAgB,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC;QACpD,OAAO,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAA;IACjD,CAAC;IAED,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAA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,CAAC,MAAM,CAAC,CAAA;AAC/B,CAAC;AAED,MAAM,UAAU,kBAAkB,CAAC,GAAW;IAC5C,MAAM,MAAM,GAAa,EAAE,CAAA;IAC3B,YAAY,CAAC,GAAG,EAAE,CAAC,IAAY,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAA;IACtD,OAAO,IAAI,UAAU,CAAC,MAAM,CAAC,CAAA;AAC/B,CAAC;AAED,MAAM,UAAU,gBAAgB,CAAC,KAAiB;IAChD,MAAM,MAAM,GAAa,EAAE,CAAA;IAC3B,MAAM,KAAK,GAAG,EAAE,KAAK,EAAE,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,CAAA;IAEzC,MAAM,MAAM,GAAG,CAAC,IAAY,EAAE,EAAE;QAC9B,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;IACnB,CAAC,CAAA;IAED,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,eAAe,CAAC,IAAI,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC,CAAA;IAE7D,qDAAqD;IACrD,eAAe,CAAC,IAAI,EAAE,KAAK,EAAE,MAAM,CAAC,CAAA;IAEpC,OAAO,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;AACxB,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/constants.d.ts b/backend/node_modules/@supabase/auth-js/dist/module/lib/constants.d.ts new file mode 100644 index 0000000..604f8d0 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/constants.d.ts @@ -0,0 +1,26 @@ +/** Current session will be checked for refresh at this interval. */ +export declare const AUTO_REFRESH_TICK_DURATION_MS: number; +/** + * A token refresh will be attempted this many ticks before the current session expires. */ +export declare const AUTO_REFRESH_TICK_THRESHOLD = 3; +export declare const EXPIRY_MARGIN_MS: number; +export declare const GOTRUE_URL = "http://localhost:9999"; +export declare const STORAGE_KEY = "supabase.auth.token"; +export declare const AUDIENCE = ""; +export declare const DEFAULT_HEADERS: { + 'X-Client-Info': string; +}; +export declare const NETWORK_FAILURE: { + MAX_RETRIES: number; + RETRY_INTERVAL: number; +}; +export declare const API_VERSION_HEADER_NAME = "X-Supabase-Api-Version"; +export declare const API_VERSIONS: { + '2024-01-01': { + timestamp: number; + name: string; + }; +}; +export declare const BASE64URL_REGEX: RegExp; +export declare const JWKS_TTL: number; +//# sourceMappingURL=constants.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/constants.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/module/lib/constants.d.ts.map new file mode 100644 index 0000000..acb62eb --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/constants.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":"AAEA,oEAAoE;AACpE,eAAO,MAAM,6BAA6B,QAAY,CAAA;AAEtD;2FAC2F;AAC3F,eAAO,MAAM,2BAA2B,IAAI,CAAA;AAK5C,eAAO,MAAM,gBAAgB,QAA8D,CAAA;AAE3F,eAAO,MAAM,UAAU,0BAA0B,CAAA;AACjD,eAAO,MAAM,WAAW,wBAAwB,CAAA;AAChD,eAAO,MAAM,QAAQ,KAAK,CAAA;AAC1B,eAAO,MAAM,eAAe;;CAA8C,CAAA;AAC1E,eAAO,MAAM,eAAe;;;CAG3B,CAAA;AAED,eAAO,MAAM,uBAAuB,2BAA2B,CAAA;AAC/D,eAAO,MAAM,YAAY;;;;;CAKxB,CAAA;AAED,eAAO,MAAM,eAAe,QAAyD,CAAA;AAErF,eAAO,MAAM,QAAQ,QAAiB,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/constants.js b/backend/node_modules/@supabase/auth-js/dist/module/lib/constants.js new file mode 100644 index 0000000..17f19e7 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/constants.js @@ -0,0 +1,28 @@ +import { version } from './version'; +/** Current session will be checked for refresh at this interval. */ +export const AUTO_REFRESH_TICK_DURATION_MS = 30 * 1000; +/** + * A token refresh will be attempted this many ticks before the current session expires. */ +export const AUTO_REFRESH_TICK_THRESHOLD = 3; +/* + * Earliest time before an access token expires that the session should be refreshed. + */ +export const EXPIRY_MARGIN_MS = AUTO_REFRESH_TICK_THRESHOLD * AUTO_REFRESH_TICK_DURATION_MS; +export const GOTRUE_URL = 'http://localhost:9999'; +export const STORAGE_KEY = 'supabase.auth.token'; +export const AUDIENCE = ''; +export const DEFAULT_HEADERS = { 'X-Client-Info': `gotrue-js/${version}` }; +export const NETWORK_FAILURE = { + MAX_RETRIES: 10, + RETRY_INTERVAL: 2, // in deciseconds +}; +export const API_VERSION_HEADER_NAME = 'X-Supabase-Api-Version'; +export const API_VERSIONS = { + '2024-01-01': { + timestamp: Date.parse('2024-01-01T00:00:00.0Z'), + name: '2024-01-01', + }, +}; +export const BASE64URL_REGEX = /^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i; +export const JWKS_TTL = 10 * 60 * 1000; // 10 minutes +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/constants.js.map b/backend/node_modules/@supabase/auth-js/dist/module/lib/constants.js.map new file mode 100644 index 0000000..12b9fa8 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AAEnC,oEAAoE;AACpE,MAAM,CAAC,MAAM,6BAA6B,GAAG,EAAE,GAAG,IAAI,CAAA;AAEtD;2FAC2F;AAC3F,MAAM,CAAC,MAAM,2BAA2B,GAAG,CAAC,CAAA;AAE5C;;GAEG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,2BAA2B,GAAG,6BAA6B,CAAA;AAE3F,MAAM,CAAC,MAAM,UAAU,GAAG,uBAAuB,CAAA;AACjD,MAAM,CAAC,MAAM,WAAW,GAAG,qBAAqB,CAAA;AAChD,MAAM,CAAC,MAAM,QAAQ,GAAG,EAAE,CAAA;AAC1B,MAAM,CAAC,MAAM,eAAe,GAAG,EAAE,eAAe,EAAE,aAAa,OAAO,EAAE,EAAE,CAAA;AAC1E,MAAM,CAAC,MAAM,eAAe,GAAG;IAC7B,WAAW,EAAE,EAAE;IACf,cAAc,EAAE,CAAC,EAAE,iBAAiB;CACrC,CAAA;AAED,MAAM,CAAC,MAAM,uBAAuB,GAAG,wBAAwB,CAAA;AAC/D,MAAM,CAAC,MAAM,YAAY,GAAG;IAC1B,YAAY,EAAE;QACZ,SAAS,EAAE,IAAI,CAAC,KAAK,CAAC,wBAAwB,CAAC;QAC/C,IAAI,EAAE,YAAY;KACnB;CACF,CAAA;AAED,MAAM,CAAC,MAAM,eAAe,GAAG,sDAAsD,CAAA;AAErF,MAAM,CAAC,MAAM,QAAQ,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAA,CAAC,aAAa"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/error-codes.d.ts b/backend/node_modules/@supabase/auth-js/dist/module/lib/error-codes.d.ts new file mode 100644 index 0000000..668ad5b --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/error-codes.d.ts @@ -0,0 +1,7 @@ +/** + * Known error codes. Note that the server may also return other error codes + * not included in this list (if the SDK is older than the version + * on the server). + */ +export type ErrorCode = 'unexpected_failure' | 'validation_failed' | 'bad_json' | 'email_exists' | 'phone_exists' | 'bad_jwt' | 'not_admin' | 'no_authorization' | 'user_not_found' | 'session_not_found' | 'session_expired' | 'refresh_token_not_found' | 'refresh_token_already_used' | 'flow_state_not_found' | 'flow_state_expired' | 'signup_disabled' | 'user_banned' | 'provider_email_needs_verification' | 'invite_not_found' | 'bad_oauth_state' | 'bad_oauth_callback' | 'oauth_provider_not_supported' | 'unexpected_audience' | 'single_identity_not_deletable' | 'email_conflict_identity_not_deletable' | 'identity_already_exists' | 'email_provider_disabled' | 'phone_provider_disabled' | 'too_many_enrolled_mfa_factors' | 'mfa_factor_name_conflict' | 'mfa_factor_not_found' | 'mfa_ip_address_mismatch' | 'mfa_challenge_expired' | 'mfa_verification_failed' | 'mfa_verification_rejected' | 'insufficient_aal' | 'captcha_failed' | 'saml_provider_disabled' | 'manual_linking_disabled' | 'sms_send_failed' | 'email_not_confirmed' | 'phone_not_confirmed' | 'reauth_nonce_missing' | 'saml_relay_state_not_found' | 'saml_relay_state_expired' | 'saml_idp_not_found' | 'saml_assertion_no_user_id' | 'saml_assertion_no_email' | 'user_already_exists' | 'sso_provider_not_found' | 'saml_metadata_fetch_failed' | 'saml_idp_already_exists' | 'sso_domain_already_exists' | 'saml_entity_id_mismatch' | 'conflict' | 'provider_disabled' | 'user_sso_managed' | 'reauthentication_needed' | 'same_password' | 'reauthentication_not_valid' | 'otp_expired' | 'otp_disabled' | 'identity_not_found' | 'weak_password' | 'over_request_rate_limit' | 'over_email_send_rate_limit' | 'over_sms_send_rate_limit' | 'bad_code_verifier' | 'anonymous_provider_disabled' | 'hook_timeout' | 'hook_timeout_after_retry' | 'hook_payload_over_size_limit' | 'hook_payload_invalid_content_type' | 'request_timeout' | 'mfa_phone_enroll_not_enabled' | 'mfa_phone_verify_not_enabled' | 'mfa_totp_enroll_not_enabled' | 'mfa_totp_verify_not_enabled' | 'mfa_webauthn_enroll_not_enabled' | 'mfa_webauthn_verify_not_enabled' | 'mfa_verified_factor_exists' | 'invalid_credentials' | 'email_address_not_authorized' | 'email_address_invalid'; +//# sourceMappingURL=error-codes.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/error-codes.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/module/lib/error-codes.d.ts.map new file mode 100644 index 0000000..cc88970 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/error-codes.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"error-codes.d.ts","sourceRoot":"","sources":["../../../src/lib/error-codes.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,MAAM,SAAS,GACjB,oBAAoB,GACpB,mBAAmB,GACnB,UAAU,GACV,cAAc,GACd,cAAc,GACd,SAAS,GACT,WAAW,GACX,kBAAkB,GAClB,gBAAgB,GAChB,mBAAmB,GACnB,iBAAiB,GACjB,yBAAyB,GACzB,4BAA4B,GAC5B,sBAAsB,GACtB,oBAAoB,GACpB,iBAAiB,GACjB,aAAa,GACb,mCAAmC,GACnC,kBAAkB,GAClB,iBAAiB,GACjB,oBAAoB,GACpB,8BAA8B,GAC9B,qBAAqB,GACrB,+BAA+B,GAC/B,uCAAuC,GACvC,yBAAyB,GACzB,yBAAyB,GACzB,yBAAyB,GACzB,+BAA+B,GAC/B,0BAA0B,GAC1B,sBAAsB,GACtB,yBAAyB,GACzB,uBAAuB,GACvB,yBAAyB,GACzB,2BAA2B,GAC3B,kBAAkB,GAClB,gBAAgB,GAChB,wBAAwB,GACxB,yBAAyB,GACzB,iBAAiB,GACjB,qBAAqB,GACrB,qBAAqB,GACrB,sBAAsB,GACtB,4BAA4B,GAC5B,0BAA0B,GAC1B,oBAAoB,GACpB,2BAA2B,GAC3B,yBAAyB,GACzB,qBAAqB,GACrB,wBAAwB,GACxB,4BAA4B,GAC5B,yBAAyB,GACzB,2BAA2B,GAC3B,yBAAyB,GACzB,UAAU,GACV,mBAAmB,GACnB,kBAAkB,GAClB,yBAAyB,GACzB,eAAe,GACf,4BAA4B,GAC5B,aAAa,GACb,cAAc,GACd,oBAAoB,GACpB,eAAe,GACf,yBAAyB,GACzB,4BAA4B,GAC5B,0BAA0B,GAC1B,mBAAmB,GACnB,6BAA6B,GAC7B,cAAc,GACd,0BAA0B,GAC1B,8BAA8B,GAC9B,mCAAmC,GACnC,iBAAiB,GACjB,8BAA8B,GAC9B,8BAA8B,GAC9B,6BAA6B,GAC7B,6BAA6B,GAC7B,iCAAiC,GACjC,iCAAiC,GACjC,4BAA4B,GAC5B,qBAAqB,GACrB,8BAA8B,GAC9B,uBAAuB,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/error-codes.js b/backend/node_modules/@supabase/auth-js/dist/module/lib/error-codes.js new file mode 100644 index 0000000..035bf41 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/error-codes.js @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=error-codes.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/error-codes.js.map b/backend/node_modules/@supabase/auth-js/dist/module/lib/error-codes.js.map new file mode 100644 index 0000000..a68e8e3 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/error-codes.js.map @@ -0,0 +1 @@ +{"version":3,"file":"error-codes.js","sourceRoot":"","sources":["../../../src/lib/error-codes.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/errors.d.ts b/backend/node_modules/@supabase/auth-js/dist/module/lib/errors.d.ts new file mode 100644 index 0000000..bec859b --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/errors.d.ts @@ -0,0 +1,227 @@ +import { WeakPasswordReasons } from './types'; +import { ErrorCode } from './error-codes'; +/** + * Base error thrown by Supabase Auth helpers. + * + * @example + * ```ts + * import { AuthError } from '@supabase/auth-js' + * + * throw new AuthError('Unexpected auth error', 500, 'unexpected') + * ``` + */ +export declare class AuthError extends Error { + /** + * Error code associated with the error. Most errors coming from + * HTTP responses will have a code, though some errors that occur + * before a response is received will not have one present. In that + * case {@link #status} will also be undefined. + */ + code: ErrorCode | (string & {}) | undefined; + /** HTTP status code that caused the error. */ + status: number | undefined; + protected __isAuthError: boolean; + constructor(message: string, status?: number, code?: string); +} +export declare function isAuthError(error: unknown): error is AuthError; +/** + * Error returned directly from the GoTrue REST API. + * + * @example + * ```ts + * import { AuthApiError } from '@supabase/auth-js' + * + * throw new AuthApiError('Invalid credentials', 400, 'invalid_credentials') + * ``` + */ +export declare class AuthApiError extends AuthError { + status: number; + constructor(message: string, status: number, code: string | undefined); +} +export declare function isAuthApiError(error: unknown): error is AuthApiError; +/** + * Wraps non-standard errors so callers can inspect the root cause. + * + * @example + * ```ts + * import { AuthUnknownError } from '@supabase/auth-js' + * + * try { + * await someAuthCall() + * } catch (err) { + * throw new AuthUnknownError('Auth failed', err) + * } + * ``` + */ +export declare class AuthUnknownError extends AuthError { + originalError: unknown; + constructor(message: string, originalError: unknown); +} +/** + * Flexible error class used to create named auth errors at runtime. + * + * @example + * ```ts + * import { CustomAuthError } from '@supabase/auth-js' + * + * throw new CustomAuthError('My custom auth error', 'MyAuthError', 400, 'custom_code') + * ``` + */ +export declare class CustomAuthError extends AuthError { + name: string; + status: number; + constructor(message: string, name: string, status: number, code: string | undefined); +} +/** + * Error thrown when an operation requires a session but none is present. + * + * @example + * ```ts + * import { AuthSessionMissingError } from '@supabase/auth-js' + * + * throw new AuthSessionMissingError() + * ``` + */ +export declare class AuthSessionMissingError extends CustomAuthError { + constructor(); +} +export declare function isAuthSessionMissingError(error: any): error is AuthSessionMissingError; +/** + * Error thrown when the token response is malformed. + * + * @example + * ```ts + * import { AuthInvalidTokenResponseError } from '@supabase/auth-js' + * + * throw new AuthInvalidTokenResponseError() + * ``` + */ +export declare class AuthInvalidTokenResponseError extends CustomAuthError { + constructor(); +} +/** + * Error thrown when email/password credentials are invalid. + * + * @example + * ```ts + * import { AuthInvalidCredentialsError } from '@supabase/auth-js' + * + * throw new AuthInvalidCredentialsError('Email or password is incorrect') + * ``` + */ +export declare class AuthInvalidCredentialsError extends CustomAuthError { + constructor(message: string); +} +/** + * Error thrown when implicit grant redirects contain an error. + * + * @example + * ```ts + * import { AuthImplicitGrantRedirectError } from '@supabase/auth-js' + * + * throw new AuthImplicitGrantRedirectError('OAuth redirect failed', { + * error: 'access_denied', + * code: 'oauth_error', + * }) + * ``` + */ +export declare class AuthImplicitGrantRedirectError extends CustomAuthError { + details: { + error: string; + code: string; + } | null; + constructor(message: string, details?: { + error: string; + code: string; + } | null); + toJSON(): { + name: string; + message: string; + status: number; + details: { + error: string; + code: string; + } | null; + }; +} +export declare function isAuthImplicitGrantRedirectError(error: any): error is AuthImplicitGrantRedirectError; +/** + * Error thrown during PKCE code exchanges. + * + * @example + * ```ts + * import { AuthPKCEGrantCodeExchangeError } from '@supabase/auth-js' + * + * throw new AuthPKCEGrantCodeExchangeError('PKCE exchange failed') + * ``` + */ +export declare class AuthPKCEGrantCodeExchangeError extends CustomAuthError { + details: { + error: string; + code: string; + } | null; + constructor(message: string, details?: { + error: string; + code: string; + } | null); + toJSON(): { + name: string; + message: string; + status: number; + details: { + error: string; + code: string; + } | null; + }; +} +/** + * Error thrown when a transient fetch issue occurs. + * + * @example + * ```ts + * import { AuthRetryableFetchError } from '@supabase/auth-js' + * + * throw new AuthRetryableFetchError('Service temporarily unavailable', 503) + * ``` + */ +export declare class AuthRetryableFetchError extends CustomAuthError { + constructor(message: string, status: number); +} +export declare function isAuthRetryableFetchError(error: unknown): error is AuthRetryableFetchError; +/** + * This error is thrown on certain methods when the password used is deemed + * weak. Inspect the reasons to identify what password strength rules are + * inadequate. + */ +/** + * Error thrown when a supplied password is considered weak. + * + * @example + * ```ts + * import { AuthWeakPasswordError } from '@supabase/auth-js' + * + * throw new AuthWeakPasswordError('Password too short', 400, ['min_length']) + * ``` + */ +export declare class AuthWeakPasswordError extends CustomAuthError { + /** + * Reasons why the password is deemed weak. + */ + reasons: WeakPasswordReasons[]; + constructor(message: string, status: number, reasons: WeakPasswordReasons[]); +} +export declare function isAuthWeakPasswordError(error: unknown): error is AuthWeakPasswordError; +/** + * Error thrown when a JWT cannot be verified or parsed. + * + * @example + * ```ts + * import { AuthInvalidJwtError } from '@supabase/auth-js' + * + * throw new AuthInvalidJwtError('Token signature is invalid') + * ``` + */ +export declare class AuthInvalidJwtError extends CustomAuthError { + constructor(message: string); +} +//# sourceMappingURL=errors.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/errors.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/module/lib/errors.d.ts.map new file mode 100644 index 0000000..f6dd864 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/errors.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../../src/lib/errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAA;AAC7C,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAA;AAEzC;;;;;;;;;GASG;AACH,qBAAa,SAAU,SAAQ,KAAK;IAClC;;;;;OAKG;IACH,IAAI,EAAE,SAAS,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC,GAAG,SAAS,CAAA;IAE3C,8CAA8C;IAC9C,MAAM,EAAE,MAAM,GAAG,SAAS,CAAA;IAE1B,SAAS,CAAC,aAAa,UAAO;gBAElB,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM;CAM5D;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,SAAS,CAE9D;AAED;;;;;;;;;GASG;AACH,qBAAa,YAAa,SAAQ,SAAS;IACzC,MAAM,EAAE,MAAM,CAAA;gBAEF,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,SAAS;CAMtE;AAED,wBAAgB,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,YAAY,CAEpE;AAED;;;;;;;;;;;;;GAaG;AACH,qBAAa,gBAAiB,SAAQ,SAAS;IAC7C,aAAa,EAAE,OAAO,CAAA;gBAEV,OAA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,CAAA;KAAE,GAAG,IAAW;IAKnF,MAAM;;;;;mBAPY,MAAM;kBAAQ,MAAM;;;CAevC;AAED;;;;;;;;;GASG;AACH,qBAAa,uBAAwB,SAAQ,eAAe;gBAC9C,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;CAG5C;AAED,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,uBAAuB,CAE1F;AAED;;;;GAIG;AACH;;;;;;;;;GASG;AACH,qBAAa,qBAAsB,SAAQ,eAAe;IACxD;;OAEG;IACH,OAAO,EAAE,mBAAmB,EAAE,CAAA;gBAElB,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,mBAAmB,EAAE;CAK5E;AAED,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,qBAAqB,CAEtF;AAED;;;;;;;;;GASG;AACH,qBAAa,mBAAoB,SAAQ,eAAe;gBAC1C,OAAO,EAAE,MAAM;CAG5B"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/errors.js b/backend/node_modules/@supabase/auth-js/dist/module/lib/errors.js new file mode 100644 index 0000000..e984b36 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/errors.js @@ -0,0 +1,243 @@ +/** + * Base error thrown by Supabase Auth helpers. + * + * @example + * ```ts + * import { AuthError } from '@supabase/auth-js' + * + * throw new AuthError('Unexpected auth error', 500, 'unexpected') + * ``` + */ +export class AuthError extends Error { + constructor(message, status, code) { + super(message); + this.__isAuthError = true; + this.name = 'AuthError'; + this.status = status; + this.code = code; + } +} +export function isAuthError(error) { + return typeof error === 'object' && error !== null && '__isAuthError' in error; +} +/** + * Error returned directly from the GoTrue REST API. + * + * @example + * ```ts + * import { AuthApiError } from '@supabase/auth-js' + * + * throw new AuthApiError('Invalid credentials', 400, 'invalid_credentials') + * ``` + */ +export class AuthApiError extends AuthError { + constructor(message, status, code) { + super(message, status, code); + this.name = 'AuthApiError'; + this.status = status; + this.code = code; + } +} +export function isAuthApiError(error) { + return isAuthError(error) && error.name === 'AuthApiError'; +} +/** + * Wraps non-standard errors so callers can inspect the root cause. + * + * @example + * ```ts + * import { AuthUnknownError } from '@supabase/auth-js' + * + * try { + * await someAuthCall() + * } catch (err) { + * throw new AuthUnknownError('Auth failed', err) + * } + * ``` + */ +export class AuthUnknownError extends AuthError { + constructor(message, originalError) { + super(message); + this.name = 'AuthUnknownError'; + this.originalError = originalError; + } +} +/** + * Flexible error class used to create named auth errors at runtime. + * + * @example + * ```ts + * import { CustomAuthError } from '@supabase/auth-js' + * + * throw new CustomAuthError('My custom auth error', 'MyAuthError', 400, 'custom_code') + * ``` + */ +export class CustomAuthError extends AuthError { + constructor(message, name, status, code) { + super(message, status, code); + this.name = name; + this.status = status; + } +} +/** + * Error thrown when an operation requires a session but none is present. + * + * @example + * ```ts + * import { AuthSessionMissingError } from '@supabase/auth-js' + * + * throw new AuthSessionMissingError() + * ``` + */ +export class AuthSessionMissingError extends CustomAuthError { + constructor() { + super('Auth session missing!', 'AuthSessionMissingError', 400, undefined); + } +} +export function isAuthSessionMissingError(error) { + return isAuthError(error) && error.name === 'AuthSessionMissingError'; +} +/** + * Error thrown when the token response is malformed. + * + * @example + * ```ts + * import { AuthInvalidTokenResponseError } from '@supabase/auth-js' + * + * throw new AuthInvalidTokenResponseError() + * ``` + */ +export class AuthInvalidTokenResponseError extends CustomAuthError { + constructor() { + super('Auth session or user missing', 'AuthInvalidTokenResponseError', 500, undefined); + } +} +/** + * Error thrown when email/password credentials are invalid. + * + * @example + * ```ts + * import { AuthInvalidCredentialsError } from '@supabase/auth-js' + * + * throw new AuthInvalidCredentialsError('Email or password is incorrect') + * ``` + */ +export class AuthInvalidCredentialsError extends CustomAuthError { + constructor(message) { + super(message, 'AuthInvalidCredentialsError', 400, undefined); + } +} +/** + * Error thrown when implicit grant redirects contain an error. + * + * @example + * ```ts + * import { AuthImplicitGrantRedirectError } from '@supabase/auth-js' + * + * throw new AuthImplicitGrantRedirectError('OAuth redirect failed', { + * error: 'access_denied', + * code: 'oauth_error', + * }) + * ``` + */ +export class AuthImplicitGrantRedirectError extends CustomAuthError { + constructor(message, details = null) { + super(message, 'AuthImplicitGrantRedirectError', 500, undefined); + this.details = null; + this.details = details; + } + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + details: this.details, + }; + } +} +export function isAuthImplicitGrantRedirectError(error) { + return isAuthError(error) && error.name === 'AuthImplicitGrantRedirectError'; +} +/** + * Error thrown during PKCE code exchanges. + * + * @example + * ```ts + * import { AuthPKCEGrantCodeExchangeError } from '@supabase/auth-js' + * + * throw new AuthPKCEGrantCodeExchangeError('PKCE exchange failed') + * ``` + */ +export class AuthPKCEGrantCodeExchangeError extends CustomAuthError { + constructor(message, details = null) { + super(message, 'AuthPKCEGrantCodeExchangeError', 500, undefined); + this.details = null; + this.details = details; + } + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + details: this.details, + }; + } +} +/** + * Error thrown when a transient fetch issue occurs. + * + * @example + * ```ts + * import { AuthRetryableFetchError } from '@supabase/auth-js' + * + * throw new AuthRetryableFetchError('Service temporarily unavailable', 503) + * ``` + */ +export class AuthRetryableFetchError extends CustomAuthError { + constructor(message, status) { + super(message, 'AuthRetryableFetchError', status, undefined); + } +} +export function isAuthRetryableFetchError(error) { + return isAuthError(error) && error.name === 'AuthRetryableFetchError'; +} +/** + * This error is thrown on certain methods when the password used is deemed + * weak. Inspect the reasons to identify what password strength rules are + * inadequate. + */ +/** + * Error thrown when a supplied password is considered weak. + * + * @example + * ```ts + * import { AuthWeakPasswordError } from '@supabase/auth-js' + * + * throw new AuthWeakPasswordError('Password too short', 400, ['min_length']) + * ``` + */ +export class AuthWeakPasswordError extends CustomAuthError { + constructor(message, status, reasons) { + super(message, 'AuthWeakPasswordError', status, 'weak_password'); + this.reasons = reasons; + } +} +export function isAuthWeakPasswordError(error) { + return isAuthError(error) && error.name === 'AuthWeakPasswordError'; +} +/** + * Error thrown when a JWT cannot be verified or parsed. + * + * @example + * ```ts + * import { AuthInvalidJwtError } from '@supabase/auth-js' + * + * throw new AuthInvalidJwtError('Token signature is invalid') + * ``` + */ +export class AuthInvalidJwtError extends CustomAuthError { + constructor(message) { + super(message, 'AuthInvalidJwtError', 400, 'invalid_jwt'); + } +} +//# sourceMappingURL=errors.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/errors.js.map b/backend/node_modules/@supabase/auth-js/dist/module/lib/errors.js.map new file mode 100644 index 0000000..b421a4d --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../src/lib/errors.ts"],"names":[],"mappings":"AAGA;;;;;;;;;GASG;AACH,MAAM,OAAO,SAAU,SAAQ,KAAK;IAclC,YAAY,OAAe,EAAE,MAAe,EAAE,IAAa;QACzD,KAAK,CAAC,OAAO,CAAC,CAAA;QAHN,kBAAa,GAAG,IAAI,CAAA;QAI5B,IAAI,CAAC,IAAI,GAAG,WAAW,CAAA;QACvB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;IAClB,CAAC;CACF;AAED,MAAM,UAAU,WAAW,CAAC,KAAc;IACxC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,eAAe,IAAI,KAAK,CAAA;AAChF,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,OAAO,YAAa,SAAQ,SAAS;IAGzC,YAAY,OAAe,EAAE,MAAc,EAAE,IAAwB;QACnE,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,CAAA;QAC5B,IAAI,CAAC,IAAI,GAAG,cAAc,CAAA;QAC1B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,IAAI,GAAG,IAA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SAAS,CAAC,CAAA;IAC9D,CAAC;CACF;AAED,MAAM,UAAU,yBAAyB,CAAC,KAAc;IACtD,OAAO,WAAW,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK,yBAAyB,CAAA;AACvE,CAAC;AAED;;;;GAIG;AACH;;;;;;;;;GASG;AACH,MAAM,OAAO,qBAAsB,SAAQ,eAAe;IAMxD,YAAY,OAAe,EAAE,MAAc,EAAE,OAA8B;QACzE,KAAK,CAAC,OAAO,EAAE,uBAAuB,EAAE,MAAM,EAAE,eAAe,CAAC,CAAA;QAEhE,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;IACxB,CAAC;CACF;AAED,MAAM,UAAU,uBAAuB,CAAC,KAAc;IACpD,OAAO,WAAW,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK,uBAAuB,CAAA;AACrE,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,OAAO,mBAAoB,SAAQ,eAAe;IACtD,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,EAAE,qBAAqB,EAAE,GAAG,EAAE,aAAa,CAAC,CAAA;IAC3D,CAAC;CACF"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/fetch.d.ts b/backend/node_modules/@supabase/auth-js/dist/module/lib/fetch.d.ts new file mode 100644 index 0000000..4649c74 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/fetch.d.ts @@ -0,0 +1,34 @@ +import { AuthResponse, AuthResponsePassword, SSOResponse, GenerateLinkResponse, UserResponse } from './types'; +export type Fetch = typeof fetch; +export interface FetchOptions { + headers?: { + [key: string]: string; + }; + noResolveJson?: boolean; +} +export interface FetchParameters { + signal?: AbortSignal; +} +export type RequestMethodType = 'GET' | 'POST' | 'PUT' | 'DELETE'; +export declare function handleError(error: unknown): Promise; +interface GotrueRequestOptions extends FetchOptions { + jwt?: string; + redirectTo?: string; + body?: object; + query?: { + [key: string]: string; + }; + /** + * Function that transforms api response from gotrue into a desirable / standardised format + */ + xform?: (data: any) => any; +} +export declare function _request(fetcher: Fetch, method: RequestMethodType, url: string, options?: GotrueRequestOptions): Promise; +export declare function _sessionResponse(data: any): AuthResponse; +export declare function _sessionResponsePassword(data: any): AuthResponsePassword; +export declare function _userResponse(data: any): UserResponse; +export declare function _ssoResponse(data: any): SSOResponse; +export declare function _generateLinkResponse(data: any): GenerateLinkResponse; +export declare function _noResolveJsonResponse(data: any): Response; +export {}; +//# sourceMappingURL=fetch.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/fetch.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/module/lib/fetch.d.ts.map new file mode 100644 index 0000000..9f607b0 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/fetch.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../../../src/lib/fetch.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,YAAY,EACZ,oBAAoB,EACpB,WAAW,EAEX,oBAAoB,EAEpB,YAAY,EACb,MAAM,SAAS,CAAA;AAShB,MAAM,MAAM,KAAK,GAAG,OAAO,KAAK,CAAA;AAEhC,MAAM,WAAW,YAAY;IAC3B,OAAO,CAAC,EAAE;QACR,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KACtB,CAAA;IACD,aAAa,CAAC,EAAE,OAAO,CAAA;CACxB;AAED,MAAM,WAAW,eAAe;IAC9B,MAAM,CAAC,EAAE,WAAW,CAAA;CACrB;AAED,MAAM,MAAM,iBAAiB,GAAG,KAAK,GAAG,MAAM,GAAG,KAAK,GAAG,QAAQ,CAAA;AAOjE,wBAAsB,WAAW,CAAC,KAAK,EAAE,OAAO,iBA+D/C;AAmBD,UAAU,oBAAqB,SAAQ,YAAY;IACjD,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,KAAK,CAAC,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE,CAAA;IACjC;;OAEG;IACH,KAAK,CAAC,EAAE,CAAC,IAAI,EAAE,GAAG,KAAK,GAAG,CAAA;CAC3B;AAED,wBAAsB,QAAQ,CAC5B,OAAO,EAAE,KAAK,EACd,MAAM,EAAE,iBAAiB,EACzB,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,oBAAoB,gBAgC/B;AAwCD,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,GAAG,GAAG,YAAY,CAYxD;AAED,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,GAAG,GAAG,oBAAoB,CAiBxE;AAED,wBAAgB,aAAa,CAAC,IAAI,EAAE,GAAG,GAAG,YAAY,CAGrD;AAED,wBAAgB,YAAY,CAAC,IAAI,EAAE,GAAG,GAAG,WAAW,CAEnD;AAED,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,GAAG,GAAG,oBAAoB,CAmBrE;AAED,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,GAAG,GAAG,QAAQ,CAE1D"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/fetch.js b/backend/node_modules/@supabase/auth-js/dist/module/lib/fetch.js new file mode 100644 index 0000000..7cc9e71 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/fetch.js @@ -0,0 +1,174 @@ +import { __rest } from "tslib"; +import { API_VERSIONS, API_VERSION_HEADER_NAME } from './constants'; +import { expiresAt, looksLikeFetchResponse, parseResponseAPIVersion } from './helpers'; +import { AuthApiError, AuthRetryableFetchError, AuthWeakPasswordError, AuthUnknownError, AuthSessionMissingError, } from './errors'; +const _getErrorMessage = (err) => err.msg || err.message || err.error_description || err.error || JSON.stringify(err); +const NETWORK_ERROR_CODES = [502, 503, 504]; +export async function handleError(error) { + var _a; + if (!looksLikeFetchResponse(error)) { + throw new AuthRetryableFetchError(_getErrorMessage(error), 0); + } + if (NETWORK_ERROR_CODES.includes(error.status)) { + // status in 500...599 range - server had an error, request might be retryed. + throw new AuthRetryableFetchError(_getErrorMessage(error), error.status); + } + let data; + try { + data = await error.json(); + } + catch (e) { + throw new AuthUnknownError(_getErrorMessage(e), e); + } + let errorCode = undefined; + const responseAPIVersion = parseResponseAPIVersion(error); + if (responseAPIVersion && + responseAPIVersion.getTime() >= API_VERSIONS['2024-01-01'].timestamp && + typeof data === 'object' && + data && + typeof data.code === 'string') { + errorCode = data.code; + } + else if (typeof data === 'object' && data && typeof data.error_code === 'string') { + errorCode = data.error_code; + } + if (!errorCode) { + // Legacy support for weak password errors, when there were no error codes + if (typeof data === 'object' && + data && + typeof data.weak_password === 'object' && + data.weak_password && + Array.isArray(data.weak_password.reasons) && + data.weak_password.reasons.length && + data.weak_password.reasons.reduce((a, i) => a && typeof i === 'string', true)) { + throw new AuthWeakPasswordError(_getErrorMessage(data), error.status, data.weak_password.reasons); + } + } + else if (errorCode === 'weak_password') { + throw new AuthWeakPasswordError(_getErrorMessage(data), error.status, ((_a = data.weak_password) === null || _a === void 0 ? void 0 : _a.reasons) || []); + } + else if (errorCode === 'session_not_found') { + // The `session_id` inside the JWT does not correspond to a row in the + // `sessions` table. This usually means the user has signed out, has been + // deleted, or their session has somehow been terminated. + throw new AuthSessionMissingError(); + } + throw new AuthApiError(_getErrorMessage(data), error.status || 500, errorCode); +} +const _getRequestParams = (method, options, parameters, body) => { + const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} }; + if (method === 'GET') { + return params; + } + params.headers = Object.assign({ 'Content-Type': 'application/json;charset=UTF-8' }, options === null || options === void 0 ? void 0 : options.headers); + params.body = JSON.stringify(body); + return Object.assign(Object.assign({}, params), parameters); +}; +export async function _request(fetcher, method, url, options) { + var _a; + const headers = Object.assign({}, options === null || options === void 0 ? void 0 : options.headers); + if (!headers[API_VERSION_HEADER_NAME]) { + headers[API_VERSION_HEADER_NAME] = API_VERSIONS['2024-01-01'].name; + } + if (options === null || options === void 0 ? void 0 : options.jwt) { + headers['Authorization'] = `Bearer ${options.jwt}`; + } + const qs = (_a = options === null || options === void 0 ? void 0 : options.query) !== null && _a !== void 0 ? _a : {}; + if (options === null || options === void 0 ? void 0 : options.redirectTo) { + qs['redirect_to'] = options.redirectTo; + } + const queryString = Object.keys(qs).length ? '?' + new URLSearchParams(qs).toString() : ''; + const data = await _handleRequest(fetcher, method, url + queryString, { + headers, + noResolveJson: options === null || options === void 0 ? void 0 : options.noResolveJson, + }, {}, options === null || options === void 0 ? void 0 : options.body); + return (options === null || options === void 0 ? void 0 : options.xform) ? options === null || options === void 0 ? void 0 : options.xform(data) : { data: Object.assign({}, data), error: null }; +} +async function _handleRequest(fetcher, method, url, options, parameters, body) { + const requestParams = _getRequestParams(method, options, parameters, body); + let result; + try { + result = await fetcher(url, Object.assign({}, requestParams)); + } + catch (e) { + console.error(e); + // fetch failed, likely due to a network or CORS error + throw new AuthRetryableFetchError(_getErrorMessage(e), 0); + } + if (!result.ok) { + await handleError(result); + } + if (options === null || options === void 0 ? void 0 : options.noResolveJson) { + return result; + } + try { + return await result.json(); + } + catch (e) { + await handleError(e); + } +} +export function _sessionResponse(data) { + var _a; + let session = null; + if (hasSession(data)) { + session = Object.assign({}, data); + if (!data.expires_at) { + session.expires_at = expiresAt(data.expires_in); + } + } + const user = (_a = data.user) !== null && _a !== void 0 ? _a : data; + return { data: { session, user }, error: null }; +} +export function _sessionResponsePassword(data) { + const response = _sessionResponse(data); + if (!response.error && + data.weak_password && + typeof data.weak_password === 'object' && + Array.isArray(data.weak_password.reasons) && + data.weak_password.reasons.length && + data.weak_password.message && + typeof data.weak_password.message === 'string' && + data.weak_password.reasons.reduce((a, i) => a && typeof i === 'string', true)) { + response.data.weak_password = data.weak_password; + } + return response; +} +export function _userResponse(data) { + var _a; + const user = (_a = data.user) !== null && _a !== void 0 ? _a : data; + return { data: { user }, error: null }; +} +export function _ssoResponse(data) { + return { data, error: null }; +} +export function _generateLinkResponse(data) { + const { action_link, email_otp, hashed_token, redirect_to, verification_type } = data, rest = __rest(data, ["action_link", "email_otp", "hashed_token", "redirect_to", "verification_type"]); + const properties = { + action_link, + email_otp, + hashed_token, + redirect_to, + verification_type, + }; + const user = Object.assign({}, rest); + return { + data: { + properties, + user, + }, + error: null, + }; +} +export function _noResolveJsonResponse(data) { + return data; +} +/** + * hasSession checks if the response object contains a valid session + * @param data A response object + * @returns true if a session is in the response + */ +function hasSession(data) { + return data.access_token && data.refresh_token && data.expires_in; +} +//# sourceMappingURL=fetch.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/fetch.js.map b/backend/node_modules/@supabase/auth-js/dist/module/lib/fetch.js.map new file mode 100644 index 0000000..b202b2e --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/fetch.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fetch.js","sourceRoot":"","sources":["../../../src/lib/fetch.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,YAAY,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAA;AACnE,OAAO,EAAE,SAAS,EAAE,sBAAsB,EAAE,uBAAuB,EAAE,MAAM,WAAW,CAAA;AAUtF,OAAO,EACL,YAAY,EACZ,uBAAuB,EACvB,qBAAqB,EACrB,gBAAgB,EAChB,uBAAuB,GACxB,MAAM,UAAU,CAAA;AAiBjB,MAAM,gBAAgB,GAAG,CAAC,GAAQ,EAAU,EAAE,CAC5C,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC,OAAO,IAAI,GAAG,CAAC,iBAAiB,IAAI,GAAG,CAAC,KAAK,IAAI,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAA;AAErF,MAAM,mBAAmB,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAA;AAE3C,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,KAAc;;IAC9C,IAAI,CAAC,sBAAsB,CAAC,KAAK,C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AC9C,OAAO,EAAE,IAAI,EAAE,EAAE,IAAI,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAA;AACxC,CAAC;AAED,MAAM,UAAU,YAAY,CAAC,IAAS;IACpC,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAA;AAC9B,CAAC;AAED,MAAM,UAAU,qBAAqB,CAAC,IAAS;IAC7C,MAAM,EAAE,WAAW,EAAE,SAAS,EAAE,YAAY,EAAE,WAAW,EAAE,iBAAiB,KAAc,IAAI,EAAb,IAAI,UAAK,IAAI,EAAxF,gFAAiF,CAAO,CAAA;IAE9F,MAAM,UAAU,GAA2B;QACzC,WAAW;QACX,SAAS;QACT,YAAY;QACZ,WAAW;QACX,iBAAiB;KAClB,CAAA;IAED,MAAM,IAAI,qBAAc,IAAI,CAAE,CAAA;IAC9B,OAAO;QACL,IAAI,EAAE;YACJ,UAAU;YACV,IAAI;SACL;QACD,KAAK,EAAE,IAAI;KACZ,CAAA;AACH,CAAC;AAED,MAAM,UAAU,sBAAsB,CAAC,IAAS;IAC9C,OAAO,IAAI,CAAA;AACb,CAAC;AAED;;;;GAIG;AACH,SAAS,UAAU,CAAC,IAAS;IAC3B,OAAO,IAAI,CAAC,YAAY,IAAI,IAAI,CAAC,aAAa,IAAI,IAAI,CAAC,UAAU,CAAA;AACnE,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/helpers.d.ts b/backend/node_modules/@supabase/auth-js/dist/module/lib/helpers.d.ts new file mode 100644 index 0000000..43fdc86 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/helpers.d.ts @@ -0,0 +1,91 @@ +import { JwtHeader, JwtPayload, SupportedStorage, User } from './types'; +import { Uint8Array_ } from './webauthn.dom'; +export declare function expiresAt(expiresIn: number): number; +/** + * Generates a unique identifier for internal callback subscriptions. + * + * This function uses JavaScript Symbols to create guaranteed-unique identifiers + * for auth state change callbacks. Symbols are ideal for this use case because: + * - They are guaranteed unique by the JavaScript runtime + * - They work in all environments (browser, SSR, Node.js) + * - They avoid issues with Next.js 16 deterministic rendering requirements + * - They are perfect for internal, non-serializable identifiers + * + * Note: This function is only used for internal subscription management, + * not for security-critical operations like session tokens. + */ +export declare function generateCallbackId(): symbol; +export declare const isBrowser: () => boolean; +/** + * Checks whether localStorage is supported on this browser. + */ +export declare const supportsLocalStorage: () => boolean; +/** + * Extracts parameters encoded in the URL both in the query and fragment. + */ +export declare function parseParametersFromURL(href: string): { + [parameter: string]: string; +}; +type Fetch = typeof fetch; +export declare const resolveFetch: (customFetch?: Fetch) => Fetch; +export declare const looksLikeFetchResponse: (maybeResponse: unknown) => maybeResponse is Response; +export declare const setItemAsync: (storage: SupportedStorage, key: string, data: any) => Promise; +export declare const getItemAsync: (storage: SupportedStorage, key: string) => Promise; +export declare const removeItemAsync: (storage: SupportedStorage, key: string) => Promise; +/** + * A deferred represents some asynchronous work that is not yet finished, which + * may or may not culminate in a value. + * Taken from: https://github.com/mike-north/types/blob/master/src/async.ts + */ +export declare class Deferred { + static promiseConstructor: PromiseConstructor; + readonly promise: PromiseLike; + readonly resolve: (value?: T | PromiseLike) => void; + readonly reject: (reason?: any) => any; + constructor(); +} +export declare function decodeJWT(token: string): { + header: JwtHeader; + payload: JwtPayload; + signature: Uint8Array_; + raw: { + header: string; + payload: string; + }; +}; +/** + * Creates a promise that resolves to null after some time. + */ +export declare function sleep(time: number): Promise; +/** + * Converts the provided async function into a retryable function. Each result + * or thrown error is sent to the isRetryable function which should return true + * if the function should run again. + */ +export declare function retryable(fn: (attempt: number) => Promise, isRetryable: (attempt: number, error: any | null, result?: T) => boolean): Promise; +export declare function generatePKCEVerifier(): string; +export declare function generatePKCEChallenge(verifier: string): Promise; +export declare function getCodeChallengeAndMethod(storage: SupportedStorage, storageKey: string, isPasswordRecovery?: boolean): Promise; +export declare function parseResponseAPIVersion(response: Response): Date | null; +export declare function validateExp(exp: number): void; +export declare function getAlgorithm(alg: 'HS256' | 'RS256' | 'ES256'): RsaHashedImportParams | EcKeyImportParams; +export declare function validateUUID(str: string): void; +export declare function userNotAvailableProxy(): User; +/** + * Creates a proxy around a user object that warns when properties are accessed on the server. + * This is used to alert developers that using user data from getSession() on the server is insecure. + * + * @param user The actual user object to wrap + * @param suppressWarningRef An object with a 'value' property that controls warning suppression + * @returns A proxied user object that warns on property access + */ +export declare function insecureUserWarningProxy(user: User, suppressWarningRef: { + value: boolean; +}): User; +/** + * Deep clones a JSON-serializable object using JSON.parse(JSON.stringify(obj)). + * Note: Only works for JSON-safe data. + */ +export declare function deepClone(obj: T): T; +export {}; +//# sourceMappingURL=helpers.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/helpers.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/module/lib/helpers.d.ts.map new file mode 100644 index 0000000..b87fd00 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/helpers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../../../src/lib/helpers.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,gBAAgB,EAAE,IAAI,EAAE,MAAM,SAAS,CAAA;AACvE,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA;AAE5C,wBAAgB,SAAS,CAAC,SAAS,EAAE,MAAM,UAG1C;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,kBAAkB,IAAI,MAAM,CAE3C;AAED,eAAO,MAAM,SAAS,eAAyE,CAAA;AAO/F;;GAEG;AACH,eAAO,MAAM,oBAAoB,eAmChC,CAAA;AAED;;GAEG;AACH,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,MAAM;;EAsBlD;AAED,KAAK,KAAK,GAAG,OAAO,KAAK,CAAA;AAEzB,eAAO,MAAM,YAAY,GAAI,cAAc,KAAK,KAAG,KAKlD,CAAA;AAED,eAAO,MAAM,sBAAsB,GAAI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MAAM,CAAC,EAAE,CAAC,KAAK,OAAO,GACvE,OAAO,CAAC,CAAC,CAAC,CAuBZ;AAOD,wBAAgB,oBAAoB,WAcnC;AAaD,wBAAsB,qBAAqB,CAAC,QAAQ,EAAE,MAAM,mBAc3D;AAED,wBAAsB,yBAAyB,CAC7C,OAAO,EAAE,gBAAgB,EACzB,UAAU,EAAE,MAAM,EAClB,kBAAkB,UAAQ,qBAW3B;AAKD,wBAAgB,uBAAuB,CAAC,QAAQ,EAAE,QAAQ,eAiBzD;AAED,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,QAQtC;AAED,wBAAgB,YAAY,CAC1B,GAAG,EAAE,OAAO,GAAG,OAAO,GAAG,OAAO,GAC/B,qBAAqB,GAAG,iBAAiB,CAgB3C;AAID,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,QAIvC;AAED,wBAAgB,qBAAqB,IAAI,IAAI,CAoC5C;AAED;;;;;;;GAOG;AACH,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,IAAI,EAAE,kBAAkB,EAAE;IAAE,KAAK,EAAE,OAAO,CAAA;CAAE,GAAG,IAAI,CAkCjG;AAED;;;GAGG;AACH,wBAAgB,SAAS,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,CAEtC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/helpers.js b/backend/node_modules/@supabase/auth-js/dist/module/lib/helpers.js new file mode 100644 index 0000000..fd20006 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/helpers.js @@ -0,0 +1,368 @@ +import { API_VERSION_HEADER_NAME, BASE64URL_REGEX } from './constants'; +import { AuthInvalidJwtError } from './errors'; +import { base64UrlToUint8Array, stringFromBase64URL } from './base64url'; +export function expiresAt(expiresIn) { + const timeNow = Math.round(Date.now() / 1000); + return timeNow + expiresIn; +} +/** + * Generates a unique identifier for internal callback subscriptions. + * + * This function uses JavaScript Symbols to create guaranteed-unique identifiers + * for auth state change callbacks. Symbols are ideal for this use case because: + * - They are guaranteed unique by the JavaScript runtime + * - They work in all environments (browser, SSR, Node.js) + * - They avoid issues with Next.js 16 deterministic rendering requirements + * - They are perfect for internal, non-serializable identifiers + * + * Note: This function is only used for internal subscription management, + * not for security-critical operations like session tokens. + */ +export function generateCallbackId() { + return Symbol('auth-callback'); +} +export const isBrowser = () => typeof window !== 'undefined' && typeof document !== 'undefined'; +const localStorageWriteTests = { + tested: false, + writable: false, +}; +/** + * Checks whether localStorage is supported on this browser. + */ +export const supportsLocalStorage = () => { + if (!isBrowser()) { + return false; + } + try { + if (typeof globalThis.localStorage !== 'object') { + return false; + } + } + catch (e) { + // DOM exception when accessing `localStorage` + return false; + } + if (localStorageWriteTests.tested) { + return localStorageWriteTests.writable; + } + const randomKey = `lswt-${Math.random()}${Math.random()}`; + try { + globalThis.localStorage.setItem(randomKey, randomKey); + globalThis.localStorage.removeItem(randomKey); + localStorageWriteTests.tested = true; + localStorageWriteTests.writable = true; + } + catch (e) { + // localStorage can't be written to + // https://www.chromium.org/for-testers/bug-reporting-guidelines/uncaught-securityerror-failed-to-read-the-localstorage-property-from-window-access-is-denied-for-this-document + localStorageWriteTests.tested = true; + localStorageWriteTests.writable = false; + } + return localStorageWriteTests.writable; +}; +/** + * Extracts parameters encoded in the URL both in the query and fragment. + */ +export function parseParametersFromURL(href) { + const result = {}; + const url = new URL(href); + if (url.hash && url.hash[0] === '#') { + try { + const hashSearchParams = new URLSearchParams(url.hash.substring(1)); + hashSearchParams.forEach((value, key) => { + result[key] = value; + }); + } + catch (e) { + // hash is not a query string + } + } + // search parameters take precedence over hash parameters + url.searchParams.forEach((value, key) => { + result[key] = value; + }); + return result; +} +export const resolveFetch = (customFetch) => { + if (customFetch) { + return (...args) => customFetch(...args); + } + return (...args) => fetch(...args); +}; +export const looksLikeFetchResponse = (maybeResponse) => { + return (typeof maybeResponse === 'object' && + maybeResponse !== null && + 'status' in maybeResponse && + 'ok' in maybeResponse && + 'json' in maybeResponse && + typeof maybeResponse.json === 'function'); +}; +// Storage helpers +export const setItemAsync = async (storage, key, data) => { + await storage.setItem(key, JSON.stringify(data)); +}; +export const getItemAsync = async (storage, key) => { + const value = await storage.getItem(key); + if (!value) { + return null; + } + try { + return JSON.parse(value); + } + catch (_a) { + return value; + } +}; +export const removeItemAsync = async (storage, key) => { + await storage.removeItem(key); +}; +/** + * A deferred represents some asynchronous work that is not yet finished, which + * may or may not culminate in a value. + * Taken from: https://github.com/mike-north/types/blob/master/src/async.ts + */ +export class Deferred { + constructor() { + // eslint-disable-next-line @typescript-eslint/no-extra-semi + ; + this.promise = new Deferred.promiseConstructor((res, rej) => { + // eslint-disable-next-line @typescript-eslint/no-extra-semi + ; + this.resolve = res; + this.reject = rej; + }); + } +} +Deferred.promiseConstructor = Promise; +export function decodeJWT(token) { + const parts = token.split('.'); + if (parts.length !== 3) { + throw new AuthInvalidJwtError('Invalid JWT structure'); + } + // Regex checks for base64url format + for (let i = 0; i < parts.length; i++) { + if (!BASE64URL_REGEX.test(parts[i])) { + throw new AuthInvalidJwtError('JWT not in base64url format'); + } + } + const data = { + // using base64url lib + header: JSON.parse(stringFromBase64URL(parts[0])), + payload: JSON.parse(stringFromBase64URL(parts[1])), + signature: base64UrlToUint8Array(parts[2]), + raw: { + header: parts[0], + payload: parts[1], + }, + }; + return data; +} +/** + * Creates a promise that resolves to null after some time. + */ +export async function sleep(time) { + return await new Promise((accept) => { + setTimeout(() => accept(null), time); + }); +} +/** + * Converts the provided async function into a retryable function. Each result + * or thrown error is sent to the isRetryable function which should return true + * if the function should run again. + */ +export function retryable(fn, isRetryable) { + const promise = new Promise((accept, reject) => { + // eslint-disable-next-line @typescript-eslint/no-extra-semi + ; + (async () => { + for (let attempt = 0; attempt < Infinity; attempt++) { + try { + const result = await fn(attempt); + if (!isRetryable(attempt, null, result)) { + accept(result); + return; + } + } + catch (e) { + if (!isRetryable(attempt, e)) { + reject(e); + return; + } + } + } + })(); + }); + return promise; +} +function dec2hex(dec) { + return ('0' + dec.toString(16)).substr(-2); +} +// Functions below taken from: https://stackoverflow.com/questions/63309409/creating-a-code-verifier-and-challenge-for-pkce-auth-on-spotify-api-in-reactjs +export function generatePKCEVerifier() { + const verifierLength = 56; + const array = new Uint32Array(verifierLength); + if (typeof crypto === 'undefined') { + const charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~'; + const charSetLen = charSet.length; + let verifier = ''; + for (let i = 0; i < verifierLength; i++) { + verifier += charSet.charAt(Math.floor(Math.random() * charSetLen)); + } + return verifier; + } + crypto.getRandomValues(array); + return Array.from(array, dec2hex).join(''); +} +async function sha256(randomString) { + const encoder = new TextEncoder(); + const encodedData = encoder.encode(randomString); + const hash = await crypto.subtle.digest('SHA-256', encodedData); + const bytes = new Uint8Array(hash); + return Array.from(bytes) + .map((c) => String.fromCharCode(c)) + .join(''); +} +export async function generatePKCEChallenge(verifier) { + const hasCryptoSupport = typeof crypto !== 'undefined' && + typeof crypto.subtle !== 'undefined' && + typeof TextEncoder !== 'undefined'; + if (!hasCryptoSupport) { + console.warn('WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256.'); + return verifier; + } + const hashed = await sha256(verifier); + return btoa(hashed).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); +} +export async function getCodeChallengeAndMethod(storage, storageKey, isPasswordRecovery = false) { + const codeVerifier = generatePKCEVerifier(); + let storedCodeVerifier = codeVerifier; + if (isPasswordRecovery) { + storedCodeVerifier += '/PASSWORD_RECOVERY'; + } + await setItemAsync(storage, `${storageKey}-code-verifier`, storedCodeVerifier); + const codeChallenge = await generatePKCEChallenge(codeVerifier); + const codeChallengeMethod = codeVerifier === codeChallenge ? 'plain' : 's256'; + return [codeChallenge, codeChallengeMethod]; +} +/** Parses the API version which is 2YYY-MM-DD. */ +const API_VERSION_REGEX = /^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i; +export function parseResponseAPIVersion(response) { + const apiVersion = response.headers.get(API_VERSION_HEADER_NAME); + if (!apiVersion) { + return null; + } + if (!apiVersion.match(API_VERSION_REGEX)) { + return null; + } + try { + const date = new Date(`${apiVersion}T00:00:00.0Z`); + return date; + } + catch (e) { + return null; + } +} +export function validateExp(exp) { + if (!exp) { + throw new Error('Missing exp claim'); + } + const timeNow = Math.floor(Date.now() / 1000); + if (exp <= timeNow) { + throw new Error('JWT has expired'); + } +} +export function getAlgorithm(alg) { + switch (alg) { + case 'RS256': + return { + name: 'RSASSA-PKCS1-v1_5', + hash: { name: 'SHA-256' }, + }; + case 'ES256': + return { + name: 'ECDSA', + namedCurve: 'P-256', + hash: { name: 'SHA-256' }, + }; + default: + throw new Error('Invalid alg claim'); + } +} +const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; +export function validateUUID(str) { + if (!UUID_REGEX.test(str)) { + throw new Error('@supabase/auth-js: Expected parameter to be UUID but is not'); + } +} +export function userNotAvailableProxy() { + const proxyTarget = {}; + return new Proxy(proxyTarget, { + get: (target, prop) => { + if (prop === '__isUserNotAvailableProxy') { + return true; + } + // Preventative check for common problematic symbols during cloning/inspection + // These symbols might be accessed by structuredClone or other internal mechanisms. + if (typeof prop === 'symbol') { + const sProp = prop.toString(); + if (sProp === 'Symbol(Symbol.toPrimitive)' || + sProp === 'Symbol(Symbol.toStringTag)' || + sProp === 'Symbol(util.inspect.custom)') { + // Node.js util.inspect + return undefined; + } + } + throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${prop}" property of the session object is not supported. Please use getUser() instead.`); + }, + set: (_target, prop) => { + throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${prop}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`); + }, + deleteProperty: (_target, prop) => { + throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${prop}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`); + }, + }); +} +/** + * Creates a proxy around a user object that warns when properties are accessed on the server. + * This is used to alert developers that using user data from getSession() on the server is insecure. + * + * @param user The actual user object to wrap + * @param suppressWarningRef An object with a 'value' property that controls warning suppression + * @returns A proxied user object that warns on property access + */ +export function insecureUserWarningProxy(user, suppressWarningRef) { + return new Proxy(user, { + get: (target, prop, receiver) => { + // Allow internal checks without warning + if (prop === '__isInsecureUserWarningProxy') { + return true; + } + // Preventative check for common problematic symbols during cloning/inspection + // These symbols might be accessed by structuredClone or other internal mechanisms + if (typeof prop === 'symbol') { + const sProp = prop.toString(); + if (sProp === 'Symbol(Symbol.toPrimitive)' || + sProp === 'Symbol(Symbol.toStringTag)' || + sProp === 'Symbol(util.inspect.custom)' || + sProp === 'Symbol(nodejs.util.inspect.custom)') { + // Return the actual value for these symbols to allow proper inspection + return Reflect.get(target, prop, receiver); + } + } + // Emit warning on first property access + if (!suppressWarningRef.value && typeof prop === 'string') { + console.warn('Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server.'); + suppressWarningRef.value = true; + } + return Reflect.get(target, prop, receiver); + }, + }); +} +/** + * Deep clones a JSON-serializable object using JSON.parse(JSON.stringify(obj)). + * Note: Only works for JSON-safe data. + */ +export function deepClone(obj) { + return JSON.parse(JSON.stringify(obj)); +} +//# sourceMappingURL=helpers.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/helpers.js.map b/backend/node_modules/@supabase/auth-js/dist/module/lib/helpers.js.map new file mode 100644 index 0000000..f5577ae --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/helpers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"helpers.js","sourceRoot":"","sources":["../../../src/lib/helpers.ts"],"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BAAsC;IACzF,OAAO,IAAI,KAAK,CAAC,IAAI,EAAE;QACrB,GAAG,EAAE,CAAC,MAAW,EAAE,IAAqB,EAAE,QAAa,EAAE,EAAE;YACzD,wCAAwC;YACxC,IAAI,IAAI,KAAK,8BAA8B,EAAE,CAAC;gBAC5C,OAAO,IAAI,CAAA;YACb,CAAC;YAED,8EAA8E;YAC9E,kFAAkF;YAClF,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;gBAC7B,MAAM,KAAK,GAAG,IAAI,CAAC,QAAQ,EAAE,CAAA;gBAC7B,IACE,KAAK,KAAK,4BAA4B;oBACtC,KAAK,KAAK,4BAA4B;oBACtC,KAAK,KAAK,6BAA6B;oBACvC,KAAK,KAAK,oCAAoC,EAC9C,CAAC;oBACD,uEAAuE;oBACvE,OAAO,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAA;gBAC5C,CAAC;YACH,CAAC;YAED,wCAAwC;YACxC,IAAI,CAAC,kBAAkB,CAAC,KAAK,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;gBAC1D,OAAO,CAAC,IAAI,CACV,iWAAiW,CAClW,CAAA;gBACD,kBAAkB,CAAC,KAAK,GAAG,IAAI,CAAA;YACjC,CAAC;YAED,OAAO,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAA;QAC5C,CAAC;KACF,CAAC,CAAA;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,SAAS,CAAI,GAAM;IACjC,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAA;AACxC,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/local-storage.d.ts b/backend/node_modules/@supabase/auth-js/dist/module/lib/local-storage.d.ts new file mode 100644 index 0000000..05dabc3 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/local-storage.d.ts @@ -0,0 +1,9 @@ +import { SupportedStorage } from './types'; +/** + * Returns a localStorage-like object that stores the key-value pairs in + * memory. + */ +export declare function memoryLocalStorageAdapter(store?: { + [key: string]: string; +}): SupportedStorage; +//# sourceMappingURL=local-storage.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/local-storage.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/module/lib/local-storage.d.ts.map new file mode 100644 index 0000000..7dc636e --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/local-storage.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"local-storage.d.ts","sourceRoot":"","sources":["../../../src/lib/local-storage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAE1C;;;GAGG;AACH,wBAAgB,yBAAyB,CAAC,KAAK,GAAE;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;CAAO,GAAG,gBAAgB,CAcjG"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/local-storage.js b/backend/node_modules/@supabase/auth-js/dist/module/lib/local-storage.js new file mode 100644 index 0000000..ee52a6f --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/local-storage.js @@ -0,0 +1,18 @@ +/** + * Returns a localStorage-like object that stores the key-value pairs in + * memory. + */ +export function memoryLocalStorageAdapter(store = {}) { + return { + getItem: (key) => { + return store[key] || null; + }, + setItem: (key, value) => { + store[key] = value; + }, + removeItem: (key) => { + delete store[key]; + }, + }; +} +//# sourceMappingURL=local-storage.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/local-storage.js.map b/backend/node_modules/@supabase/auth-js/dist/module/lib/local-storage.js.map new file mode 100644 index 0000000..c1399df --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/local-storage.js.map @@ -0,0 +1 @@ +{"version":3,"file":"local-storage.js","sourceRoot":"","sources":["../../../src/lib/local-storage.ts"],"names":[],"mappings":"AAEA;;;GAGG;AACH,MAAM,UAAU,yBAAyB,CAAC,QAAmC,EAAE;IAC7E,OAAO;QACL,OAAO,EAAE,CAAC,GAAG,EAAE,EAAE;YACf,OAAO,KAAK,CAAC,GAAG,CAAC,IAAI,IAAI,CAAA;QAC3B,CAAC;QAED,OAAO,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE;YACtB,KAAK,CAAC,GAAG,CAAC,GAAG,KAAK,CAAA;QACpB,CAAC;QAED,UAAU,EAAE,CAAC,GAAG,EAAE,EAAE;YAClB,OAAO,KAAK,CAAC,GAAG,CAAC,CAAA;QACnB,CAAC;KACF,CAAA;AACH,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/locks.d.ts b/backend/node_modules/@supabase/auth-js/dist/module/lib/locks.d.ts new file mode 100644 index 0000000..41c5032 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/locks.d.ts @@ -0,0 +1,107 @@ +/** + * @experimental + */ +export declare const internals: { + /** + * @experimental + */ + debug: boolean; +}; +/** + * An error thrown when a lock cannot be acquired after some amount of time. + * + * Use the {@link #isAcquireTimeout} property instead of checking with `instanceof`. + * + * @example + * ```ts + * import { LockAcquireTimeoutError } from '@supabase/auth-js' + * + * class CustomLockError extends LockAcquireTimeoutError { + * constructor() { + * super('Lock timed out') + * } + * } + * ``` + */ +export declare abstract class LockAcquireTimeoutError extends Error { + readonly isAcquireTimeout = true; + constructor(message: string); +} +/** + * Error thrown when the browser Navigator Lock API fails to acquire a lock. + * + * @example + * ```ts + * import { NavigatorLockAcquireTimeoutError } from '@supabase/auth-js' + * + * throw new NavigatorLockAcquireTimeoutError('Lock timed out') + * ``` + */ +export declare class NavigatorLockAcquireTimeoutError extends LockAcquireTimeoutError { +} +/** + * Error thrown when the process-level lock helper cannot acquire a lock. + * + * @example + * ```ts + * import { ProcessLockAcquireTimeoutError } from '@supabase/auth-js' + * + * throw new ProcessLockAcquireTimeoutError('Lock timed out') + * ``` + */ +export declare class ProcessLockAcquireTimeoutError extends LockAcquireTimeoutError { +} +/** + * Implements a global exclusive lock using the Navigator LockManager API. It + * is available on all browsers released after 2022-03-15 with Safari being the + * last one to release support. If the API is not available, this function will + * throw. Make sure you check availablility before configuring {@link + * GoTrueClient}. + * + * You can turn on debugging by setting the `supabase.gotrue-js.locks.debug` + * local storage item to `true`. + * + * Internals: + * + * Since the LockManager API does not preserve stack traces for the async + * function passed in the `request` method, a trick is used where acquiring the + * lock releases a previously started promise to run the operation in the `fn` + * function. The lock waits for that promise to finish (with or without error), + * while the function will finally wait for the result anyway. + * + * @param name Name of the lock to be acquired. + * @param acquireTimeout If negative, no timeout. If 0 an error is thrown if + * the lock can't be acquired without waiting. If positive, the lock acquire + * will time out after so many milliseconds. An error is + * a timeout if it has `isAcquireTimeout` set to true. + * @param fn The operation to run once the lock is acquired. + * @example + * ```ts + * await navigatorLock('sync-user', 1000, async () => { + * await refreshSession() + * }) + * ``` + */ +export declare function navigatorLock(name: string, acquireTimeout: number, fn: () => Promise): Promise; +/** + * Implements a global exclusive lock that works only in the current process. + * Useful for environments like React Native or other non-browser + * single-process (i.e. no concept of "tabs") environments. + * + * Use {@link #navigatorLock} in browser environments. + * + * @param name Name of the lock to be acquired. + * @param acquireTimeout If negative, no timeout. If 0 an error is thrown if + * the lock can't be acquired without waiting. If positive, the lock acquire + * will time out after so many milliseconds. An error is + * a timeout if it has `isAcquireTimeout` set to true. + * @param fn The operation to run once the lock is acquired. + * @example + * ```ts + * await processLock('migrate', 5000, async () => { + * await runMigration() + * }) + * ``` + */ +export declare function processLock(name: string, acquireTimeout: number, fn: () => Promise): Promise; +//# sourceMappingURL=locks.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/locks.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/module/lib/locks.d.ts.map new file mode 100644 index 0000000..c03b579 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/locks.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"locks.d.ts","sourceRoot":"","sources":["../../../src/lib/locks.ts"],"names":[],"mappings":"AAEA;;GAEG;AACH,eAAO,MAAM,SAAS;IACpB;;OAEG;;CAOJ,CAAA;AAED;;;;;;;;;;;;;;;GAeG;AACH,8BAAsB,uBAAwB,SAAQ,KAAK;IACzD,SAAgB,gBAAgB,QAAO;gBAE3B,OAAO,EAAE,MAAM;CAG5B;AAED;;;;;;;;;GASG;AACH,qBAAa,gCAAiC,SAAQ,uBAAuB;CAAG;AAChF;;;;;;;;;GASG;AACH,qBAAa,8BAA+B,SAAQ,uBAAuB;CAAG;AAE9E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,wBAAsB,aAAa,CAAC,CAAC,EACnC,IAAI,EAAE,MAAM,EACZ,cAAc,EAAE,MAAM,EACtB,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GACnB,OAAO,CAAC,CAAC,CAAC,CA0FZ;AAID;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAsB,WAAW,CAAC,CAAC,EACjC,IAAI,EAAE,MAAM,EACZ,cAAc,EAAE,MAAM,EACtB,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GACnB,OAAO,CAAC,CAAC,CAAC,CAkDZ"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/locks.js b/backend/node_modules/@supabase/auth-js/dist/module/lib/locks.js new file mode 100644 index 0000000..186f3db --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/locks.js @@ -0,0 +1,222 @@ +import { supportsLocalStorage } from './helpers'; +/** + * @experimental + */ +export const internals = { + /** + * @experimental + */ + debug: !!(globalThis && + supportsLocalStorage() && + globalThis.localStorage && + globalThis.localStorage.getItem('supabase.gotrue-js.locks.debug') === 'true'), +}; +/** + * An error thrown when a lock cannot be acquired after some amount of time. + * + * Use the {@link #isAcquireTimeout} property instead of checking with `instanceof`. + * + * @example + * ```ts + * import { LockAcquireTimeoutError } from '@supabase/auth-js' + * + * class CustomLockError extends LockAcquireTimeoutError { + * constructor() { + * super('Lock timed out') + * } + * } + * ``` + */ +export class LockAcquireTimeoutError extends Error { + constructor(message) { + super(message); + this.isAcquireTimeout = true; + } +} +/** + * Error thrown when the browser Navigator Lock API fails to acquire a lock. + * + * @example + * ```ts + * import { NavigatorLockAcquireTimeoutError } from '@supabase/auth-js' + * + * throw new NavigatorLockAcquireTimeoutError('Lock timed out') + * ``` + */ +export class NavigatorLockAcquireTimeoutError extends LockAcquireTimeoutError { +} +/** + * Error thrown when the process-level lock helper cannot acquire a lock. + * + * @example + * ```ts + * import { ProcessLockAcquireTimeoutError } from '@supabase/auth-js' + * + * throw new ProcessLockAcquireTimeoutError('Lock timed out') + * ``` + */ +export class ProcessLockAcquireTimeoutError extends LockAcquireTimeoutError { +} +/** + * Implements a global exclusive lock using the Navigator LockManager API. It + * is available on all browsers released after 2022-03-15 with Safari being the + * last one to release support. If the API is not available, this function will + * throw. Make sure you check availablility before configuring {@link + * GoTrueClient}. + * + * You can turn on debugging by setting the `supabase.gotrue-js.locks.debug` + * local storage item to `true`. + * + * Internals: + * + * Since the LockManager API does not preserve stack traces for the async + * function passed in the `request` method, a trick is used where acquiring the + * lock releases a previously started promise to run the operation in the `fn` + * function. The lock waits for that promise to finish (with or without error), + * while the function will finally wait for the result anyway. + * + * @param name Name of the lock to be acquired. + * @param acquireTimeout If negative, no timeout. If 0 an error is thrown if + * the lock can't be acquired without waiting. If positive, the lock acquire + * will time out after so many milliseconds. An error is + * a timeout if it has `isAcquireTimeout` set to true. + * @param fn The operation to run once the lock is acquired. + * @example + * ```ts + * await navigatorLock('sync-user', 1000, async () => { + * await refreshSession() + * }) + * ``` + */ +export async function navigatorLock(name, acquireTimeout, fn) { + if (internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock: acquire lock', name, acquireTimeout); + } + const abortController = new globalThis.AbortController(); + if (acquireTimeout > 0) { + setTimeout(() => { + abortController.abort(); + if (internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock acquire timed out', name); + } + }, acquireTimeout); + } + // MDN article: https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request + // Wrapping navigator.locks.request() with a plain Promise is done as some + // libraries like zone.js patch the Promise object to track the execution + // context. However, it appears that most browsers use an internal promise + // implementation when using the navigator.locks.request() API causing them + // to lose context and emit confusing log messages or break certain features. + // This wrapping is believed to help zone.js track the execution context + // better. + return await Promise.resolve().then(() => globalThis.navigator.locks.request(name, acquireTimeout === 0 + ? { + mode: 'exclusive', + ifAvailable: true, + } + : { + mode: 'exclusive', + signal: abortController.signal, + }, async (lock) => { + if (lock) { + if (internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock: acquired', name, lock.name); + } + try { + return await fn(); + } + finally { + if (internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock: released', name, lock.name); + } + } + } + else { + if (acquireTimeout === 0) { + if (internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock: not immediately available', name); + } + throw new NavigatorLockAcquireTimeoutError(`Acquiring an exclusive Navigator LockManager lock "${name}" immediately failed`); + } + else { + if (internals.debug) { + try { + const result = await globalThis.navigator.locks.query(); + console.log('@supabase/gotrue-js: Navigator LockManager state', JSON.stringify(result, null, ' ')); + } + catch (e) { + console.warn('@supabase/gotrue-js: Error when querying Navigator LockManager state', e); + } + } + // Browser is not following the Navigator LockManager spec, it + // returned a null lock when we didn't use ifAvailable. So we can + // pretend the lock is acquired in the name of backward compatibility + // and user experience and just run the function. + console.warn('@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request'); + return await fn(); + } + } + })); +} +const PROCESS_LOCKS = {}; +/** + * Implements a global exclusive lock that works only in the current process. + * Useful for environments like React Native or other non-browser + * single-process (i.e. no concept of "tabs") environments. + * + * Use {@link #navigatorLock} in browser environments. + * + * @param name Name of the lock to be acquired. + * @param acquireTimeout If negative, no timeout. If 0 an error is thrown if + * the lock can't be acquired without waiting. If positive, the lock acquire + * will time out after so many milliseconds. An error is + * a timeout if it has `isAcquireTimeout` set to true. + * @param fn The operation to run once the lock is acquired. + * @example + * ```ts + * await processLock('migrate', 5000, async () => { + * await runMigration() + * }) + * ``` + */ +export async function processLock(name, acquireTimeout, fn) { + var _a; + const previousOperation = (_a = PROCESS_LOCKS[name]) !== null && _a !== void 0 ? _a : Promise.resolve(); + const currentOperation = Promise.race([ + previousOperation.catch(() => { + // ignore error of previous operation that we're waiting to finish + return null; + }), + acquireTimeout >= 0 + ? new Promise((_, reject) => { + setTimeout(() => { + reject(new ProcessLockAcquireTimeoutError(`Acquring process lock with name "${name}" timed out`)); + }, acquireTimeout); + }) + : null, + ].filter((x) => x)) + .catch((e) => { + if (e && e.isAcquireTimeout) { + throw e; + } + return null; + }) + .then(async () => { + // previous operations finished and we didn't get a race on the acquire + // timeout, so the current operation can finally start + return await fn(); + }); + PROCESS_LOCKS[name] = currentOperation.catch(async (e) => { + if (e && e.isAcquireTimeout) { + // if the current operation timed out, it doesn't mean that the previous + // operation finished, so we need contnue waiting for it to finish + await previousOperation; + return null; + } + throw e; + }); + // finally wait for the current operation to finish successfully, with an + // error or with an acquire timeout error + return await currentOperation; +} +//# sourceMappingURL=locks.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/locks.js.map b/backend/node_modules/@supabase/auth-js/dist/module/lib/locks.js.map new file mode 100644 index 0000000..6881102 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/locks.js.map @@ -0,0 +1 @@ +{"version":3,"file":"locks.js","sourceRoot":"","sources":["../../../src/lib/locks.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,WAAW,CAAA;AAEhD;;GAEG;AACH,MAAM,CAAC,MAAM,SA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QACT,CAAC;QAED,OAAO,IAAI,CAAA;IACb,CAAC,CAAC;SACD,IAAI,CAAC,KAAK,IAAI,EAAE;QACf,uEAAuE;QACvE,sDAAsD;QACtD,OAAO,MAAM,EAAE,EAAE,CAAA;IACnB,CAAC,CAAC,CAAA;IAEJ,aAAa,CAAC,IAAI,CAAC,GAAG,gBAAgB,CAAC,KAAK,CAAC,KAAK,EAAE,CAAM,EAAE,EAAE;QAC5D,IAAI,CAAC,IAAI,CAAC,CAAC,gBAAgB,EAAE,CAAC;YAC5B,wEAAwE;YACxE,kEAAkE;YAClE,MAAM,iBAAiB,CAAA;YAEvB,OAAO,IAAI,CAAA;QACb,CAAC;QAED,MAAM,CAAC,CAAA;IACT,CAAC,CAAC,CAAA;IAEF,yEAAyE;IACzE,yCAAyC;IACzC,OAAO,MAAM,gBAAgB,CAAA;AAC/B,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/polyfills.d.ts b/backend/node_modules/@supabase/auth-js/dist/module/lib/polyfills.d.ts new file mode 100644 index 0000000..d85562a --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/polyfills.d.ts @@ -0,0 +1,5 @@ +/** + * https://mathiasbynens.be/notes/globalthis + */ +export declare function polyfillGlobalThis(): void; +//# sourceMappingURL=polyfills.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/polyfills.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/module/lib/polyfills.d.ts.map new file mode 100644 index 0000000..ee5ea0f --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/polyfills.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfills.d.ts","sourceRoot":"","sources":["../../../src/lib/polyfills.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,wBAAgB,kBAAkB,SAmBjC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/polyfills.js b/backend/node_modules/@supabase/auth-js/dist/module/lib/polyfills.js new file mode 100644 index 0000000..7ab7d6c --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/polyfills.js @@ -0,0 +1,26 @@ +/** + * https://mathiasbynens.be/notes/globalthis + */ +export function polyfillGlobalThis() { + if (typeof globalThis === 'object') + return; + try { + Object.defineProperty(Object.prototype, '__magic__', { + get: function () { + return this; + }, + configurable: true, + }); + // @ts-expect-error 'Allow access to magic' + __magic__.globalThis = __magic__; + // @ts-expect-error 'Allow access to magic' + delete Object.prototype.__magic__; + } + catch (e) { + if (typeof self !== 'undefined') { + // @ts-expect-error 'Allow access to globals' + self.globalThis = self; + } + } +} +//# sourceMappingURL=polyfills.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/polyfills.js.map b/backend/node_modules/@supabase/auth-js/dist/module/lib/polyfills.js.map new file mode 100644 index 0000000..ae82f84 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/polyfills.js.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfills.js","sourceRoot":"","sources":["../../../src/lib/polyfills.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,UAAU,kBAAkB;IAChC,IAAI,OAAO,UAAU,KAAK,QAAQ;QAAE,OAAM;IAC1C,IAAI,CAAC;QACH,MAAM,CAAC,cAAc,CAAC,MAAM,CAAC,SAAS,EAAE,WAAW,EAAE;YACnD,GAAG,EAAE;gBACH,OAAO,IAAI,CAAA;YACb,CAAC;YACD,YAAY,EAAE,IAAI;SACnB,CAAC,CAAA;QACF,2CAA2C;QAC3C,SAAS,CAAC,UAAU,GAAG,SAAS,CAAA;QAChC,2CAA2C;QAC3C,OAAO,MAAM,CAAC,SAAS,CAAC,SAAS,CAAA;IACnC,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,IAAI,OAAO,IAAI,KAAK,WAAW,EAAE,CAAC;YAChC,6CAA6C;YAC7C,IAAI,CAAC,UAAU,GAAG,IAAI,CAAA;QACxB,CAAC;IACH,CAAC;AACH,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/types.d.ts b/backend/node_modules/@supabase/auth-js/dist/module/lib/types.d.ts new file mode 100644 index 0000000..2f66ff4 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/types.d.ts @@ -0,0 +1,1468 @@ +import { AuthError } from './errors'; +import { Fetch } from './fetch'; +import { EIP1193Provider, EthereumSignInInput, Hex } from './web3/ethereum'; +import type { SolanaSignInInput, SolanaSignInOutput } from './web3/solana'; +import { ServerCredentialCreationOptions, ServerCredentialRequestOptions, WebAuthnApi } from './webauthn'; +import { AuthenticationCredential, PublicKeyCredentialCreationOptionsFuture, PublicKeyCredentialRequestOptionsFuture, RegistrationCredential } from './webauthn.dom'; +/** One of the providers supported by GoTrue. */ +export type Provider = 'apple' | 'azure' | 'bitbucket' | 'discord' | 'facebook' | 'figma' | 'github' | 'gitlab' | 'google' | 'kakao' | 'keycloak' | 'linkedin' | 'linkedin_oidc' | 'notion' | 'slack' | 'slack_oidc' | 'spotify' | 'twitch' | 'twitter' | 'workos' | 'zoom' | 'fly'; +export type AuthChangeEventMFA = 'MFA_CHALLENGE_VERIFIED'; +export type AuthChangeEvent = 'INITIAL_SESSION' | 'PASSWORD_RECOVERY' | 'SIGNED_IN' | 'SIGNED_OUT' | 'TOKEN_REFRESHED' | 'USER_UPDATED' | AuthChangeEventMFA; +/** + * Provide your own global lock implementation instead of the default + * implementation. The function should acquire a lock for the duration of the + * `fn` async function, such that no other client instances will be able to + * hold it at the same time. + * + * @experimental + * + * @param name Name of the lock to be acquired. + * @param acquireTimeout If negative, no timeout should occur. If positive it + * should throw an Error with an `isAcquireTimeout` + * property set to true if the operation fails to be + * acquired after this much time (ms). + * @param fn The operation to execute when the lock is acquired. + */ +export type LockFunc = (name: string, acquireTimeout: number, fn: () => Promise) => Promise; +export type GoTrueClientOptions = { + url?: string; + headers?: { + [key: string]: string; + }; + storageKey?: string; + detectSessionInUrl?: boolean; + autoRefreshToken?: boolean; + persistSession?: boolean; + storage?: SupportedStorage; + /** + * Stores the user object in a separate storage location from the rest of the session data. When non-null, `storage` will only store a JSON object containing the access and refresh token and some adjacent metadata, while `userStorage` will only contain the user object under the key `storageKey + '-user'`. + * + * When this option is set and cookie storage is used, `getSession()` and other functions that load a session from the cookie store might not return back a user. It's very important to always use `getUser()` to fetch a user object in those scenarios. + * + * @experimental + */ + userStorage?: SupportedStorage; + fetch?: Fetch; + flowType?: AuthFlowType; + debug?: boolean | ((message: string, ...args: any[]) => void); + /** + * Provide your own locking mechanism based on the environment. By default no locking is done at this time. + * + * @experimental + */ + lock?: LockFunc; + /** + * Set to "true" if there is a custom authorization header set globally. + * @experimental + */ + hasCustomAuthorizationHeader?: boolean; + /** + * If there is an error with the query, throwOnError will reject the promise by + * throwing the error instead of returning it as part of a successful response. + */ + throwOnError?: boolean; +}; +declare const WeakPasswordReasons: readonly ["length", "characters", "pwned"]; +export type WeakPasswordReasons = (typeof WeakPasswordReasons)[number]; +export type WeakPassword = { + reasons: WeakPasswordReasons[]; + message: string; +}; +/** + * Resolve mapped types and show the derived keys and their types when hovering in + * VS Code, instead of just showing the names those mapped types are defined with. + */ +export type Prettify = T extends Function ? T : { + [K in keyof T]: T[K]; +}; +/** + * A stricter version of TypeScript's Omit that only allows omitting keys that actually exist. + * This prevents typos and ensures type safety at compile time. + * Unlike regular Omit, this will error if you try to omit a non-existent key. + */ +export type StrictOmit = Omit; +/** + * a shared result type that encapsulates errors instead of throwing them, allows you to optionally specify the ErrorType + */ +export type RequestResult = { + data: T; + error: null; +} | { + data: null; + error: Error extends AuthError ? AuthError : ErrorType; +}; +/** + * similar to RequestResult except it allows you to destructure the possible shape of the success response + * {@see RequestResult} + */ +export type RequestResultSafeDestructure = { + data: T; + error: null; +} | { + data: T extends object ? { + [K in keyof T]: null; + } : null; + error: AuthError; +}; +export type AuthResponse = RequestResultSafeDestructure<{ + user: User | null; + session: Session | null; +}>; +export type AuthResponsePassword = RequestResultSafeDestructure<{ + user: User | null; + session: Session | null; + weak_password?: WeakPassword | null; +}>; +/** + * AuthOtpResponse is returned when OTP is used. + * + * {@see AuthResponse} + */ +export type AuthOtpResponse = RequestResultSafeDestructure<{ + user: null; + session: null; + messageId?: string | null; +}>; +export type AuthTokenResponse = RequestResultSafeDestructure<{ + user: User; + session: Session; +}>; +export type AuthTokenResponsePassword = RequestResultSafeDestructure<{ + user: User; + session: Session; + weakPassword?: WeakPassword; +}>; +export type OAuthResponse = { + data: { + provider: Provider; + url: string; + }; + error: null; +} | { + data: { + provider: Provider; + url: null; + }; + error: AuthError; +}; +export type SSOResponse = RequestResult<{ + /** + * URL to open in a browser which will complete the sign-in flow by + * taking the user to the identity provider's authentication flow. + * + * On browsers you can set the URL to `window.location.href` to take + * the user to the authentication flow. + */ + url: string; +}>; +export type UserResponse = RequestResultSafeDestructure<{ + user: User; +}>; +export interface Session { + /** + * The oauth provider token. If present, this can be used to make external API requests to the oauth provider used. + */ + provider_token?: string | null; + /** + * The oauth provider refresh token. If present, this can be used to refresh the provider_token via the oauth provider's API. + * Not all oauth providers return a provider refresh token. If the provider_refresh_token is missing, please refer to the oauth provider's documentation for information on how to obtain the provider refresh token. + */ + provider_refresh_token?: string | null; + /** + * The access token jwt. It is recommended to set the JWT_EXPIRY to a shorter expiry value. + */ + access_token: string; + /** + * A one-time used refresh token that never expires. + */ + refresh_token: string; + /** + * The number of seconds until the token expires (since it was issued). Returned when a login is confirmed. + */ + expires_in: number; + /** + * A timestamp of when the token will expire. Returned when a login is confirmed. + */ + expires_at?: number; + token_type: 'bearer'; + /** + * When using a separate user storage, accessing properties of this object will throw an error. + */ + user: User; +} +declare const AMRMethods: readonly ["password", "otp", "oauth", "totp", "mfa/totp", "mfa/phone", "mfa/webauthn", "anonymous", "sso/saml", "magiclink", "web3"]; +export type AMRMethod = (typeof AMRMethods)[number] | (string & {}); +/** + * An authentication methord reference (AMR) entry. + * + * An entry designates what method was used by the user to verify their + * identity and at what time. + * + * @see {@link GoTrueMFAApi#getAuthenticatorAssuranceLevel}. + */ +export interface AMREntry { + /** Authentication method name. */ + method: AMRMethod; + /** + * Timestamp when the method was successfully used. Represents number of + * seconds since 1st January 1970 (UNIX epoch) in UTC. + */ + timestamp: number; +} +export interface UserIdentity { + id: string; + user_id: string; + identity_data?: { + [key: string]: any; + }; + identity_id: string; + provider: string; + created_at?: string; + last_sign_in_at?: string; + updated_at?: string; +} +declare const FactorTypes: readonly ["totp", "phone", "webauthn"]; +/** + * Type of factor. `totp` and `phone` supported with this version + */ +export type FactorType = (typeof FactorTypes)[number]; +declare const FactorVerificationStatuses: readonly ["verified", "unverified"]; +/** + * The verification status of the factor, default is `unverified` after `.enroll()`, then `verified` after the user verifies it with `.verify()` + */ +type FactorVerificationStatus = (typeof FactorVerificationStatuses)[number]; +/** + * A MFA factor. + * + * @see {@link GoTrueMFAApi#enroll} + * @see {@link GoTrueMFAApi#listFactors} + * @see {@link GoTrueMFAAdminApi#listFactors} + */ +export type Factor = { + /** ID of the factor. */ + id: string; + /** Friendly name of the factor, useful to disambiguate between multiple factors. */ + friendly_name?: string; + /** + * Type of factor. `totp` and `phone` supported with this version + */ + factor_type: Type; + /** + * The verification status of the factor, default is `unverified` after `.enroll()`, then `verified` after the user verifies it with `.verify()` + */ + status: Status; + created_at: string; + updated_at: string; +}; +export interface UserAppMetadata { + /** + * The first provider that the user used to sign up with. + */ + provider?: string; + /** + * A list of all providers that the user has linked to their account. + */ + providers?: string[]; + [key: string]: any; +} +export interface UserMetadata { + [key: string]: any; +} +export interface User { + id: string; + app_metadata: UserAppMetadata; + user_metadata: UserMetadata; + aud: string; + confirmation_sent_at?: string; + recovery_sent_at?: string; + email_change_sent_at?: string; + new_email?: string; + new_phone?: string; + invited_at?: string; + action_link?: string; + email?: string; + phone?: string; + created_at: string; + confirmed_at?: string; + email_confirmed_at?: string; + phone_confirmed_at?: string; + last_sign_in_at?: string; + role?: string; + updated_at?: string; + identities?: UserIdentity[]; + is_anonymous?: boolean; + is_sso_user?: boolean; + factors?: (Factor | Factor)[]; + deleted_at?: string; +} +export interface UserAttributes { + /** + * The user's email. + */ + email?: string; + /** + * The user's phone. + */ + phone?: string; + /** + * The user's password. + */ + password?: string; + /** + * The nonce sent for reauthentication if the user's password is to be updated. + * + * Call reauthenticate() to obtain the nonce first. + */ + nonce?: string; + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.raw_user_meta_data` column. + * + * The `data` should be a JSON object that includes user-specific info, such as their first and last name. + * + */ + data?: object; +} +export interface AdminUserAttributes extends Omit { + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.raw_user_meta_data` column. + * + * + * The `user_metadata` should be a JSON object that includes user-specific info, such as their first and last name. + * + * Note: When using the GoTrueAdminApi and wanting to modify a user's metadata, + * this attribute is used instead of UserAttributes data. + * + */ + user_metadata?: object; + /** + * A custom data object to store the user's application specific metadata. This maps to the `auth.users.app_metadata` column. + * + * Only a service role can modify. + * + * The `app_metadata` should be a JSON object that includes app-specific info, such as identity providers, roles, and other + * access control information. + */ + app_metadata?: object; + /** + * Confirms the user's email address if set to true. + * + * Only a service role can modify. + */ + email_confirm?: boolean; + /** + * Confirms the user's phone number if set to true. + * + * Only a service role can modify. + */ + phone_confirm?: boolean; + /** + * Determines how long a user is banned for. + * + * The format for the ban duration follows a strict sequence of decimal numbers with a unit suffix. + * Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h". + * + * For example, some possible durations include: '300ms', '2h45m'. + * + * Setting the ban duration to 'none' lifts the ban on the user. + */ + ban_duration?: string | 'none'; + /** + * The `role` claim set in the user's access token JWT. + * + * When a user signs up, this role is set to `authenticated` by default. You should only modify the `role` if you need to provision several levels of admin access that have different permissions on individual columns in your database. + * + * Setting this role to `service_role` is not recommended as it grants the user admin privileges. + */ + role?: string; + /** + * The `password_hash` for the user's password. + * + * Allows you to specify a password hash for the user. This is useful for migrating a user's password hash from another service. + * + * Supports bcrypt, scrypt (firebase), and argon2 password hashes. + */ + password_hash?: string; + /** + * The `id` for the user. + * + * Allows you to overwrite the default `id` set for the user. + */ + id?: string; +} +export interface Subscription { + /** + * A unique identifier for this subscription, set by the client. + * This is an internal identifier used for managing callbacks and should not be + * relied upon by application code. Use the unsubscribe() method to remove listeners. + */ + id: string | symbol; + /** + * The function to call every time there is an event. eg: (eventName) => {} + */ + callback: (event: AuthChangeEvent, session: Session | null) => void; + /** + * Call this to remove the listener. + */ + unsubscribe: () => void; +} +export type SignInAnonymouslyCredentials = { + options?: { + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.raw_user_meta_data` column. + * + * The `data` should be a JSON object that includes user-specific info, such as their first and last name. + */ + data?: object; + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + }; +}; +export type SignUpWithPasswordCredentials = Prettify; +type PasswordCredentialsBase = { + email: string; + password: string; +} | { + phone: string; + password: string; +}; +export type SignInWithPasswordCredentials = PasswordCredentialsBase & { + options?: { + captchaToken?: string; + }; +}; +export type SignInWithPasswordlessCredentials = { + /** The user's email address. */ + email: string; + options?: { + /** The redirect url embedded in the email link */ + emailRedirectTo?: string; + /** If set to false, this method will not create a new user. Defaults to true. */ + shouldCreateUser?: boolean; + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.raw_user_meta_data` column. + * + * The `data` should be a JSON object that includes user-specific info, such as their first and last name. + */ + data?: object; + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + }; +} | { + /** The user's phone number. */ + phone: string; + options?: { + /** If set to false, this method will not create a new user. Defaults to true. */ + shouldCreateUser?: boolean; + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.raw_user_meta_data` column. + * + * The `data` should be a JSON object that includes user-specific info, such as their first and last name. + */ + data?: object; + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + /** Messaging channel to use (e.g. whatsapp or sms) */ + channel?: 'sms' | 'whatsapp'; + }; +}; +export type AuthFlowType = 'implicit' | 'pkce'; +export type SignInWithOAuthCredentials = { + /** One of the providers supported by GoTrue. */ + provider: Provider; + options?: { + /** A URL to send the user to after they are confirmed. */ + redirectTo?: string; + /** A space-separated list of scopes granted to the OAuth application. */ + scopes?: string; + /** An object of query params */ + queryParams?: { + [key: string]: string; + }; + /** If set to true does not immediately redirect the current browser context to visit the OAuth authorization page for the provider. */ + skipBrowserRedirect?: boolean; + }; +}; +export type SignInWithIdTokenCredentials = { + /** Provider name or OIDC `iss` value identifying which provider should be used to verify the provided token. Supported names: `google`, `apple`, `azure`, `facebook`, `kakao`, `keycloak` (deprecated). */ + provider: 'google' | 'apple' | 'azure' | 'facebook' | 'kakao' | (string & {}); + /** OIDC ID token issued by the specified provider. The `iss` claim in the ID token must match the supplied provider. Some ID tokens contain an `at_hash` which require that you provide an `access_token` value to be accepted properly. If the token contains a `nonce` claim you must supply the nonce used to obtain the ID token. */ + token: string; + /** If the ID token contains an `at_hash` claim, then the hash of this value is compared to the value in the ID token. */ + access_token?: string; + /** If the ID token contains a `nonce` claim, then the hash of this value is compared to the value in the ID token. */ + nonce?: string; + options?: { + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + }; +}; +export type SolanaWallet = { + signIn?: (...inputs: SolanaSignInInput[]) => Promise; + publicKey?: { + toBase58: () => string; + } | null; + signMessage?: (message: Uint8Array, encoding?: 'utf8' | string) => Promise | undefined; +}; +export type SolanaWeb3Credentials = { + chain: 'solana'; + /** Wallet interface to use. If not specified will default to `window.solana`. */ + wallet?: SolanaWallet; + /** Optional statement to include in the Sign in with Solana message. Must not include new line characters. Most wallets like Phantom **require specifying a statement!** */ + statement?: string; + options?: { + /** URL to use with the wallet interface. Some wallets do not allow signing a message for URLs different from the current page. */ + url?: string; + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + signInWithSolana?: Partial>; + }; +} | { + chain: 'solana'; + /** Sign in with Solana compatible message. Must include `Issued At`, `URI` and `Version`. */ + message: string; + /** Ed25519 signature of the message. */ + signature: Uint8Array; + options?: { + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + }; +}; +export type EthereumWallet = EIP1193Provider; +export type EthereumWeb3Credentials = { + chain: 'ethereum'; + /** Wallet interface to use. If not specified will default to `window.ethereum`. */ + wallet?: EthereumWallet; + /** Optional statement to include in the Sign in with Ethereum message. Must not include new line characters. Most wallets like Phantom **require specifying a statement!** */ + statement?: string; + options?: { + /** URL to use with the wallet interface. Some wallets do not allow signing a message for URLs different from the current page. */ + url?: string; + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + signInWithEthereum?: Partial>; + }; +} | { + chain: 'ethereum'; + /** Sign in with Ethereum compatible message. Must include `Issued At`, `URI` and `Version`. */ + message: string; + /** Ethereum curve (secp256k1) signature of the message. */ + signature: Hex; + options?: { + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + }; +}; +export type Web3Credentials = SolanaWeb3Credentials | EthereumWeb3Credentials; +export type VerifyOtpParams = VerifyMobileOtpParams | VerifyEmailOtpParams | VerifyTokenHashParams; +export interface VerifyMobileOtpParams { + /** The user's phone number. */ + phone: string; + /** The otp sent to the user's phone number. */ + token: string; + /** The user's verification type. */ + type: MobileOtpType; + options?: { + /** A URL to send the user to after they are confirmed. */ + redirectTo?: string; + /** + * Verification token received when the user completes the captcha on the site. + * + * @deprecated + */ + captchaToken?: string; + }; +} +export interface VerifyEmailOtpParams { + /** The user's email address. */ + email: string; + /** The otp sent to the user's email address. */ + token: string; + /** The user's verification type. */ + type: EmailOtpType; + options?: { + /** A URL to send the user to after they are confirmed. */ + redirectTo?: string; + /** Verification token received when the user completes the captcha on the site. + * + * @deprecated + */ + captchaToken?: string; + }; +} +export interface VerifyTokenHashParams { + /** The token hash used in an email link */ + token_hash: string; + /** The user's verification type. */ + type: EmailOtpType; +} +export type MobileOtpType = 'sms' | 'phone_change'; +export type EmailOtpType = 'signup' | 'invite' | 'magiclink' | 'recovery' | 'email_change' | 'email'; +export type ResendParams = { + type: Extract; + email: string; + options?: { + /** A URL to send the user to after they have signed-in. */ + emailRedirectTo?: string; + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + }; +} | { + type: Extract; + phone: string; + options?: { + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + }; +}; +export type SignInWithSSO = { + /** UUID of the SSO provider to invoke single-sign on to. */ + providerId: string; + options?: { + /** A URL to send the user to after they have signed-in. */ + redirectTo?: string; + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + /** + * If set to true, the redirect will not happen on the client side. + * This parameter is used when you wish to handle the redirect yourself. + * Defaults to false. + */ + skipBrowserRedirect?: boolean; + }; +} | { + /** Domain name of the organization for which to invoke single-sign on. */ + domain: string; + options?: { + /** A URL to send the user to after they have signed-in. */ + redirectTo?: string; + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + /** + * If set to true, the redirect will not happen on the client side. + * This parameter is used when you wish to handle the redirect yourself. + * Defaults to false. + */ + skipBrowserRedirect?: boolean; + }; +}; +export type GenerateSignupLinkParams = { + type: 'signup'; + email: string; + password: string; + options?: Pick; +}; +export type GenerateInviteOrMagiclinkParams = { + type: 'invite' | 'magiclink'; + /** The user's email */ + email: string; + options?: Pick; +}; +export type GenerateRecoveryLinkParams = { + type: 'recovery'; + /** The user's email */ + email: string; + options?: Pick; +}; +export type GenerateEmailChangeLinkParams = { + type: 'email_change_current' | 'email_change_new'; + /** The user's email */ + email: string; + /** + * The user's new email. Only required if type is 'email_change_current' or 'email_change_new'. + */ + newEmail: string; + options?: Pick; +}; +export interface GenerateLinkOptions { + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.raw_user_meta_data` column. + * + * The `data` should be a JSON object that includes user-specific info, such as their first and last name. + */ + data?: object; + /** The URL which will be appended to the email link generated. */ + redirectTo?: string; +} +export type GenerateLinkParams = GenerateSignupLinkParams | GenerateInviteOrMagiclinkParams | GenerateRecoveryLinkParams | GenerateEmailChangeLinkParams; +export type GenerateLinkResponse = RequestResultSafeDestructure<{ + properties: GenerateLinkProperties; + user: User; +}>; +/** The properties related to the email link generated */ +export type GenerateLinkProperties = { + /** + * The email link to send to the user. + * The action_link follows the following format: auth/v1/verify?type={verification_type}&token={hashed_token}&redirect_to={redirect_to} + * */ + action_link: string; + /** + * The raw email OTP. + * You should send this in the email if you want your users to verify using an OTP instead of the action link. + * */ + email_otp: string; + /** + * The hashed token appended to the action link. + * */ + hashed_token: string; + /** The URL appended to the action link. */ + redirect_to: string; + /** The verification type that the email link is associated to. */ + verification_type: GenerateLinkType; +}; +export type GenerateLinkType = 'signup' | 'invite' | 'magiclink' | 'recovery' | 'email_change_current' | 'email_change_new'; +export type MFAEnrollParams = MFAEnrollTOTPParams | MFAEnrollPhoneParams | MFAEnrollWebauthnParams; +export type MFAUnenrollParams = { + /** ID of the factor being unenrolled. */ + factorId: string; +}; +type MFAVerifyParamsBase = { + /** ID of the factor being verified. Returned in enroll(). */ + factorId: string; + /** ID of the challenge being verified. Returned in challenge(). */ + challengeId: string; +}; +type MFAVerifyTOTPParamFields = { + /** Verification code provided by the user. */ + code: string; +}; +export type MFAVerifyTOTPParams = Prettify; +type MFAVerifyPhoneParamFields = MFAVerifyTOTPParamFields; +export type MFAVerifyPhoneParams = Prettify; +type MFAVerifyWebauthnParamFieldsBase = { + /** Relying party ID */ + rpId: string; + /** Relying party origins */ + rpOrigins?: string[]; +}; +type MFAVerifyWebauthnCredentialParamFields = { + /** Operation type */ + type: T; + /** Creation response from the authenticator (for enrollment/unverified factors) */ + credential_response: T extends 'create' ? RegistrationCredential : AuthenticationCredential; +}; +/** + * WebAuthn-specific fields for MFA verification. + * Supports both credential creation (registration) and request (authentication) flows. + * @template T - Type of WebAuthn operation: 'create' for registration, 'request' for authentication + */ +export type MFAVerifyWebauthnParamFields = { + webauthn: MFAVerifyWebauthnParamFieldsBase & MFAVerifyWebauthnCredentialParamFields; +}; +/** + * Parameters for WebAuthn MFA verification. + * Used to verify WebAuthn credentials after challenge. + * @template T - Type of WebAuthn operation: 'create' for registration, 'request' for authentication + * @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying an Authentication Assertion} + */ +export type MFAVerifyWebauthnParams = Prettify>; +export type MFAVerifyParams = MFAVerifyTOTPParams | MFAVerifyPhoneParams | MFAVerifyWebauthnParams; +type MFAChallengeParamsBase = { + /** ID of the factor to be challenged. Returned in enroll(). */ + factorId: string; +}; +declare const MFATOTPChannels: readonly ["sms", "whatsapp"]; +export type MFATOTPChannel = (typeof MFATOTPChannels)[number]; +export type MFAChallengeTOTPParams = Prettify; +type MFAChallengePhoneParamFields = { + /** Messaging channel to use (e.g. whatsapp or sms). Only relevant for phone factors */ + channel: Channel; +}; +export type MFAChallengePhoneParams = Prettify; +/** WebAuthn parameters for WebAuthn factor challenge */ +type MFAChallengeWebauthnParamFields = { + webauthn: { + /** Relying party ID */ + rpId: string; + /** Relying party origins*/ + rpOrigins?: string[]; + }; +}; +/** + * Parameters for initiating a WebAuthn MFA challenge. + * Includes Relying Party information needed for WebAuthn ceremonies. + * @see {@link https://w3c.github.io/webauthn/#sctn-rp-operations W3C WebAuthn Spec - Relying Party Operations} + */ +export type MFAChallengeWebauthnParams = Prettify; +export type MFAChallengeParams = MFAChallengeTOTPParams | MFAChallengePhoneParams | MFAChallengeWebauthnParams; +type MFAChallengeAndVerifyParamsBase = Omit; +type MFAChallengeAndVerifyTOTPParamFields = MFAVerifyTOTPParamFields; +type MFAChallengeAndVerifyTOTPParams = Prettify; +export type MFAChallengeAndVerifyParams = MFAChallengeAndVerifyTOTPParams; +/** + * Data returned after successful MFA verification. + * Contains new session tokens and updated user information. + */ +export type AuthMFAVerifyResponseData = { + /** New access token (JWT) after successful verification. */ + access_token: string; + /** Type of token, always `bearer`. */ + token_type: 'bearer'; + /** Number of seconds in which the access token will expire. */ + expires_in: number; + /** Refresh token you can use to obtain new access tokens when expired. */ + refresh_token: string; + /** Updated user profile. */ + user: User; +}; +/** + * Response type for MFA verification operations. + * Returns session tokens on successful verification. + */ +export type AuthMFAVerifyResponse = RequestResult; +export type AuthMFAEnrollResponse = AuthMFAEnrollTOTPResponse | AuthMFAEnrollPhoneResponse | AuthMFAEnrollWebauthnResponse; +export type AuthMFAUnenrollResponse = RequestResult<{ + /** ID of the factor that was successfully unenrolled. */ + id: string; +}>; +type AuthMFAChallengeResponseBase = { + /** ID of the newly created challenge. */ + id: string; + /** Factor Type which generated the challenge */ + type: T; + /** Timestamp in UNIX seconds when this challenge will no longer be usable. */ + expires_at: number; +}; +type AuthMFAChallengeTOTPResponseFields = {}; +export type AuthMFAChallengeTOTPResponse = RequestResult & AuthMFAChallengeTOTPResponseFields>>; +type AuthMFAChallengePhoneResponseFields = {}; +export type AuthMFAChallengePhoneResponse = RequestResult & AuthMFAChallengePhoneResponseFields>>; +type AuthMFAChallengeWebauthnResponseFields = { + webauthn: { + type: 'create'; + credential_options: { + publicKey: PublicKeyCredentialCreationOptionsFuture; + }; + } | { + type: 'request'; + credential_options: { + publicKey: PublicKeyCredentialRequestOptionsFuture; + }; + }; +}; +/** + * Response type for WebAuthn MFA challenge. + * Contains credential creation or request options from the server. + * @see {@link https://w3c.github.io/webauthn/#sctn-credential-creation W3C WebAuthn Spec - Credential Creation} + */ +export type AuthMFAChallengeWebauthnResponse = RequestResult & AuthMFAChallengeWebauthnResponseFields>>; +type AuthMFAChallengeWebauthnResponseFieldsJSON = { + webauthn: { + type: 'create'; + credential_options: { + publicKey: ServerCredentialCreationOptions; + }; + } | { + type: 'request'; + credential_options: { + publicKey: ServerCredentialRequestOptions; + }; + }; +}; +/** + * JSON-serializable version of WebAuthn challenge response. + * Used for server communication with base64url-encoded binary fields. + */ +export type AuthMFAChallengeWebauthnResponseDataJSON = Prettify & AuthMFAChallengeWebauthnResponseFieldsJSON>; +/** + * Server response type for WebAuthn MFA challenge. + * Contains JSON-formatted WebAuthn options ready for browser API. + */ +export type AuthMFAChallengeWebauthnServerResponse = RequestResult; +export type AuthMFAChallengeResponse = AuthMFAChallengeTOTPResponse | AuthMFAChallengePhoneResponse | AuthMFAChallengeWebauthnResponse; +/** response of ListFactors, which should contain all the types of factors that are available, this ensures we always include all */ +export type AuthMFAListFactorsResponse = RequestResult<{ + /** All available factors (verified and unverified). */ + all: Prettify[]; +} & { + [K in T[number]]: Prettify>[]; +}>; +export type AuthenticatorAssuranceLevels = 'aal1' | 'aal2'; +export type AuthMFAGetAuthenticatorAssuranceLevelResponse = RequestResult<{ + /** Current AAL level of the session. */ + currentLevel: AuthenticatorAssuranceLevels | null; + /** + * Next possible AAL level for the session. If the next level is higher + * than the current one, the user should go through MFA. + * + * @see {@link GoTrueMFAApi#challenge} + */ + nextLevel: AuthenticatorAssuranceLevels | null; + /** + * A list of all authentication methods attached to this session. Use + * the information here to detect the last time a user verified a + * factor, for example if implementing a step-up scenario. + */ + currentAuthenticationMethods: AMREntry[]; +}>; +/** + * Contains the full multi-factor authentication API. + * + */ +export interface GoTrueMFAApi { + /** + * Starts the enrollment process for a new Multi-Factor Authentication (MFA) + * factor. This method creates a new `unverified` factor. + * To verify a factor, present the QR code or secret to the user and ask them to add it to their + * authenticator app. + * The user has to enter the code from their authenticator app to verify it. + * + * Upon verifying a factor, all other sessions are logged out and the current session's authenticator level is promoted to `aal2`. + */ + enroll(params: MFAEnrollTOTPParams): Promise; + enroll(params: MFAEnrollPhoneParams): Promise; + enroll(params: MFAEnrollWebauthnParams): Promise; + enroll(params: MFAEnrollParams): Promise; + /** + * Prepares a challenge used to verify that a user has access to a MFA + * factor. + */ + challenge(params: MFAChallengeTOTPParams): Promise>; + challenge(params: MFAChallengePhoneParams): Promise>; + challenge(params: MFAChallengeWebauthnParams): Promise>; + challenge(params: MFAChallengeParams): Promise; + /** + * Verifies a code against a challenge. The verification code is + * provided by the user by entering a code seen in their authenticator app. + */ + verify(params: MFAVerifyTOTPParams): Promise; + verify(params: MFAVerifyPhoneParams): Promise; + verify(params: MFAVerifyWebauthnParams): Promise; + verify(params: MFAVerifyParams): Promise; + /** + * Unenroll removes a MFA factor. + * A user has to have an `aal2` authenticator level in order to unenroll a `verified` factor. + */ + unenroll(params: MFAUnenrollParams): Promise; + /** + * Helper method which creates a challenge and immediately uses the given code to verify against it thereafter. The verification code is + * provided by the user by entering a code seen in their authenticator app. + */ + challengeAndVerify(params: MFAChallengeAndVerifyParams): Promise; + /** + * Returns the list of MFA factors enabled for this user. + * + * @see {@link GoTrueMFAApi#enroll} + * @see {@link GoTrueMFAApi#getAuthenticatorAssuranceLevel} + * @see {@link GoTrueClient#getUser} + * + */ + listFactors(): Promise; + /** + * Returns the Authenticator Assurance Level (AAL) for the active session. + * + * - `aal1` (or `null`) means that the user's identity has been verified only + * with a conventional login (email+password, OTP, magic link, social login, + * etc.). + * - `aal2` means that the user's identity has been verified both with a conventional login and at least one MFA factor. + * + * Although this method returns a promise, it's fairly quick (microseconds) + * and rarely uses the network. You can use this to check whether the current + * user needs to be shown a screen to verify their MFA factors. + * + */ + getAuthenticatorAssuranceLevel(): Promise; + webauthn: WebAuthnApi; +} +/** + * @expermental + */ +export type AuthMFAAdminDeleteFactorResponse = RequestResult<{ + /** ID of the factor that was successfully deleted. */ + id: string; +}>; +/** + * @expermental + */ +export type AuthMFAAdminDeleteFactorParams = { + /** ID of the MFA factor to delete. */ + id: string; + /** ID of the user whose factor is being deleted. */ + userId: string; +}; +/** + * @expermental + */ +export type AuthMFAAdminListFactorsResponse = RequestResult<{ + /** All factors attached to the user. */ + factors: Factor[]; +}>; +/** + * @expermental + */ +export type AuthMFAAdminListFactorsParams = { + /** ID of the user. */ + userId: string; +}; +/** + * Contains the full multi-factor authentication administration API. + * + * @expermental + */ +export interface GoTrueAdminMFAApi { + /** + * Lists all factors associated to a user. + * + */ + listFactors(params: AuthMFAAdminListFactorsParams): Promise; + /** + * Deletes a factor on a user. This will log the user out of all active + * sessions if the deleted factor was verified. + * + * @see {@link GoTrueMFAApi#unenroll} + * + * @expermental + */ + deleteFactor(params: AuthMFAAdminDeleteFactorParams): Promise; +} +type AnyFunction = (...args: any[]) => any; +type MaybePromisify = T | Promise; +type PromisifyMethods = { + [K in keyof T]: T[K] extends AnyFunction ? (...args: Parameters) => MaybePromisify> : T[K]; +}; +export type SupportedStorage = PromisifyMethods> & { + /** + * If set to `true` signals to the library that the storage medium is used + * on a server and the values may not be authentic, such as reading from + * request cookies. Implementations should not set this to true if the client + * is used on a server that reads storage information from authenticated + * sources, such as a secure database or file. + */ + isServer?: boolean; +}; +export type InitializeResult = { + error: AuthError | null; +}; +export type CallRefreshTokenResult = RequestResult; +export type Pagination = { + [key: string]: any; + nextPage: number | null; + lastPage: number; + total: number; +}; +export type PageParams = { + /** The page number */ + page?: number; + /** Number of items returned per page */ + perPage?: number; +}; +export type SignOut = { + /** + * Determines which sessions should be + * logged out. Global means all + * sessions by this account. Local + * means only this session. Others + * means all other sessions except the + * current one. When using others, + * there is no sign-out event fired on + * the current session! + */ + scope?: 'global' | 'local' | 'others'; +}; +type MFAEnrollParamsBase = { + /** The type of factor being enrolled. */ + factorType: T; + /** Human readable name assigned to the factor. */ + friendlyName?: string; +}; +type MFAEnrollTOTPParamFields = { + /** Domain which the user is enrolled with. */ + issuer?: string; +}; +export type MFAEnrollTOTPParams = Prettify & MFAEnrollTOTPParamFields>; +type MFAEnrollPhoneParamFields = { + /** Phone number associated with a factor. Number should conform to E.164 format */ + phone: string; +}; +export type MFAEnrollPhoneParams = Prettify & MFAEnrollPhoneParamFields>; +type MFAEnrollWebauthnFields = {}; +/** + * Parameters for enrolling a WebAuthn factor. + * Creates an unverified WebAuthn factor that must be verified with a credential. + * @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registering a New Credential} + */ +export type MFAEnrollWebauthnParams = Prettify & MFAEnrollWebauthnFields>; +type AuthMFAEnrollResponseBase = { + /** ID of the factor that was just enrolled (in an unverified state). */ + id: string; + /** Type of MFA factor.*/ + type: T; + /** Friendly name of the factor, useful for distinguishing between factors **/ + friendly_name?: string; +}; +type AuthMFAEnrollTOTPResponseFields = { + /** TOTP enrollment information. */ + totp: { + /** Contains a QR code encoding the authenticator URI. You can + * convert it to a URL by prepending `data:image/svg+xml;utf-8,` to + * the value. Avoid logging this value to the console. */ + qr_code: string; + /** The TOTP secret (also encoded in the QR code). Show this secret + * in a password-style field to the user, in case they are unable to + * scan the QR code. Avoid logging this value to the console. */ + secret: string; + /** The authenticator URI encoded within the QR code, should you need + * to use it. Avoid loggin this value to the console. */ + uri: string; + }; +}; +export type AuthMFAEnrollTOTPResponse = RequestResult & AuthMFAEnrollTOTPResponseFields>>; +type AuthMFAEnrollPhoneResponseFields = { + /** Phone number of the MFA factor in E.164 format. Used to send messages */ + phone: string; +}; +export type AuthMFAEnrollPhoneResponse = RequestResult & AuthMFAEnrollPhoneResponseFields>>; +type AuthMFAEnrollWebauthnFields = {}; +/** + * Response type for WebAuthn factor enrollment. + * Returns the enrolled factor ID and metadata. + * @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registering a New Credential} + */ +export type AuthMFAEnrollWebauthnResponse = RequestResult & AuthMFAEnrollWebauthnFields>>; +export type JwtHeader = { + alg: 'RS256' | 'ES256' | 'HS256'; + kid: string; + typ: string; +}; +export type RequiredClaims = { + iss: string; + sub: string; + aud: string | string[]; + exp: number; + iat: number; + role: string; + aal: AuthenticatorAssuranceLevels; + session_id: string; +}; +/** + * JWT Payload containing claims for Supabase authentication tokens. + * + * Required claims (iss, aud, exp, iat, sub, role, aal, session_id) are inherited from RequiredClaims. + * All other claims are optional as they can be customized via Custom Access Token Hooks. + * + * @see https://supabase.com/docs/guides/auth/jwt-fields + */ +export interface JwtPayload extends RequiredClaims { + email?: string; + phone?: string; + is_anonymous?: boolean; + jti?: string; + nbf?: number; + app_metadata?: UserAppMetadata; + user_metadata?: UserMetadata; + amr?: AMREntry[]; + ref?: string; + [key: string]: any; +} +export interface JWK { + kty: 'RSA' | 'EC' | 'oct'; + key_ops: string[]; + alg?: string; + kid?: string; + [key: string]: any; +} +export declare const SIGN_OUT_SCOPES: readonly ["global", "local", "others"]; +export type SignOutScope = (typeof SIGN_OUT_SCOPES)[number]; +/** + * OAuth client grant types supported by the OAuth 2.1 server. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type OAuthClientGrantType = 'authorization_code' | 'refresh_token'; +/** + * OAuth client response types supported by the OAuth 2.1 server. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type OAuthClientResponseType = 'code'; +/** + * OAuth client type indicating whether the client can keep credentials confidential. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type OAuthClientType = 'public' | 'confidential'; +/** + * OAuth client registration type. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type OAuthClientRegistrationType = 'dynamic' | 'manual'; +/** + * OAuth client object returned from the OAuth 2.1 server. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type OAuthClient = { + /** Unique identifier for the OAuth client */ + client_id: string; + /** Human-readable name of the OAuth client */ + client_name: string; + /** Client secret (only returned on registration and regeneration) */ + client_secret?: string; + /** Type of OAuth client */ + client_type: OAuthClientType; + /** Token endpoint authentication method */ + token_endpoint_auth_method: string; + /** Registration type of the client */ + registration_type: OAuthClientRegistrationType; + /** URI of the OAuth client */ + client_uri?: string; + /** URI of the OAuth client's logo */ + logo_uri?: string; + /** Array of allowed redirect URIs */ + redirect_uris: string[]; + /** Array of allowed grant types */ + grant_types: OAuthClientGrantType[]; + /** Array of allowed response types */ + response_types: OAuthClientResponseType[]; + /** Scope of the OAuth client */ + scope?: string; + /** Timestamp when the client was created */ + created_at: string; + /** Timestamp when the client was last updated */ + updated_at: string; +}; +/** + * Parameters for creating a new OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type CreateOAuthClientParams = { + /** Human-readable name of the OAuth client */ + client_name: string; + /** URI of the OAuth client */ + client_uri?: string; + /** Array of allowed redirect URIs */ + redirect_uris: string[]; + /** Array of allowed grant types (optional, defaults to authorization_code and refresh_token) */ + grant_types?: OAuthClientGrantType[]; + /** Array of allowed response types (optional, defaults to code) */ + response_types?: OAuthClientResponseType[]; + /** Scope of the OAuth client */ + scope?: string; +}; +/** + * Parameters for updating an existing OAuth client. + * All fields are optional. Only provided fields will be updated. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type UpdateOAuthClientParams = { + /** Human-readable name of the OAuth client */ + client_name?: string; + /** URI of the OAuth client */ + client_uri?: string; + /** URI of the OAuth client's logo */ + logo_uri?: string; + /** Array of allowed redirect URIs */ + redirect_uris?: string[]; + /** Array of allowed grant types */ + grant_types?: OAuthClientGrantType[]; +}; +/** + * Response type for OAuth client operations. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type OAuthClientResponse = RequestResult; +/** + * Response type for listing OAuth clients. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type OAuthClientListResponse = { + data: { + clients: OAuthClient[]; + aud: string; + } & Pagination; + error: null; +} | { + data: { + clients: []; + }; + error: AuthError; +}; +/** + * Contains all OAuth client administration methods. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export interface GoTrueAdminOAuthApi { + /** + * Lists all OAuth clients with optional pagination. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + listClients(params?: PageParams): Promise; + /** + * Creates a new OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + createClient(params: CreateOAuthClientParams): Promise; + /** + * Gets details of a specific OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + getClient(clientId: string): Promise; + /** + * Updates an existing OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + updateClient(clientId: string, params: UpdateOAuthClientParams): Promise; + /** + * Deletes an OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + deleteClient(clientId: string): Promise<{ + data: null; + error: AuthError | null; + }>; + /** + * Regenerates the secret for an OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + regenerateClientSecret(clientId: string): Promise; +} +/** + * OAuth client details in an authorization request. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type OAuthAuthorizationClient = { + /** Unique identifier for the OAuth client (UUID) */ + id: string; + /** Human-readable name of the OAuth client */ + name: string; + /** URI of the OAuth client's website */ + uri: string; + /** URI of the OAuth client's logo */ + logo_uri: string; +}; +/** + * OAuth authorization details for the consent flow. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type OAuthAuthorizationDetails = { + /** The authorization ID */ + authorization_id: string; + /** Redirect URL - present if user already consented (can be used to trigger immediate redirect) */ + redirect_url?: string; + /** OAuth client requesting authorization */ + client: OAuthAuthorizationClient; + /** User object associated with the authorization */ + user: { + /** User ID (UUID) */ + id: string; + /** User email */ + email: string; + }; + /** Space-separated list of requested scopes */ + scope: string; +}; +/** + * Response type for getting OAuth authorization details. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type AuthOAuthAuthorizationDetailsResponse = RequestResult; +/** + * Response type for OAuth consent decision (approve/deny). + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type AuthOAuthConsentResponse = RequestResult<{ + /** URL to redirect the user back to the OAuth client */ + redirect_url: string; +}>; +/** + * An OAuth grant representing a user's authorization of an OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type OAuthGrant = { + /** OAuth client information */ + client: OAuthAuthorizationClient; + /** Array of scopes granted to this client */ + scopes: string[]; + /** Timestamp when the grant was created (ISO 8601 date-time) */ + granted_at: string; +}; +/** + * Response type for listing user's OAuth grants. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type AuthOAuthGrantsResponse = RequestResult; +/** + * Response type for revoking an OAuth grant. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type AuthOAuthRevokeGrantResponse = RequestResult<{}>; +/** + * Contains all OAuth 2.1 authorization server user-facing methods. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * These methods are used to implement the consent page. + */ +export interface AuthOAuthServerApi { + /** + * Retrieves details about an OAuth authorization request. + * Used to display consent information to the user. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This method returns authorization details including client info, scopes, and user information. + * If the response includes a redirect_uri, it means consent was already given - the caller + * should handle the redirect manually if needed. + * + * @param authorizationId - The authorization ID from the authorization request + * @returns Authorization details including client info and requested scopes + */ + getAuthorizationDetails(authorizationId: string): Promise; + /** + * Approves an OAuth authorization request. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * @param authorizationId - The authorization ID to approve + * @param options - Optional parameters including skipBrowserRedirect + * @returns Redirect URL to send the user back to the OAuth client + */ + approveAuthorization(authorizationId: string, options?: { + skipBrowserRedirect?: boolean; + }): Promise; + /** + * Denies an OAuth authorization request. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * @param authorizationId - The authorization ID to deny + * @param options - Optional parameters including skipBrowserRedirect + * @returns Redirect URL to send the user back to the OAuth client + */ + denyAuthorization(authorizationId: string, options?: { + skipBrowserRedirect?: boolean; + }): Promise; + /** + * Lists all OAuth grants that the authenticated user has authorized. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * @returns Response with array of OAuth grants with client information and granted scopes + */ + listGrants(): Promise; + /** + * Revokes a user's OAuth grant for a specific client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * Revocation marks consent as revoked, deletes active sessions for that OAuth client, + * and invalidates associated refresh tokens. + * + * @param options - Revocation options + * @param options.clientId - The OAuth client identifier (UUID) to revoke access for + * @returns Empty response on successful revocation + */ + revokeGrant(options: { + clientId: string; + }): Promise; +} +export {}; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/types.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/module/lib/types.d.ts.map new file mode 100644 index 0000000..ba89c28 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/lib/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAA;AACpC,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAC/B,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAA;AAC3E,OAAO,KAAK,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAA;AAC1E,OAAO,EACL,+BAA+B,EAC/B,8BAA8B,EAC9B,WAAW,EACZ,MAAM,YAAY,CAAA;AACnB,OAAO,EACL,wBAAwB,EACxB,wCAAwC,EACxC,uCAAuC,EACvC,sBAAsB,EACvB,MAAM,gBAAgB,CAAA;AAEvB,gDAAgD;AAChD,MAAM,MAAM,QAAQ,GAChB,OAAO,GACP,OAAO,GACP,WAAW,GACX,SAAS,GACT,UAAU,GACV,OAAO,GACP,QAAQ,GACR,QAAQ,GACR,QAAQ,GACR,OAAO,GACP,UAAU,GACV,UAAU,GACV,eAAe,GACf,QAAQ,GACR,OAAO,GACP,YAAY,GACZ,SAAS,GACT,QAAQ,GACR,SAAS,GACT,QAAQ,GACR,MAAM,GACN,KAAK,CAAA;AAET,MAAM,MAAM,kBAAkB,GAAG,wBAAwB,CAAA;AAEzD,MAAM,MAAM,eAAe,GACvB,iBAAiB,GACjB,mBAAmB,GACnB,WAAW,GACX,YAAY,GACZ,iBAAiB,GACjB,cAAc,GACd,kBAAkB,CAAA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;QAAE,QAAQ,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,4BAA4B,CAAC,CAAA;CAClF"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/types.js b/backend/node_modules/@supabase/auth-js/dist/module/lib/types.js new file mode 100644 index 0000000..89050b2 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/types.js @@ -0,0 +1,19 @@ +const WeakPasswordReasons = ['length', 'characters', 'pwned']; +const AMRMethods = [ + 'password', + 'otp', + 'oauth', + 'totp', + 'mfa/totp', + 'mfa/phone', + 'mfa/webauthn', + 'anonymous', + 'sso/saml', + 'magiclink', + 'web3', +]; +const FactorTypes = ['totp', 'phone', 'webauthn']; +const FactorVerificationStatuses = ['verified', 'unverified']; +const MFATOTPChannels = ['sms', 'whatsapp']; +export const SIGN_OUT_SCOPES = ['global', 'local', 'others']; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/types.js.map b/backend/node_modules/@supabase/auth-js/dist/module/lib/types.js.map new file mode 100644 index 0000000..1e6a1ad --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/lib/types.ts"],"names":[],"mappings":"AAoHA,MAAM,mBAAmB,GAAG,CAAC,QAAQ,EAAE,YAAY,EAAE,OAAO,CAAU,CAAA;AA+ItE,MAAM,UAAU,GAAG;IACjB,UAAU;IACV,KAAK;IACL,OAAO;IACP,MAAM;IACN,UAAU;IACV,WAAW;IACX,cAAc;IACd,WAAW;IACX,UAAU;IACV,WAAW;IACX,MAAM;CACE,CAAA;AAoCV,MAAM,WAAW,GAAG,CAAC,MAAM,EAAE,OAAO,EAAE,UAAU,CAAU,CAAA;AAO1D,MAAM,0BAA0B,GAAG,CAAC,UAAU,EAAE,YAAY,CAAU,CAAA;AA2oBtE,MAAM,eAAe,GAAG,CAAC,KAAK,EAAE,UAAU,CAAU,CAAA;AAqhBpD,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,QAAQ,EAAE,OAAO,EAAE,QAAQ,CAAU,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/version.d.ts b/backend/node_modules/@supabase/auth-js/dist/module/lib/version.d.ts new file mode 100644 index 0000000..da11aac --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/version.d.ts @@ -0,0 +1,2 @@ +export declare const version = "2.87.1"; +//# sourceMappingURL=version.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/version.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/module/lib/version.d.ts.map new file mode 100644 index 0000000..a4c2b72 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/version.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,OAAO,WAAW,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/version.js b/backend/node_modules/@supabase/auth-js/dist/module/lib/version.js new file mode 100644 index 0000000..8a1c0bd --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/version.js @@ -0,0 +1,8 @@ +// Generated automatically during releases by scripts/update-version-files.ts +// This file provides runtime access to the package version for: +// - HTTP request headers (e.g., X-Client-Info header for API requests) +// - Debugging and support (identifying which version is running) +// - Telemetry and logging (version reporting in errors/analytics) +// - Ensuring build artifacts match the published package version +export const version = '2.87.1'; +//# sourceMappingURL=version.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/version.js.map b/backend/node_modules/@supabase/auth-js/dist/module/lib/version.js.map new file mode 100644 index 0000000..b571c4f --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/version.js.map @@ -0,0 +1 @@ +{"version":3,"file":"version.js","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,gEAAgE;AAChE,uEAAuE;AACvE,iEAAiE;AACjE,kEAAkE;AAClE,iEAAiE;AACjE,MAAM,CAAC,MAAM,OAAO,GAAG,QAAQ,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/web3/ethereum.d.ts b/backend/node_modules/@supabase/auth-js/dist/module/lib/web3/ethereum.d.ts new file mode 100644 index 0000000..71f4b6e --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/web3/ethereum.d.ts @@ -0,0 +1,96 @@ +export type Hex = `0x${string}`; +export type Address = Hex; +export type EIP1193EventMap = { + accountsChanged(accounts: Address[]): void; + chainChanged(chainId: string): void; + connect(connectInfo: { + chainId: string; + }): void; + disconnect(error: { + code: number; + message: string; + }): void; + message(message: { + type: string; + data: unknown; + }): void; +}; +export type EIP1193Events = { + on(event: event, listener: EIP1193EventMap[event]): void; + removeListener(event: event, listener: EIP1193EventMap[event]): void; +}; +export type EIP1193RequestFn = (args: { + method: string; + params?: unknown; +}) => Promise; +export type EIP1193Provider = EIP1193Events & { + address: string; + request: EIP1193RequestFn; +}; +export type EthereumWallet = EIP1193Provider; +/** + * EIP-4361 message fields + */ +export type SiweMessage = { + /** + * The Ethereum address performing the signing. + */ + address: Address; + /** + * The [EIP-155](https://eips.ethereum.org/EIPS/eip-155) Chain ID to which the session is bound, + */ + chainId: number; + /** + * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) authority that is requesting the signing. + */ + domain: string; + /** + * Time when the signed authentication message is no longer valid. + */ + expirationTime?: Date | undefined; + /** + * Time when the message was generated, typically the current time. + */ + issuedAt?: Date | undefined; + /** + * A random string typically chosen by the relying party and used to prevent replay attacks. + */ + nonce?: string; + /** + * Time when the signed authentication message will become valid. + */ + notBefore?: Date | undefined; + /** + * A system-specific identifier that may be used to uniquely refer to the sign-in request. + */ + requestId?: string | undefined; + /** + * A list of information or references to information the user wishes to have resolved as part of authentication by the relying party. + */ + resources?: string[] | undefined; + /** + * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) URI scheme of the origin of the request. + */ + scheme?: string | undefined; + /** + * A human-readable ASCII assertion that the user will sign. + */ + statement?: string | undefined; + /** + * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) URI referring to the resource that is the subject of the signing (as in the subject of a claim). + */ + uri: string; + /** + * The current version of the SIWE Message. + */ + version: '1'; +}; +export type EthereumSignInInput = SiweMessage; +export declare function getAddress(address: string): Address; +export declare function fromHex(hex: Hex): number; +export declare function toHex(value: string): Hex; +/** + * Creates EIP-4361 formatted message. + */ +export declare function createSiweMessage(parameters: SiweMessage): string; +//# sourceMappingURL=ethereum.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/web3/ethereum.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/module/lib/web3/ethereum.d.ts.map new file mode 100644 index 0000000..7b3ac39 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/web3/ethereum.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ethereum.d.ts","sourceRoot":"","sources":["../../../../src/lib/web3/ethereum.ts"],"names":[],"mappings":"AAEA,MAAM,MAAM,GAAG,GAAG,KAAK,MAAM,EAAE,CAAA;AAE/B,MAAM,MAAM,OAAO,GAAG,GAAG,CAAA;AAEzB,MAAM,MAAM,eAAe,GAAG;IAC5B,eAAe,CAAC,QAAQ,EAAE,OAAO,EAAE,GAAG,IAAI,CAAA;IAC1C,YAAY,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAA;IACnC,OAAO,CAAC,WAAW,EAAE;QAAE,OAAO,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAA;IAC/C,UAAU,CAAC,KAAK,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,GAAG,IAA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AS,CAAC,EAAE,MAAM,EAAE,GAAG,SAAS,CAAA;IAChC;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IAC3B;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IAC9B;;OAEG;IACH,GAAG,EAAE,MAAM,CAAA;IACX;;OAEG;IACH,OAAO,EAAE,GAAG,CAAA;CACb,CAAA;AAED,MAAM,MAAM,mBAAmB,GAAG,WAAW,CAAA;AAE7C,wBAAgB,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAKnD;AAED,wBAAgB,OAAO,CAAC,GAAG,EAAE,GAAG,GAAG,MAAM,CAExC;AAED,wBAAgB,KAAK,CAAC,KAAK,EAAE,MAAM,GAAG,GAAG,CAIxC;AAED;;GAEG;AACH,wBAAgB,iBAAiB,CAAC,UAAU,EAAE,WAAW,GAAG,MAAM,CAwEjE"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/web3/ethereum.js b/backend/node_modules/@supabase/auth-js/dist/module/lib/web3/ethereum.js new file mode 100644 index 0000000..24245a4 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/web3/ethereum.js @@ -0,0 +1,60 @@ +// types and functions copied over from viem so this library doesn't depend on it +export function getAddress(address) { + if (!/^0x[a-fA-F0-9]{40}$/.test(address)) { + throw new Error(`@supabase/auth-js: Address "${address}" is invalid.`); + } + return address.toLowerCase(); +} +export function fromHex(hex) { + return parseInt(hex, 16); +} +export function toHex(value) { + const bytes = new TextEncoder().encode(value); + const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join(''); + return ('0x' + hex); +} +/** + * Creates EIP-4361 formatted message. + */ +export function createSiweMessage(parameters) { + var _a; + const { chainId, domain, expirationTime, issuedAt = new Date(), nonce, notBefore, requestId, resources, scheme, uri, version, } = parameters; + // Validate fields + { + if (!Number.isInteger(chainId)) + throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${chainId}`); + if (!domain) + throw new Error(`@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.`); + if (nonce && nonce.length < 8) + throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${nonce}`); + if (!uri) + throw new Error(`@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.`); + if (version !== '1') + throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${version}`); + if ((_a = parameters.statement) === null || _a === void 0 ? void 0 : _a.includes('\n')) + throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${parameters.statement}`); + } + // Construct message + const address = getAddress(parameters.address); + const origin = scheme ? `${scheme}://${domain}` : domain; + const statement = parameters.statement ? `${parameters.statement}\n` : ''; + const prefix = `${origin} wants you to sign in with your Ethereum account:\n${address}\n\n${statement}`; + let suffix = `URI: ${uri}\nVersion: ${version}\nChain ID: ${chainId}${nonce ? `\nNonce: ${nonce}` : ''}\nIssued At: ${issuedAt.toISOString()}`; + if (expirationTime) + suffix += `\nExpiration Time: ${expirationTime.toISOString()}`; + if (notBefore) + suffix += `\nNot Before: ${notBefore.toISOString()}`; + if (requestId) + suffix += `\nRequest ID: ${requestId}`; + if (resources) { + let content = '\nResources:'; + for (const resource of resources) { + if (!resource || typeof resource !== 'string') + throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${resource}`); + content += `\n- ${resource}`; + } + suffix += content; + } + return `${prefix}\n${suffix}`; +} +//# sourceMappingURL=ethereum.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/web3/ethereum.js.map b/backend/node_modules/@supabase/auth-js/dist/module/lib/web3/ethereum.js.map new file mode 100644 index 0000000..264dd9c --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/web3/ethereum.js.map @@ -0,0 +1 @@ +{"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iBAAiB,SAAS,EAAE,CAAA;IACrD,IAAI,SAAS,EAAE,CAAC;QACd,IAAI,OAAO,GAAG,cAAc,CAAA;QAC5B,KAAK,MAAM,QAAQ,IAAI,SAAS,EAAE,CAAC;YACjC,IAAI,CAAC,QAAQ,IAAI,OAAO,QAAQ,KAAK,QAAQ;gBAC3C,MAAM,IAAI,KAAK,CACb,qHAAqH,QAAQ,EAAE,CAChI,CAAA;YACH,OAAO,IAAI,OAAO,QAAQ,EAAE,CAAA;QAC9B,CAAC;QACD,MAAM,IAAI,OAAO,CAAA;IACnB,CAAC;IAED,OAAO,GAAG,MAAM,KAAK,MAAM,EAAE,CAAA;AAC/B,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/web3/solana.d.ts b/backend/node_modules/@supabase/auth-js/dist/module/lib/web3/solana.d.ts new file mode 100644 index 0000000..1fa5b62 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/web3/solana.d.ts @@ -0,0 +1,160 @@ +/** + * A namespaced identifier in the format `${namespace}:${reference}`. + * + * Used by {@link IdentifierArray} and {@link IdentifierRecord}. + * + * @group Identifier + */ +export type IdentifierString = `${string}:${string}`; +/** + * A read-only array of namespaced identifiers in the format `${namespace}:${reference}`. + * + * Used by {@link Wallet.chains | Wallet::chains}, {@link WalletAccount.chains | WalletAccount::chains}, and + * {@link WalletAccount.features | WalletAccount::features}. + * + * @group Identifier + */ +export type IdentifierArray = readonly IdentifierString[]; +/** + * Version of the Wallet Standard implemented by a {@link Wallet}. + * + * Used by {@link Wallet.version | Wallet::version}. + * + * Note that this is _NOT_ a version of the Wallet, but a version of the Wallet Standard itself that the Wallet + * supports. + * + * This may be used by the app to determine compatibility and feature detect. + * + * @group Wallet + */ +export type WalletVersion = '1.0.0'; +/** + * A data URI containing a base64-encoded SVG, WebP, PNG, or GIF image. + * + * Used by {@link Wallet.icon | Wallet::icon} and {@link WalletAccount.icon | WalletAccount::icon}. + * + * @group Wallet + */ +export type WalletIcon = `data:image/${'svg+xml' | 'webp' | 'png' | 'gif'};base64,${string}`; +/** + * Interface of a **WalletAccount**, also referred to as an **Account**. + * + * An account is a _read-only data object_ that is provided from the Wallet to the app, authorizing the app to use it. + * + * The app can use an account to display and query information from a chain. + * + * The app can also act using an account by passing it to {@link Wallet.features | features} of the Wallet. + * + * Wallets may use or extend {@link "@wallet-standard/wallet".ReadonlyWalletAccount} which implements this interface. + * + * @group Wallet + */ +export interface WalletAccount { + /** Address of the account, corresponding with a public key. */ + readonly address: string; + /** Public key of the account, corresponding with a secret key to use. */ + readonly publicKey: Uint8Array; + /** + * Chains supported by the account. + * + * This must be a subset of the {@link Wallet.chains | chains} of the Wallet. + */ + readonly chains: IdentifierArray; + /** + * Feature names supported by the account. + * + * This must be a subset of the names of {@link Wallet.features | features} of the Wallet. + */ + readonly features: IdentifierArray; + /** Optional user-friendly descriptive label or name for the account. This may be displayed by the app. */ + readonly label?: string; + /** Optional user-friendly icon for the account. This may be displayed by the app. */ + readonly icon?: WalletIcon; +} +/** Input for signing in. */ +export interface SolanaSignInInput { + /** + * Optional EIP-4361 Domain. + * If not provided, the wallet must determine the Domain to include in the message. + */ + readonly domain?: string; + /** + * Optional EIP-4361 Address. + * If not provided, the wallet must determine the Address to include in the message. + */ + readonly address?: string; + /** + * Optional EIP-4361 Statement. + * If not provided, the wallet must not include Statement in the message. + */ + readonly statement?: string; + /** + * Optional EIP-4361 URI. + * If not provided, the wallet must not include URI in the message. + */ + readonly uri?: string; + /** + * Optional EIP-4361 Version. + * If not provided, the wallet must not include Version in the message. + */ + readonly version?: string; + /** + * Optional EIP-4361 Chain ID. + * If not provided, the wallet must not include Chain ID in the message. + */ + readonly chainId?: string; + /** + * Optional EIP-4361 Nonce. + * If not provided, the wallet must not include Nonce in the message. + */ + readonly nonce?: string; + /** + * Optional EIP-4361 Issued At. + * If not provided, the wallet must not include Issued At in the message. + */ + readonly issuedAt?: string; + /** + * Optional EIP-4361 Expiration Time. + * If not provided, the wallet must not include Expiration Time in the message. + */ + readonly expirationTime?: string; + /** + * Optional EIP-4361 Not Before. + * If not provided, the wallet must not include Not Before in the message. + */ + readonly notBefore?: string; + /** + * Optional EIP-4361 Request ID. + * If not provided, the wallet must not include Request ID in the message. + */ + readonly requestId?: string; + /** + * Optional EIP-4361 Resources. + * If not provided, the wallet must not include Resources in the message. + */ + readonly resources?: readonly string[]; +} +/** Output of signing in. */ +export interface SolanaSignInOutput { + /** + * Account that was signed in. + * The address of the account may be different from the provided input Address. + */ + readonly account: WalletAccount; + /** + * Message bytes that were signed. + * The wallet may prefix or otherwise modify the message before signing it. + */ + readonly signedMessage: Uint8Array; + /** + * Message signature produced. + * If the signature type is provided, the signature must be Ed25519. + */ + readonly signature: Uint8Array; + /** + * Optional type of the message signature produced. + * If not provided, the signature must be Ed25519. + */ + readonly signatureType?: 'ed25519'; +} +//# sourceMappingURL=solana.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/web3/solana.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/module/lib/web3/solana.d.ts.map new file mode 100644 index 0000000..447112c --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/web3/solana.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"solana.d.ts","sourceRoot":"","sources":["../../../../src/lib/web3/solana.ts"],"names":[],"mappings":"AAEA;;;;;;GAMG;AACH,MAAM,MAAM,gBAAgB,GAAG,GAAG,MAAM,IAAI,MAAM,EAAE,CAAA;AAEpD;;;;;;;GAOG;AACH,MAAM,MAAM,eAAe,GAAG,SAAS,gBAAgB,EAAE,CAAA;AAEzD;;;;;;;;;;;GAWG;AACH,MAAM,MAAM,aAAa,GAAG,OAAO,CAAA;AAEnC;;;;;;GAMG;AACH,MAAM,MAAM,UAAU,GAAG,cAAc,SAAS,GAAG,MAAM,GAAG,KAAK,GAAG,KAAK,WAAW,MAAM,EAAE,CAAA;AAE5F;;;;;;;;;;;;GAYG;AACH,MA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MAAM,WAAW,kBAAkB;IACjC;;;OAGG;IACH,QAAQ,CAAC,OAAO,EAAE,aAAa,CAAA;IAE/B;;;OAGG;IACH,QAAQ,CAAC,aAAa,EAAE,UAAU,CAAA;IAElC;;;OAGG;IACH,QAAQ,CAAC,SAAS,EAAE,UAAU,CAAA;IAE9B;;;OAGG;IACH,QAAQ,CAAC,aAAa,CAAC,EAAE,SAAS,CAAA;CACnC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/web3/solana.js b/backend/node_modules/@supabase/auth-js/dist/module/lib/web3/solana.js new file mode 100644 index 0000000..0bf182a --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/web3/solana.js @@ -0,0 +1,3 @@ +// types copied over from @solana/wallet-standard-features and @wallet-standard/base so this library doesn't depend on them +export {}; +//# sourceMappingURL=solana.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/web3/solana.js.map b/backend/node_modules/@supabase/auth-js/dist/module/lib/web3/solana.js.map new file mode 100644 index 0000000..27432a1 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/web3/solana.js.map @@ -0,0 +1 @@ +{"version":3,"file":"solana.js","sourceRoot":"","sources":["../../../../src/lib/web3/solana.ts"],"names":[],"mappings":"AAAA,2HAA2H"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/webauthn.d.ts b/backend/node_modules/@supabase/auth-js/dist/module/lib/webauthn.d.ts new file mode 100644 index 0000000..a0fd0d8 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/webauthn.d.ts @@ -0,0 +1,276 @@ +import GoTrueClient from '../GoTrueClient'; +import { AuthError } from './errors'; +import { AuthMFAEnrollWebauthnResponse, AuthMFAVerifyResponse, AuthMFAVerifyResponseData, MFAChallengeWebauthnParams, MFAEnrollWebauthnParams, MFAVerifyWebauthnParamFields, MFAVerifyWebauthnParams, RequestResult, StrictOmit } from './types'; +import type { AuthenticationCredential, AuthenticationResponseJSON, PublicKeyCredentialCreationOptionsFuture, PublicKeyCredentialCreationOptionsJSON, PublicKeyCredentialRequestOptionsFuture, PublicKeyCredentialRequestOptionsJSON, RegistrationCredential, RegistrationResponseJSON } from './webauthn.dom'; +import { identifyAuthenticationError, identifyRegistrationError, isWebAuthnError, WebAuthnError } from './webauthn.errors'; +export { WebAuthnError, isWebAuthnError, identifyRegistrationError, identifyAuthenticationError }; +export type { RegistrationResponseJSON, AuthenticationResponseJSON }; +/** + * WebAuthn abort service to manage ceremony cancellation. + * Ensures only one WebAuthn ceremony is active at a time to prevent "operation already in progress" errors. + * + * @experimental This class is experimental and may change in future releases + * @see {@link https://w3c.github.io/webauthn/#sctn-automation-webdriver-capability W3C WebAuthn Spec - Aborting Ceremonies} + */ +export declare class WebAuthnAbortService { + private controller; + /** + * Create an abort signal for a new WebAuthn operation. + * Automatically cancels any existing operation. + * + * @returns {AbortSignal} Signal to pass to navigator.credentials.create() or .get() + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal MDN - AbortSignal} + */ + createNewAbortSignal(): AbortSignal; + /** + * Manually cancel the current WebAuthn operation. + * Useful for cleaning up when user cancels or navigates away. + * + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort MDN - AbortController.abort} + */ + cancelCeremony(): void; +} +/** + * Singleton instance to ensure only one WebAuthn ceremony is active at a time. + * This prevents "operation already in progress" errors when retrying WebAuthn operations. + * + * @experimental This instance is experimental and may change in future releases + */ +export declare const webAuthnAbortService: WebAuthnAbortService; +/** + * Server response format for WebAuthn credential creation options. + * Uses W3C standard JSON format with base64url-encoded binary fields. + */ +export type ServerCredentialCreationOptions = PublicKeyCredentialCreationOptionsJSON; +/** + * Server response format for WebAuthn credential request options. + * Uses W3C standard JSON format with base64url-encoded binary fields. + */ +export type ServerCredentialRequestOptions = PublicKeyCredentialRequestOptionsJSON; +/** + * Convert base64url encoded strings in WebAuthn credential creation options to ArrayBuffers + * as required by the WebAuthn browser API. + * Supports both native WebAuthn Level 3 parseCreationOptionsFromJSON and manual fallback. + * + * @param {ServerCredentialCreationOptions} options - JSON options from server with base64url encoded fields + * @returns {PublicKeyCredentialCreationOptionsFuture} Options ready for navigator.credentials.create() + * @see {@link https://w3c.github.io/webauthn/#sctn-parseCreationOptionsFromJSON W3C WebAuthn Spec - parseCreationOptionsFromJSON} + */ +export declare function deserializeCredentialCreationOptions(options: ServerCredentialCreationOptions): PublicKeyCredentialCreationOptionsFuture; +/** + * Convert base64url encoded strings in WebAuthn credential request options to ArrayBuffers + * as required by the WebAuthn browser API. + * Supports both native WebAuthn Level 3 parseRequestOptionsFromJSON and manual fallback. + * + * @param {ServerCredentialRequestOptions} options - JSON options from server with base64url encoded fields + * @returns {PublicKeyCredentialRequestOptionsFuture} Options ready for navigator.credentials.get() + * @see {@link https://w3c.github.io/webauthn/#sctn-parseRequestOptionsFromJSON W3C WebAuthn Spec - parseRequestOptionsFromJSON} + */ +export declare function deserializeCredentialRequestOptions(options: ServerCredentialRequestOptions): PublicKeyCredentialRequestOptionsFuture; +/** + * Server format for credential response with base64url-encoded binary fields + * Can be either a registration or authentication response + */ +export type ServerCredentialResponse = RegistrationResponseJSON | AuthenticationResponseJSON; +/** + * Convert a registration/enrollment credential response to server format. + * Serializes binary fields to base64url for JSON transmission. + * Supports both native WebAuthn Level 3 toJSON and manual fallback. + * + * @param {RegistrationCredential} credential - Credential from navigator.credentials.create() + * @returns {RegistrationResponseJSON} JSON-serializable credential for server + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-tojson W3C WebAuthn Spec - toJSON} + */ +export declare function serializeCredentialCreationResponse(credential: RegistrationCredential): RegistrationResponseJSON; +/** + * Convert an authentication/verification credential response to server format. + * Serializes binary fields to base64url for JSON transmission. + * Supports both native WebAuthn Level 3 toJSON and manual fallback. + * + * @param {AuthenticationCredential} credential - Credential from navigator.credentials.get() + * @returns {AuthenticationResponseJSON} JSON-serializable credential for server + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-tojson W3C WebAuthn Spec - toJSON} + */ +export declare function serializeCredentialRequestResponse(credential: AuthenticationCredential): AuthenticationResponseJSON; +/** + * A simple test to determine if a hostname is a properly-formatted domain name. + * Considers localhost valid for development environments. + * + * A "valid domain" is defined here: https://url.spec.whatwg.org/#valid-domain + * + * Regex sourced from here: + * https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch08s15.html + * + * @param {string} hostname - The hostname to validate + * @returns {boolean} True if valid domain or localhost + * @see {@link https://url.spec.whatwg.org/#valid-domain WHATWG URL Spec - Valid Domain} + */ +export declare function isValidDomain(hostname: string): boolean; +/** + * Create a WebAuthn credential using the browser's credentials API. + * Wraps navigator.credentials.create() with error handling. + * + * @param {CredentialCreationOptions} options - Options including publicKey parameters + * @returns {Promise>} Created credential or error + * @see {@link https://w3c.github.io/webauthn/#sctn-createCredential W3C WebAuthn Spec - Create Credential} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/create MDN - credentials.create} + */ +export declare function createCredential(options: StrictOmit & { + publicKey: PublicKeyCredentialCreationOptionsFuture; +}): Promise>; +/** + * Get a WebAuthn credential using the browser's credentials API. + * Wraps navigator.credentials.get() with error handling. + * + * @param {CredentialRequestOptions} options - Options including publicKey parameters + * @returns {Promise>} Retrieved credential or error + * @see {@link https://w3c.github.io/webauthn/#sctn-getAssertion W3C WebAuthn Spec - Get Assertion} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/get MDN - credentials.get} + */ +export declare function getCredential(options: StrictOmit & { + publicKey: PublicKeyCredentialRequestOptionsFuture; +}): Promise>; +export declare const DEFAULT_CREATION_OPTIONS: Partial; +export declare const DEFAULT_REQUEST_OPTIONS: Partial; +/** + * Merges WebAuthn credential creation options with overrides. + * Sets sensible defaults for authenticator selection and extensions. + * + * @param {PublicKeyCredentialCreationOptionsFuture} baseOptions - The base options from the server + * @param {PublicKeyCredentialCreationOptionsFuture} overrides - Optional overrides to apply + * @param {string} friendlyName - Optional friendly name for the credential + * @returns {PublicKeyCredentialCreationOptionsFuture} Merged credential creation options + * @see {@link https://w3c.github.io/webauthn/#dictdef-authenticatorselectioncriteria W3C WebAuthn Spec - AuthenticatorSelectionCriteria} + */ +export declare function mergeCredentialCreationOptions(baseOptions: PublicKeyCredentialCreationOptionsFuture, overrides?: Partial): PublicKeyCredentialCreationOptionsFuture; +/** + * Merges WebAuthn credential request options with overrides. + * Sets sensible defaults for user verification and hints. + * + * @param {PublicKeyCredentialRequestOptionsFuture} baseOptions - The base options from the server + * @param {PublicKeyCredentialRequestOptionsFuture} overrides - Optional overrides to apply + * @returns {PublicKeyCredentialRequestOptionsFuture} Merged credential request options + * @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialrequestoptions W3C WebAuthn Spec - PublicKeyCredentialRequestOptions} + */ +export declare function mergeCredentialRequestOptions(baseOptions: PublicKeyCredentialRequestOptionsFuture, overrides?: Partial): PublicKeyCredentialRequestOptionsFuture; +/** + * WebAuthn API wrapper for Supabase Auth. + * Provides methods for enrolling, challenging, verifying, authenticating, and registering WebAuthn credentials. + * + * @experimental This API is experimental and may change in future releases + * @see {@link https://w3c.github.io/webauthn/ W3C WebAuthn Specification} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API MDN - Web Authentication API} + */ +export declare class WebAuthnApi { + private client; + enroll: typeof WebAuthnApi.prototype._enroll; + challenge: typeof WebAuthnApi.prototype._challenge; + verify: typeof WebAuthnApi.prototype._verify; + authenticate: typeof WebAuthnApi.prototype._authenticate; + register: typeof WebAuthnApi.prototype._register; + constructor(client: GoTrueClient); + /** + * Enroll a new WebAuthn factor. + * Creates an unverified WebAuthn factor that must be verified with a credential. + * + * @experimental This method is experimental and may change in future releases + * @param {Omit} params - Enrollment parameters (friendlyName required) + * @returns {Promise} Enrolled factor details or error + * @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registering a New Credential} + */ + _enroll(params: Omit): Promise; + /** + * Challenge for WebAuthn credential creation or authentication. + * Combines server challenge with browser credential operations. + * Handles both registration (create) and authentication (request) flows. + * + * @experimental This method is experimental and may change in future releases + * @param {MFAChallengeWebauthnParams & { friendlyName?: string; signal?: AbortSignal }} params - Challenge parameters including factorId + * @param {Object} overrides - Allows you to override the parameters passed to navigator.credentials + * @param {PublicKeyCredentialCreationOptionsFuture} overrides.create - Override options for credential creation + * @param {PublicKeyCredentialRequestOptionsFuture} overrides.request - Override options for credential request + * @returns {Promise} Challenge response with credential or error + * @see {@link https://w3c.github.io/webauthn/#sctn-credential-creation W3C WebAuthn Spec - Credential Creation} + * @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying Assertion} + */ + _challenge({ factorId, webauthn, friendlyName, signal, }: MFAChallengeWebauthnParams & { + friendlyName?: string; + signal?: AbortSignal; + }, overrides?: { + create?: Partial; + request?: never; + } | { + create?: never; + request?: Partial; + }): Promise['webauthn'], 'rpId' | 'rpOrigins'>; + }, WebAuthnError | AuthError>>; + /** + * Verify a WebAuthn credential with the server. + * Completes the WebAuthn ceremony by sending the credential to the server for verification. + * + * @experimental This method is experimental and may change in future releases + * @param {Object} params - Verification parameters + * @param {string} params.challengeId - ID of the challenge being verified + * @param {string} params.factorId - ID of the WebAuthn factor + * @param {MFAVerifyWebauthnParams['webauthn']} params.webauthn - WebAuthn credential response + * @returns {Promise} Verification result with session or error + * @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying an Authentication Assertion} + * */ + _verify({ challengeId, factorId, webauthn, }: { + challengeId: string; + factorId: string; + webauthn: MFAVerifyWebauthnParams['webauthn']; + }): Promise; + /** + * Complete WebAuthn authentication flow. + * Performs challenge and verification in a single operation for existing credentials. + * + * @experimental This method is experimental and may change in future releases + * @param {Object} params - Authentication parameters + * @param {string} params.factorId - ID of the WebAuthn factor to authenticate with + * @param {Object} params.webauthn - WebAuthn configuration + * @param {string} params.webauthn.rpId - Relying Party ID (defaults to current hostname) + * @param {string[]} params.webauthn.rpOrigins - Allowed origins (defaults to current origin) + * @param {AbortSignal} params.webauthn.signal - Optional abort signal + * @param {PublicKeyCredentialRequestOptionsFuture} overrides - Override options for navigator.credentials.get + * @returns {Promise>} Authentication result + * @see {@link https://w3c.github.io/webauthn/#sctn-authentication W3C WebAuthn Spec - Authentication Ceremony} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialRequestOptions MDN - PublicKeyCredentialRequestOptions} + */ + _authenticate({ factorId, webauthn: { rpId, rpOrigins, signal, }, }: { + factorId: string; + webauthn?: { + rpId?: string; + rpOrigins?: string[]; + signal?: AbortSignal; + }; + }, overrides?: PublicKeyCredentialRequestOptionsFuture): Promise>; + /** + * Complete WebAuthn registration flow. + * Performs enrollment, challenge, and verification in a single operation for new credentials. + * + * @experimental This method is experimental and may change in future releases + * @param {Object} params - Registration parameters + * @param {string} params.friendlyName - User-friendly name for the credential + * @param {string} params.rpId - Relying Party ID (defaults to current hostname) + * @param {string[]} params.rpOrigins - Allowed origins (defaults to current origin) + * @param {AbortSignal} params.signal - Optional abort signal + * @param {PublicKeyCredentialCreationOptionsFuture} overrides - Override options for navigator.credentials.create + * @returns {Promise>} Registration result + * @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registration Ceremony} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions MDN - PublicKeyCredentialCreationOptions} + */ + _register({ friendlyName, webauthn: { rpId, rpOrigins, signal, }, }: { + friendlyName: string; + webauthn?: { + rpId?: string; + rpOrigins?: string[]; + signal?: AbortSignal; + }; + }, overrides?: Partial): Promise>; +} +//# sourceMappingURL=webauthn.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/webauthn.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/module/lib/webauthn.d.ts.map new file mode 100644 index 0000000..a608276 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/webauthn.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"webauthn.d.ts","sourceRoot":"","sources":["../../../src/lib/webauthn.ts"],"names":[],"mappings":"AAAA,OAAO,YAAY,MAAM,iBAAiB,CAAA;AAE1C,OAAO,EAAE,SAAS,EAAiC,MAAM,UAAU,CAAA;AACnE,OAAO,EACL,6BAA6B,EAC7B,qBAAqB,EACrB,yBAAyB,EACzB,0BAA0B,EAC1B,uBAAuB,EACvB,4BAA4B,EAC5B,uBAAuB,EACvB,aAAa,EACb,UAAU,EACX,MAAM,SAAS,CAAA;AAEhB,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAE1B,wCAAwC,EACxC,sCAAsC,EAEtC,uCAAuC,EACvC,qCAAqC,EACrC,sBAAsB,EACtB,wBAAwB,EACzB,MAAM,gBAAgB,CAAA;AAEvB,OAAO,EACL,2BAA2B,EAC3B,yBAAyB,EACzB,eAAe,EACf,aAAa,EAEd,MAAM,mBAAmB,CAAA;AAE1B,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,yBAAyB,EAAE,2BAA2B,EAAE,CAAA;AAEjG,YAAY,EAAE,wBAAwB,EAAE,0BAA0B,EAAE,CAAA;AAEpE;;;;;;GAMG;AACH,qBAAa,oBAAoB;IAC/B,OAAO,CAAC,UAAU,CAA6B;IAE/C;;;;;;OAMG;IACH,oBAAoB,IAAI,WAAW;IAanC;;;;;OAKG;IACH,cAAc,IAAI,IAAI;CAQvB;AAED;;;;;GAKG;AACH,eAAO,MAAM,oBAAoB,sBAA6B,CAAA;AAE9D;;;GAGG;AACH,MAAM,MAAM,+BAA+B,GAAG,sCAAsC,CAAA;AAEpF;;;GAGG;AACH,MAAM,MAAM,8BAA8B,GAAG,qCAAqC,CAAA;AAElF;;;;;;;;GAQG;AACH,wBAAgB,oCAAoC,CAClD,OAAO,EAAE,+BAA+B,GACvC,wCAAwC,CA0D1C;AAED;;;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ts b/backend/node_modules/@supabase/auth-js/dist/module/lib/webauthn.dom.d.ts new file mode 100644 index 0000000..ff0410f --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/webauthn.dom.d.ts @@ -0,0 +1,583 @@ +import { StrictOmit } from './types'; +/** + * A variant of PublicKeyCredentialCreationOptions suitable for JSON transmission to the browser to + * (eventually) get passed into navigator.credentials.create(...) in the browser. + * + * This should eventually get replaced with official TypeScript DOM types when WebAuthn Level 3 types + * eventually make it into the language: + * + * @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialcreationoptionsjson W3C WebAuthn Spec - PublicKeyCredentialCreationOptionsJSON} + */ +export interface PublicKeyCredentialCreationOptionsJSON { + /** + * Information about the Relying Party responsible for the request. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-rp W3C - rp} + */ + rp: PublicKeyCredentialRpEntity; + /** + * Information about the user account for which the credential is being created. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-user W3C - user} + */ + user: PublicKeyCredentialUserEntityJSON; + /** + * A server-generated challenge in base64url format. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-challenge W3C - challenge} + */ + challenge: Base64URLString; + /** + * Information about desired properties of the credential to be created. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-pubkeycredparams W3C - pubKeyCredParams} + */ + pubKeyCredParams: PublicKeyCredentialParameters[]; + /** + * Time in milliseconds that the caller is willing to wait for the operation to complete. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-timeout W3C - timeout} + */ + timeout?: number; + /** + * Credentials that the authenticator should not create a new credential for. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-excludecredentials W3C - excludeCredentials} + */ + excludeCredentials?: PublicKeyCredentialDescriptorJSON[]; + /** + * Criteria for authenticator selection. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-authenticatorselection W3C - authenticatorSelection} + */ + authenticatorSelection?: AuthenticatorSelectionCriteria; + /** + * Hints about what types of authenticators the user might want to use. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-hints W3C - hints} + */ + hints?: PublicKeyCredentialHint[]; + /** + * How the attestation statement should be transported. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-attestation W3C - attestation} + */ + attestation?: AttestationConveyancePreference; + /** + * The attestation statement formats that the Relying Party will accept. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-attestationformats W3C - attestationFormats} + */ + attestationFormats?: AttestationFormat[]; + /** + * Additional parameters requesting additional processing by the client and authenticator. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-extensions W3C - extensions} + */ + extensions?: AuthenticationExtensionsClientInputs; +} +/** + * A variant of PublicKeyCredentialRequestOptions suitable for JSON transmission to the browser to + * (eventually) get passed into navigator.credentials.get(...) in the browser. + * + * @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialrequestoptionsjson W3C WebAuthn Spec - PublicKeyCredentialRequestOptionsJSON} + */ +export interface PublicKeyCredentialRequestOptionsJSON { + /** + * A server-generated challenge in base64url format. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialrequestoptions-challenge W3C - challenge} + */ + challenge: Base64URLString; + /** + * Time in milliseconds that the caller is willing to wait for the operation to complete. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialrequestoptions-timeout W3C - timeout} + */ + timeout?: number; + /** + * The relying party identifier claimed by the caller. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialrequestoptions-rpid W3C - rpId} + */ + rpId?: string; + /** + * A list of credentials acceptable for authentication. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialrequestoptions-allowcredentials W3C - allowCredentials} + */ + allowCredentials?: PublicKeyCredentialDescriptorJSON[]; + /** + * Whether user verification should be performed by the authenticator. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialrequestoptions-userverification W3C - userVerification} + */ + userVerification?: UserVerificationRequirement; + /** + * Hints about what types of authenticators the user might want to use. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialrequestoptions-hints W3C - hints} + */ + hints?: PublicKeyCredentialHint[]; + /** + * Additional parameters requesting additional processing by the client and authenticator. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialrequestoptions-extensions W3C - extensions} + */ + extensions?: AuthenticationExtensionsClientInputs; +} +/** + * Represents a public key credential descriptor in JSON format. + * Used to identify credentials for exclusion or allowance during WebAuthn ceremonies. + * + * @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialdescriptorjson W3C WebAuthn Spec - PublicKeyCredentialDescriptorJSON} + */ +export interface PublicKeyCredentialDescriptorJSON { + /** + * The credential ID in base64url format. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialdescriptor-id W3C - id} + */ + id: Base64URLString; + /** + * The type of the public key credential (always "public-key"). + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialdescriptor-type W3C - type} + */ + type: PublicKeyCredentialType; + /** + * How the authenticator communicates with clients. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialdescriptor-transports W3C - transports} + */ + transports?: AuthenticatorTransportFuture[]; +} +/** + * Represents user account information in JSON format for WebAuthn registration. + * Contains identifiers and display information for the user being registered. + * + * @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialuserentityjson W3C WebAuthn Spec - PublicKeyCredentialUserEntityJSON} + */ +export interface PublicKeyCredentialUserEntityJSON { + /** + * A unique identifier for the user account (base64url encoded). + * Maximum 64 bytes. Should not contain PII. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialuserentity-id W3C - user.id} + */ + id: string; + /** + * A human-readable identifier for the account (e.g., email, username). + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialentity-name W3C - user.name} + */ + name: string; + /** + * A human-friendly display name for the user (e.g., "John Doe"). + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialuserentity-displayname W3C - user.displayName} + */ + displayName: string; +} +/** + * Represents user account information for WebAuthn registration with binary data. + * Contains identifiers and display information for the user being registered. + * + * @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialuserentity W3C WebAuthn Spec - PublicKeyCredentialUserEntity} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialUserEntity MDN - PublicKeyCredentialUserEntity} + */ +export interface PublicKeyCredentialUserEntity { + /** + * A unique identifier for the user account. + * Maximum 64 bytes. Should not contain PII. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialuserentity-id W3C - user.id} + */ + id: BufferSource; + /** + * A human-readable identifier for the account. + * Typically an email, username, or phone number. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialentity-name W3C - user.name} + */ + name: string; + /** + * A human-friendly display name for the user. + * Example: "John Doe" + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialuserentity-displayname W3C - user.displayName} + */ + displayName: string; +} +/** + * The credential returned from navigator.credentials.create() during WebAuthn registration. + * Contains the new credential's public key and attestation information. + * + * @see {@link https://w3c.github.io/webauthn/#registrationceremony W3C WebAuthn Spec - Registration} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredential MDN - PublicKeyCredential} + */ +export interface RegistrationCredential extends PublicKeyCredentialFuture { + response: AuthenticatorAttestationResponseFuture; +} +/** + * A slightly-modified RegistrationCredential to simplify working with ArrayBuffers that + * are Base64URL-encoded in the browser so that they can be sent as JSON to the server. + * + * @see {@link https://w3c.github.io/webauthn/#dictdef-registrationresponsejson W3C WebAuthn Spec - RegistrationResponseJSON} + */ +export interface RegistrationResponseJSON { + /** + * The credential ID (same as rawId for JSON). + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-id W3C - id} + */ + id: Base64URLString; + /** + * The raw credential ID in base64url format. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-rawid W3C - rawId} + */ + rawId: Base64URLString; + /** + * The authenticator's response to the client's request to create a credential. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-response W3C - response} + */ + response: AuthenticatorAttestationResponseJSON; + /** + * The authenticator attachment modality in effect at the time of credential creation. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-authenticatorattachment W3C - authenticatorAttachment} + */ + authenticatorAttachment?: AuthenticatorAttachment; + /** + * The results of processing client extensions. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-getclientextensionresults W3C - getClientExtensionResults} + */ + clientExtensionResults: AuthenticationExtensionsClientOutputs; + /** + * The type of the credential (always "public-key"). + * @see {@link https://w3c.github.io/webauthn/#dom-credential-type W3C - type} + */ + type: PublicKeyCredentialType; +} +/** + * The credential returned from navigator.credentials.get() during WebAuthn authentication. + * Contains the assertion signature proving possession of the private key. + * + * @see {@link https://w3c.github.io/webauthn/#authentication W3C WebAuthn Spec - Authentication} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredential MDN - PublicKeyCredential} + */ +export interface AuthenticationCredential extends PublicKeyCredentialFuture { + response: AuthenticatorAssertionResponse; +} +/** + * A slightly-modified AuthenticationCredential to simplify working with ArrayBuffers that + * are Base64URL-encoded in the browser so that they can be sent as JSON to the server. + * + * @see {@link https://w3c.github.io/webauthn/#dictdef-authenticationresponsejson W3C WebAuthn Spec - AuthenticationResponseJSON} + */ +export interface AuthenticationResponseJSON { + /** + * The credential ID (same as rawId for JSON). + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-id W3C - id} + */ + id: Base64URLString; + /** + * The raw credential ID in base64url format. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-rawid W3C - rawId} + */ + rawId: Base64URLString; + /** + * The authenticator's response to the client's request to authenticate. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-response W3C - response} + */ + response: AuthenticatorAssertionResponseJSON; + /** + * The authenticator attachment modality in effect at the time of authentication. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-authenticatorattachment W3C - authenticatorAttachment} + */ + authenticatorAttachment?: AuthenticatorAttachment; + /** + * The results of processing client extensions. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-getclientextensionresults W3C - getClientExtensionResults} + */ + clientExtensionResults: AuthenticationExtensionsClientOutputs; + /** + * The type of the credential (always "public-key"). + * @see {@link https://w3c.github.io/webauthn/#dom-credential-type W3C - type} + */ + type: PublicKeyCredentialType; +} +/** + * A slightly-modified AuthenticatorAttestationResponse to simplify working with ArrayBuffers that + * are Base64URL-encoded in the browser so that they can be sent as JSON to the server. + * + * @see {@link https://w3c.github.io/webauthn/#dictdef-authenticatorattestationresponsejson W3C WebAuthn Spec - AuthenticatorAttestationResponseJSON} + */ +export interface AuthenticatorAttestationResponseJSON { + /** + * JSON-serialized client data passed to the authenticator. + * @see {@link https://w3c.github.io/webauthn/#dom-authenticatorresponse-clientdatajson W3C - clientDataJSON} + */ + clientDataJSON: Base64URLString; + /** + * The attestation object in base64url format. + * @see {@link https://w3c.github.io/webauthn/#dom-authenticatorattestationresponse-attestationobject W3C - attestationObject} + */ + attestationObject: Base64URLString; + /** + * The authenticator data contained within the attestation object. + * Optional in L2, but becomes required in L3. Play it safe until L3 becomes Recommendation + * @see {@link https://w3c.github.io/webauthn/#dom-authenticatorattestationresponse-getauthenticatordata W3C - getAuthenticatorData} + */ + authenticatorData?: Base64URLString; + /** + * The transports that the authenticator supports. + * Optional in L2, but becomes required in L3. Play it safe until L3 becomes Recommendation + * @see {@link https://w3c.github.io/webauthn/#dom-authenticatorattestationresponse-gettransports W3C - getTransports} + */ + transports?: AuthenticatorTransportFuture[]; + /** + * The COSEAlgorithmIdentifier for the public key. + * Optional in L2, but becomes required in L3. Play it safe until L3 becomes Recommendation + * @see {@link https://w3c.github.io/webauthn/#dom-authenticatorattestationresponse-getpublickeyalgorithm W3C - getPublicKeyAlgorithm} + */ + publicKeyAlgorithm?: COSEAlgorithmIdentifier; + /** + * The public key in base64url format. + * @see {@link https://w3c.github.io/webauthn/#dom-authenticatorattestationresponse-getpublickey W3C - getPublicKey} + */ + publicKey?: Base64URLString; +} +/** + * A slightly-modified AuthenticatorAssertionResponse to simplify working with ArrayBuffers that + * are Base64URL-encoded in the browser so that they can be sent as JSON to the server. + * + * @see {@link https://w3c.github.io/webauthn/#dictdef-authenticatorassertionresponsejson W3C WebAuthn Spec - AuthenticatorAssertionResponseJSON} + */ +export interface AuthenticatorAssertionResponseJSON { + /** + * JSON-serialized client data passed to the authenticator. + * @see {@link https://w3c.github.io/webauthn/#dom-authenticatorresponse-clientdatajson W3C - clientDataJSON} + */ + clientDataJSON: Base64URLString; + /** + * The authenticator data returned by the authenticator. + * @see {@link https://w3c.github.io/webauthn/#dom-authenticatorassertionresponse-authenticatordata W3C - authenticatorData} + */ + authenticatorData: Base64URLString; + /** + * The signature generated by the authenticator. + * @see {@link https://w3c.github.io/webauthn/#dom-authenticatorassertionresponse-signature W3C - signature} + */ + signature: Base64URLString; + /** + * The user handle returned by the authenticator, if any. + * @see {@link https://w3c.github.io/webauthn/#dom-authenticatorassertionresponse-userhandle W3C - userHandle} + */ + userHandle?: Base64URLString; +} +/** + * Public key credential information needed to verify authentication responses. + * Stores the credential's public key and metadata for server-side verification. + * + * @see {@link https://w3c.github.io/webauthn/#sctn-credential-storage-modality W3C WebAuthn Spec - Credential Storage} + */ +export type WebAuthnCredential = { + /** + * The credential ID in base64url format. + * @see {@link https://w3c.github.io/webauthn/#credential-id W3C - Credential ID} + */ + id: Base64URLString; + /** + * The credential's public key. + * @see {@link https://w3c.github.io/webauthn/#credential-public-key W3C - Credential Public Key} + */ + publicKey: Uint8Array_; + /** + * Number of times this authenticator is expected to have been used. + * @see {@link https://w3c.github.io/webauthn/#signature-counter W3C - Signature Counter} + */ + counter: number; + /** + * The transports that the authenticator supports. + * From browser's `startRegistration()` -> RegistrationCredentialJSON.transports (API L2 and up) + * @see {@link https://w3c.github.io/webauthn/#dom-authenticatorattestationresponse-gettransports W3C - getTransports} + */ + transports?: AuthenticatorTransportFuture[]; +}; +/** + * An attempt to communicate that this isn't just any string, but a Base64URL-encoded string. + * Base64URL encoding is used throughout WebAuthn for binary data transmission. + * + * @see {@link https://datatracker.ietf.org/doc/html/rfc4648#section-5 RFC 4648 - Base64URL Encoding} + */ +export type Base64URLString = string; +/** + * AuthenticatorAttestationResponse in TypeScript's DOM lib is outdated (up through v3.9.7). + * Maintain an augmented version here so we can implement additional properties as the WebAuthn + * spec evolves. + * + * Properties marked optional are not supported in all browsers. + * + * @see {@link https://www.w3.org/TR/webauthn-2/#iface-authenticatorattestationresponse W3C WebAuthn Spec - AuthenticatorAttestationResponse} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AuthenticatorAttestationResponse MDN - AuthenticatorAttestationResponse} + */ +export interface AuthenticatorAttestationResponseFuture extends AuthenticatorAttestationResponse { + /** + * Returns the transports that the authenticator supports. + * @see {@link https://w3c.github.io/webauthn/#dom-authenticatorattestationresponse-gettransports W3C - getTransports} + */ + getTransports(): AuthenticatorTransportFuture[]; +} +/** + * A super class of TypeScript's `AuthenticatorTransport` that includes support for the latest + * transports. Should eventually be replaced by TypeScript's when TypeScript gets updated to + * know about it (sometime after 4.6.3) + * + * @see {@link https://w3c.github.io/webauthn/#enum-transport W3C WebAuthn Spec - AuthenticatorTransport} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AuthenticatorAttestationResponse/getTransports MDN - getTransports} + */ +export type AuthenticatorTransportFuture = 'ble' | 'cable' | 'hybrid' | 'internal' | 'nfc' | 'smart-card' | 'usb'; +/** + * A super class of TypeScript's `PublicKeyCredentialDescriptor` that knows about the latest + * transports. Should eventually be replaced by TypeScript's when TypeScript gets updated to + * know about it (sometime after 4.6.3) + * + * @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialdescriptor W3C WebAuthn Spec - PublicKeyCredentialDescriptor} + */ +export interface PublicKeyCredentialDescriptorFuture extends Omit { + /** + * How the authenticator communicates with clients. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialdescriptor-transports W3C - transports} + */ + transports?: AuthenticatorTransportFuture[]; +} +/** + * Enhanced PublicKeyCredentialCreationOptions that knows about the latest features. + * Used for WebAuthn registration ceremonies. + * + * @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialcreationoptions W3C WebAuthn Spec - PublicKeyCredentialCreationOptions} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions MDN - PublicKeyCredentialCreationOptions} + */ +export interface PublicKeyCredentialCreationOptionsFuture extends StrictOmit { + /** + * Credentials that the authenticator should not create a new credential for. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-excludecredentials W3C - excludeCredentials} + */ + excludeCredentials?: PublicKeyCredentialDescriptorFuture[]; + /** + * Information about the user account for which the credential is being created. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-user W3C - user} + */ + user: PublicKeyCredentialUserEntity; + /** + * Hints about what types of authenticators the user might want to use. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-hints W3C - hints} + */ + hints?: PublicKeyCredentialHint[]; + /** + * Criteria for authenticator selection. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-authenticatorselection W3C - authenticatorSelection} + */ + authenticatorSelection?: AuthenticatorSelectionCriteria; + /** + * Information about desired properties of the credential to be created. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-pubkeycredparams W3C - pubKeyCredParams} + */ + pubKeyCredParams: PublicKeyCredentialParameters[]; + /** + * Information about the Relying Party responsible for the request. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-rp W3C - rp} + */ + rp: PublicKeyCredentialRpEntity; +} +/** + * Enhanced PublicKeyCredentialRequestOptions that knows about the latest features. + * Used for WebAuthn authentication ceremonies. + * + * @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialrequestoptions W3C WebAuthn Spec - PublicKeyCredentialRequestOptions} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialRequestOptions MDN - PublicKeyCredentialRequestOptions} + */ +export interface PublicKeyCredentialRequestOptionsFuture extends StrictOmit { + /** + * A list of credentials acceptable for authentication. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialrequestoptions-allowcredentials W3C - allowCredentials} + */ + allowCredentials?: PublicKeyCredentialDescriptorFuture[]; + /** + * Hints about what types of authenticators the user might want to use. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialrequestoptions-hints W3C - hints} + */ + hints?: PublicKeyCredentialHint[]; + /** + * The attestation conveyance preference for the authentication ceremony. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-attestation W3C - attestation} + */ + attestation?: AttestationConveyancePreference; +} +/** + * Union type for all WebAuthn credential responses in JSON format. + * Can be either a registration response (for new credentials) or authentication response (for existing credentials). + */ +export type PublicKeyCredentialJSON = RegistrationResponseJSON | AuthenticationResponseJSON; +/** + * A super class of TypeScript's `PublicKeyCredential` that knows about upcoming WebAuthn features. + * Includes WebAuthn Level 3 methods for JSON serialization and parsing. + * + * @see {@link https://w3c.github.io/webauthn/#publickeycredential W3C WebAuthn Spec - PublicKeyCredential} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredential MDN - PublicKeyCredential} + */ +export interface PublicKeyCredentialFuture extends PublicKeyCredential { + /** + * The type of the credential (always "public-key"). + * @see {@link https://w3c.github.io/webauthn/#dom-credential-type W3C - type} + */ + type: PublicKeyCredentialType; + /** + * Checks if conditional mediation is available. + * @see {@link https://github.com/w3c/webauthn/issues/1745 GitHub - Conditional Mediation} + */ + isConditionalMediationAvailable?(): Promise; + /** + * Parses JSON to create PublicKeyCredentialCreationOptions. + * @see {@link https://w3c.github.io/webauthn/#sctn-parseCreationOptionsFromJSON W3C - parseCreationOptionsFromJSON} + */ + parseCreationOptionsFromJSON(options: PublicKeyCredentialCreationOptionsJSON): PublicKeyCredentialCreationOptionsFuture; + /** + * Parses JSON to create PublicKeyCredentialRequestOptions. + * @see {@link https://w3c.github.io/webauthn/#sctn-parseRequestOptionsFromJSON W3C - parseRequestOptionsFromJSON} + */ + parseRequestOptionsFromJSON(options: PublicKeyCredentialRequestOptionsJSON): PublicKeyCredentialRequestOptionsFuture; + /** + * Serializes the credential to JSON format. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-tojson W3C - toJSON} + */ + toJSON(): T; +} +/** + * The two types of credentials as defined by bit 3 ("Backup Eligibility") in authenticator data: + * - `"singleDevice"` credentials will never be backed up + * - `"multiDevice"` credentials can be backed up + * + * @see {@link https://w3c.github.io/webauthn/#sctn-authenticator-data W3C WebAuthn Spec - Authenticator Data} + */ +export type CredentialDeviceType = 'singleDevice' | 'multiDevice'; +/** + * Categories of authenticators that Relying Parties can pass along to browsers during + * registration. Browsers that understand these values can optimize their modal experience to + * start the user off in a particular registration flow: + * + * - `hybrid`: A platform authenticator on a mobile device + * - `security-key`: A portable FIDO2 authenticator capable of being used on multiple devices via a USB or NFC connection + * - `client-device`: The device that WebAuthn is being called on. Typically synonymous with platform authenticators + * + * These values are less strict than `authenticatorAttachment` + * + * @see {@link https://w3c.github.io/webauthn/#enumdef-publickeycredentialhint W3C WebAuthn Spec - PublicKeyCredentialHint} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions#hints MDN - hints} + */ +export type PublicKeyCredentialHint = 'hybrid' | 'security-key' | 'client-device'; +/** + * Values for an attestation object's `fmt`. + * Defines the format of the attestation statement from the authenticator. + * + * @see {@link https://www.iana.org/assignments/webauthn/webauthn.xhtml#webauthn-attestation-statement-format-ids IANA - WebAuthn Attestation Statement Format Identifiers} + * @see {@link https://w3c.github.io/webauthn/#sctn-attestation-formats W3C WebAuthn Spec - Attestation Statement Formats} + */ +export type AttestationFormat = 'fido-u2f' | 'packed' | 'android-safetynet' | 'android-key' | 'tpm' | 'apple' | 'none'; +/** + * Equivalent to `Uint8Array` before TypeScript 5.7, and `Uint8Array` in TypeScript 5.7 + * and beyond. + * + * **Context** + * + * `Uint8Array` became a generic type in TypeScript 5.7, requiring types defined simply as + * `Uint8Array` to be refactored to `Uint8Array` starting in Deno 2.2. `Uint8Array` is + * _not_ generic in Deno 2.1.x and earlier, though, so this type helps bridge this gap. + * + * Inspired by Deno's std library: + * + * https://github.com/denoland/std/blob/b5a5fe4f96b91c1fe8dba5cc0270092dd11d3287/bytes/_types.ts#L11 + */ +export type Uint8Array_ = ReturnType; +/** + * Specifies the preferred authenticator attachment modality. + * - `platform`: A platform authenticator attached to the client device (e.g., Touch ID, Windows Hello) + * - `cross-platform`: A roaming authenticator not attached to the client device (e.g., USB security key) + * + * @see {@link https://w3c.github.io/webauthn/#enum-attachment W3C WebAuthn Spec - AuthenticatorAttachment} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions/authenticatorSelection#authenticatorattachment MDN - authenticatorAttachment} + */ +export type AuthenticatorAttachment = 'cross-platform' | 'platform'; +//# sourceMappingURL=webauthn.dom.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/webauthn.dom.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/module/lib/webauthn.dom.d.ts.map new file mode 100644 index 0000000..d9d3aeb --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/webauthn.dom.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"webauthn.dom.d.ts","sourceRoot":"","sources":["../../../src/lib/webauthn.dom.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AAEpC;;;;;;;;GAQG;AACH,MAAM,WAAW,sCAAsC;IACrD;;;OAGG;IACH,EAAE,EAAE,2BAA2B,CAAA;IAC/B;;;OAGG;IACH,IAAI,EAAE,iCAAiC,CAAA;IACvC;;;OAGG;IACH,SAAS,EAAE,eAAe,CAAA;IAC1B;;;OAGG;I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GAAG,cAAc,GAAG,eAAe,CAAA;AAEjF;;;;;;GAMG;AACH,MAAM,MAAM,iBAAiB,GACzB,UAAU,GACV,QAAQ,GACR,mBAAmB,GACnB,aAAa,GACb,KAAK,GACL,OAAO,GACP,MAAM,CAAA;AAEV;;;;;;;;;;;;;GAaG;AACH,MAAM,MAAM,WAAW,GAAG,UAAU,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAA;AAEzD;;;;;;;GAOG;AACH,MAAM,MAAM,uBAAuB,GAAG,gBAAgB,GAAG,UAAU,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/webauthn.dom.js b/backend/node_modules/@supabase/auth-js/dist/module/lib/webauthn.dom.js new file mode 100644 index 0000000..0c67551 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/webauthn.dom.js @@ -0,0 +1,3 @@ +// from https://github.com/MasterKale/SimpleWebAuthn/blob/master/packages/browser/src/types/index.ts +export {}; +//# sourceMappingURL=webauthn.dom.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/webauthn.dom.js.map b/backend/node_modules/@supabase/auth-js/dist/module/lib/webauthn.dom.js.map new file mode 100644 index 0000000..9def322 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/webauthn.dom.js.map @@ -0,0 +1 @@ +{"version":3,"file":"webauthn.dom.js","sourceRoot":"","sources":["../../../src/lib/webauthn.dom.ts"],"names":[],"mappings":"AAAA,oGAAoG"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/webauthn.errors.d.ts b/backend/node_modules/@supabase/auth-js/dist/module/lib/webauthn.errors.d.ts new file mode 100644 index 0000000..5fe8218 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/webauthn.errors.d.ts @@ -0,0 +1,80 @@ +import { StrictOmit } from './types'; +import { PublicKeyCredentialCreationOptionsFuture, PublicKeyCredentialRequestOptionsFuture } from './webauthn.dom'; +/** + * A custom Error used to return a more nuanced error detailing _why_ one of the eight documented + * errors in the spec was raised after calling `navigator.credentials.create()` or + * `navigator.credentials.get()`: + * + * - `AbortError` + * - `ConstraintError` + * - `InvalidStateError` + * - `NotAllowedError` + * - `NotSupportedError` + * - `SecurityError` + * - `TypeError` + * - `UnknownError` + * + * Error messages were determined through investigation of the spec to determine under which + * scenarios a given error would be raised. + */ +export declare class WebAuthnError extends Error { + code: WebAuthnErrorCode; + protected __isWebAuthnError: boolean; + constructor({ message, code, cause, name, }: { + message: string; + code: WebAuthnErrorCode; + cause?: Error | unknown; + name?: string; + }); +} +/** + * Error class for unknown WebAuthn errors. + * Wraps unexpected errors that don't match known WebAuthn error conditions. + */ +export declare class WebAuthnUnknownError extends WebAuthnError { + originalError: unknown; + constructor(message: string, originalError: unknown); +} +/** + * Type guard to check if an error is a WebAuthnError. + * @param {unknown} error - The error to check + * @returns {boolean} True if the error is a WebAuthnError + */ +export declare function isWebAuthnError(error: unknown): error is WebAuthnError; +/** + * Error codes for WebAuthn operations. + * These codes provide specific information about why a WebAuthn ceremony failed. + * @see {@link https://w3c.github.io/webauthn/#sctn-defined-errors W3C WebAuthn Spec - Defined Errors} + */ +export type WebAuthnErrorCode = 'ERROR_CEREMONY_ABORTED' | 'ERROR_INVALID_DOMAIN' | 'ERROR_INVALID_RP_ID' | 'ERROR_INVALID_USER_ID_LENGTH' | 'ERROR_MALFORMED_PUBKEYCREDPARAMS' | 'ERROR_AUTHENTICATOR_GENERAL_ERROR' | 'ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT' | 'ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT' | 'ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED' | 'ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG' | 'ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE' | 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY'; +/** + * Attempt to intuit _why_ an error was raised after calling `navigator.credentials.create()`. + * Maps browser errors to specific WebAuthn error codes for better debugging. + * @param {Object} params - Error identification parameters + * @param {Error} params.error - The error thrown by the browser + * @param {CredentialCreationOptions} params.options - The options passed to credentials.create() + * @returns {WebAuthnError} A WebAuthnError with a specific error code + * @see {@link https://w3c.github.io/webauthn/#sctn-createCredential W3C WebAuthn Spec - Create Credential} + */ +export declare function identifyRegistrationError({ error, options, }: { + error: Error; + options: StrictOmit & { + publicKey: PublicKeyCredentialCreationOptionsFuture; + }; +}): WebAuthnError; +/** + * Attempt to intuit _why_ an error was raised after calling `navigator.credentials.get()`. + * Maps browser errors to specific WebAuthn error codes for better debugging. + * @param {Object} params - Error identification parameters + * @param {Error} params.error - The error thrown by the browser + * @param {CredentialRequestOptions} params.options - The options passed to credentials.get() + * @returns {WebAuthnError} A WebAuthnError with a specific error code + * @see {@link https://w3c.github.io/webauthn/#sctn-getAssertion W3C WebAuthn Spec - Get Assertion} + */ +export declare function identifyAuthenticationError({ error, options, }: { + error: Error; + options: StrictOmit & { + publicKey: PublicKeyCredentialRequestOptionsFuture; + }; +}): WebAuthnError; +//# sourceMappingURL=webauthn.errors.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/webauthn.errors.d.ts.map b/backend/node_modules/@supabase/auth-js/dist/module/lib/webauthn.errors.d.ts.map new file mode 100644 index 0000000..0c057a6 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/webauthn.errors.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"webauthn.errors.d.ts","sourceRoot":"","sources":["../../../src/lib/webauthn.errors.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AAEpC,OAAO,EACL,wCAAwC,EACxC,uCAAuC,EACxC,MAAM,gBAAgB,CAAA;AAEvB;;;;;;;;;;;;;;;;GAgBG;AACH,qBAAa,aAAc,SAAQ,KAAK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file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/webauthn.errors.js b/backend/node_modules/@supabase/auth-js/dist/module/lib/webauthn.errors.js new file mode 100644 index 0000000..029b6fe --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/webauthn.errors.js @@ -0,0 +1,257 @@ +/* eslint-disable @typescript-eslint/ban-ts-comment */ +import { isValidDomain } from './webauthn'; +/** + * A custom Error used to return a more nuanced error detailing _why_ one of the eight documented + * errors in the spec was raised after calling `navigator.credentials.create()` or + * `navigator.credentials.get()`: + * + * - `AbortError` + * - `ConstraintError` + * - `InvalidStateError` + * - `NotAllowedError` + * - `NotSupportedError` + * - `SecurityError` + * - `TypeError` + * - `UnknownError` + * + * Error messages were determined through investigation of the spec to determine under which + * scenarios a given error would be raised. + */ +export class WebAuthnError extends Error { + constructor({ message, code, cause, name, }) { + var _a; + // @ts-ignore: help Rollup understand that `cause` is okay to set + super(message, { cause }); + this.__isWebAuthnError = true; + this.name = (_a = name !== null && name !== void 0 ? name : (cause instanceof Error ? cause.name : undefined)) !== null && _a !== void 0 ? _a : 'Unknown Error'; + this.code = code; + } +} +/** + * Error class for unknown WebAuthn errors. + * Wraps unexpected errors that don't match known WebAuthn error conditions. + */ +export class WebAuthnUnknownError extends WebAuthnError { + constructor(message, originalError) { + super({ + code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY', + cause: originalError, + message, + }); + this.name = 'WebAuthnUnknownError'; + this.originalError = originalError; + } +} +/** + * Type guard to check if an error is a WebAuthnError. + * @param {unknown} error - The error to check + * @returns {boolean} True if the error is a WebAuthnError + */ +export function isWebAuthnError(error) { + return typeof error === 'object' && error !== null && '__isWebAuthnError' in error; +} +/** + * Attempt to intuit _why_ an error was raised after calling `navigator.credentials.create()`. + * Maps browser errors to specific WebAuthn error codes for better debugging. + * @param {Object} params - Error identification parameters + * @param {Error} params.error - The error thrown by the browser + * @param {CredentialCreationOptions} params.options - The options passed to credentials.create() + * @returns {WebAuthnError} A WebAuthnError with a specific error code + * @see {@link https://w3c.github.io/webauthn/#sctn-createCredential W3C WebAuthn Spec - Create Credential} + */ +export function identifyRegistrationError({ error, options, }) { + var _a, _b, _c; + const { publicKey } = options; + if (!publicKey) { + throw Error('options was missing required publicKey property'); + } + if (error.name === 'AbortError') { + if (options.signal instanceof AbortSignal) { + // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 16) + return new WebAuthnError({ + message: 'Registration ceremony was sent an abort signal', + code: 'ERROR_CEREMONY_ABORTED', + cause: error, + }); + } + } + else if (error.name === 'ConstraintError') { + if (((_a = publicKey.authenticatorSelection) === null || _a === void 0 ? void 0 : _a.requireResidentKey) === true) { + // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 4) + return new WebAuthnError({ + message: 'Discoverable credentials were required but no available authenticator supported it', + code: 'ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT', + cause: error, + }); + } + else if ( + // @ts-ignore: `mediation` doesn't yet exist on CredentialCreationOptions but it's possible as of Sept 2024 + options.mediation === 'conditional' && + ((_b = publicKey.authenticatorSelection) === null || _b === void 0 ? void 0 : _b.userVerification) === 'required') { + // https://w3c.github.io/webauthn/#sctn-createCredential (Step 22.4) + return new WebAuthnError({ + message: 'User verification was required during automatic registration but it could not be performed', + code: 'ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE', + cause: error, + }); + } + else if (((_c = publicKey.authenticatorSelection) === null || _c === void 0 ? void 0 : _c.userVerification) === 'required') { + // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 5) + return new WebAuthnError({ + message: 'User verification was required but no available authenticator supported it', + code: 'ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT', + cause: error, + }); + } + } + else if (error.name === 'InvalidStateError') { + // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 20) + // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 3) + return new WebAuthnError({ + message: 'The authenticator was previously registered', + code: 'ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED', + cause: error, + }); + } + else if (error.name === 'NotAllowedError') { + /** + * Pass the error directly through. Platforms are overloading this error beyond what the spec + * defines and we don't want to overwrite potentially useful error messages. + */ + return new WebAuthnError({ + message: error.message, + code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY', + cause: error, + }); + } + else if (error.name === 'NotSupportedError') { + const validPubKeyCredParams = publicKey.pubKeyCredParams.filter((param) => param.type === 'public-key'); + if (validPubKeyCredParams.length === 0) { + // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 10) + return new WebAuthnError({ + message: 'No entry in pubKeyCredParams was of type "public-key"', + code: 'ERROR_MALFORMED_PUBKEYCREDPARAMS', + cause: error, + }); + } + // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 2) + return new WebAuthnError({ + message: 'No available authenticator supported any of the specified pubKeyCredParams algorithms', + code: 'ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG', + cause: error, + }); + } + else if (error.name === 'SecurityError') { + const effectiveDomain = window.location.hostname; + if (!isValidDomain(effectiveDomain)) { + // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 7) + return new WebAuthnError({ + message: `${window.location.hostname} is an invalid domain`, + code: 'ERROR_INVALID_DOMAIN', + cause: error, + }); + } + else if (publicKey.rp.id !== effectiveDomain) { + // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 8) + return new WebAuthnError({ + message: `The RP ID "${publicKey.rp.id}" is invalid for this domain`, + code: 'ERROR_INVALID_RP_ID', + cause: error, + }); + } + } + else if (error.name === 'TypeError') { + if (publicKey.user.id.byteLength < 1 || publicKey.user.id.byteLength > 64) { + // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 5) + return new WebAuthnError({ + message: 'User ID was not between 1 and 64 characters', + code: 'ERROR_INVALID_USER_ID_LENGTH', + cause: error, + }); + } + } + else if (error.name === 'UnknownError') { + // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 1) + // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 8) + return new WebAuthnError({ + message: 'The authenticator was unable to process the specified options, or could not create a new credential', + code: 'ERROR_AUTHENTICATOR_GENERAL_ERROR', + cause: error, + }); + } + return new WebAuthnError({ + message: 'a Non-Webauthn related error has occurred', + code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY', + cause: error, + }); +} +/** + * Attempt to intuit _why_ an error was raised after calling `navigator.credentials.get()`. + * Maps browser errors to specific WebAuthn error codes for better debugging. + * @param {Object} params - Error identification parameters + * @param {Error} params.error - The error thrown by the browser + * @param {CredentialRequestOptions} params.options - The options passed to credentials.get() + * @returns {WebAuthnError} A WebAuthnError with a specific error code + * @see {@link https://w3c.github.io/webauthn/#sctn-getAssertion W3C WebAuthn Spec - Get Assertion} + */ +export function identifyAuthenticationError({ error, options, }) { + const { publicKey } = options; + if (!publicKey) { + throw Error('options was missing required publicKey property'); + } + if (error.name === 'AbortError') { + if (options.signal instanceof AbortSignal) { + // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 16) + return new WebAuthnError({ + message: 'Authentication ceremony was sent an abort signal', + code: 'ERROR_CEREMONY_ABORTED', + cause: error, + }); + } + } + else if (error.name === 'NotAllowedError') { + /** + * Pass the error directly through. Platforms are overloading this error beyond what the spec + * defines and we don't want to overwrite potentially useful error messages. + */ + return new WebAuthnError({ + message: error.message, + code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY', + cause: error, + }); + } + else if (error.name === 'SecurityError') { + const effectiveDomain = window.location.hostname; + if (!isValidDomain(effectiveDomain)) { + // https://www.w3.org/TR/webauthn-2/#sctn-discover-from-external-source (Step 5) + return new WebAuthnError({ + message: `${window.location.hostname} is an invalid domain`, + code: 'ERROR_INVALID_DOMAIN', + cause: error, + }); + } + else if (publicKey.rpId !== effectiveDomain) { + // https://www.w3.org/TR/webauthn-2/#sctn-discover-from-external-source (Step 6) + return new WebAuthnError({ + message: `The RP ID "${publicKey.rpId}" is invalid for this domain`, + code: 'ERROR_INVALID_RP_ID', + cause: error, + }); + } + } + else if (error.name === 'UnknownError') { + // https://www.w3.org/TR/webauthn-2/#sctn-op-get-assertion (Step 1) + // https://www.w3.org/TR/webauthn-2/#sctn-op-get-assertion (Step 12) + return new WebAuthnError({ + message: 'The authenticator was unable to process the specified options, or could not create a new assertion signature', + code: 'ERROR_AUTHENTICATOR_GENERAL_ERROR', + cause: error, + }); + } + return new WebAuthnError({ + message: 'a Non-Webauthn related error has occurred', + code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY', + cause: error, + }); +} +//# sourceMappingURL=webauthn.errors.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/webauthn.errors.js.map b/backend/node_modules/@supabase/auth-js/dist/module/lib/webauthn.errors.js.map new file mode 100644 index 0000000..27f1b76 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/webauthn.errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"webauthn.errors.js","sourceRoot":"","sources":["../../../src/lib/webauthn.errors.ts"],"names":[],"mappings":"AAAA,sDAAsD;AAGtD,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAM1C;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,OAAO,aAAc,SAAQ,KAAK;IAKtC,YAAY,EACV,OAAO,EACP,IAAI,EACJ,KAAK,EACL,IAAI,GAML;;QACC,iEAAiE;QACjE,KAAK,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,CAAC,CAAA;QAdjB,sBAAiB,GAAG,IAAI,CAAA;QAehC,IAAI,CAAC,IAAI,GAAG,MAAA,IAAI,aAAJ,IAAI,cAAJ,IAAI,GAAI,CAAC,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,mCAAI,eAAe,CAAA;QACxF,IAAI,CAAC,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AC;QAC1C,MAAM,eAAe,GAAG,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAA;QAChD,IAAI,CAAC,aAAa,CAAC,eAAe,CAAC,EAAE,CAAC;YACpC,gFAAgF;YAChF,OAAO,IAAI,aAAa,CAAC;gBACvB,OAAO,EAAE,GAAG,MAAM,CAAC,QAAQ,CAAC,QAAQ,uBAAuB;gBAC3D,IAAI,EAAE,sBAAsB;gBAC5B,KAAK,EAAE,KAAK;aACb,CAAC,CAAA;QACJ,CAAC;aAAM,IAAI,SAAS,CAAC,IAAI,KAAK,eAAe,EAAE,CAAC;YAC9C,gFAAgF;YAChF,OAAO,IAAI,aAAa,CAAC;gBACvB,OAAO,EAAE,cAAc,SAAS,CAAC,IAAI,8BAA8B;gBACnE,IAAI,EAAE,qBAAqB;gBAC3B,KAAK,EAAE,KAAK;aACb,CAAC,CAAA;QACJ,CAAC;IACH,CAAC;SAAM,IAAI,KAAK,CAAC,IAAI,KAAK,cAAc,EAAE,CAAC;QACzC,mEAAmE;QACnE,oEAAoE;QACpE,OAAO,IAAI,aAAa,CAAC;YACvB,OAAO,EACL,8GAA8G;YAChH,IAAI,EAAE,mCAAmC;YACzC,KAAK,EAAE,KAAK;SACb,CAAC,CAAA;IACJ,CAAC;IAED,OAAO,IAAI,aAAa,CAAC;QACvB,OAAO,EAAE,2CAA2C;QACpD,IAAI,EAAE,sCAAsC;QAC5C,KAAK,EAAE,KAAK;KACb,CAAC,CAAA;AACJ,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/webauthn.js b/backend/node_modules/@supabase/auth-js/dist/module/lib/webauthn.js new file mode 100644 index 0000000..60d3dff --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/webauthn.js @@ -0,0 +1,676 @@ +import { __rest } from "tslib"; +import { base64UrlToUint8Array, bytesToBase64URL } from './base64url'; +import { AuthError, AuthUnknownError, isAuthError } from './errors'; +import { isBrowser } from './helpers'; +import { identifyAuthenticationError, identifyRegistrationError, isWebAuthnError, WebAuthnError, WebAuthnUnknownError, } from './webauthn.errors'; +export { WebAuthnError, isWebAuthnError, identifyRegistrationError, identifyAuthenticationError }; +/** + * WebAuthn abort service to manage ceremony cancellation. + * Ensures only one WebAuthn ceremony is active at a time to prevent "operation already in progress" errors. + * + * @experimental This class is experimental and may change in future releases + * @see {@link https://w3c.github.io/webauthn/#sctn-automation-webdriver-capability W3C WebAuthn Spec - Aborting Ceremonies} + */ +export class WebAuthnAbortService { + /** + * Create an abort signal for a new WebAuthn operation. + * Automatically cancels any existing operation. + * + * @returns {AbortSignal} Signal to pass to navigator.credentials.create() or .get() + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal MDN - AbortSignal} + */ + createNewAbortSignal() { + // Abort any existing calls to navigator.credentials.create() or navigator.credentials.get() + if (this.controller) { + const abortError = new Error('Cancelling existing WebAuthn API call for new one'); + abortError.name = 'AbortError'; + this.controller.abort(abortError); + } + const newController = new AbortController(); + this.controller = newController; + return newController.signal; + } + /** + * Manually cancel the current WebAuthn operation. + * Useful for cleaning up when user cancels or navigates away. + * + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort MDN - AbortController.abort} + */ + cancelCeremony() { + if (this.controller) { + const abortError = new Error('Manually cancelling existing WebAuthn API call'); + abortError.name = 'AbortError'; + this.controller.abort(abortError); + this.controller = undefined; + } + } +} +/** + * Singleton instance to ensure only one WebAuthn ceremony is active at a time. + * This prevents "operation already in progress" errors when retrying WebAuthn operations. + * + * @experimental This instance is experimental and may change in future releases + */ +export const webAuthnAbortService = new WebAuthnAbortService(); +/** + * Convert base64url encoded strings in WebAuthn credential creation options to ArrayBuffers + * as required by the WebAuthn browser API. + * Supports both native WebAuthn Level 3 parseCreationOptionsFromJSON and manual fallback. + * + * @param {ServerCredentialCreationOptions} options - JSON options from server with base64url encoded fields + * @returns {PublicKeyCredentialCreationOptionsFuture} Options ready for navigator.credentials.create() + * @see {@link https://w3c.github.io/webauthn/#sctn-parseCreationOptionsFromJSON W3C WebAuthn Spec - parseCreationOptionsFromJSON} + */ +export function deserializeCredentialCreationOptions(options) { + if (!options) { + throw new Error('Credential creation options are required'); + } + // Check if the native parseCreationOptionsFromJSON method is available + if (typeof PublicKeyCredential !== 'undefined' && + 'parseCreationOptionsFromJSON' in PublicKeyCredential && + typeof PublicKeyCredential + .parseCreationOptionsFromJSON === 'function') { + // Use the native WebAuthn Level 3 method + return PublicKeyCredential.parseCreationOptionsFromJSON( + /** we assert the options here as typescript still doesn't know about future webauthn types */ + options); + } + // Fallback to manual parsing for browsers that don't support the native method + // Destructure to separate fields that need transformation + const { challenge: challengeStr, user: userOpts, excludeCredentials } = options, restOptions = __rest(options + // Convert challenge from base64url to ArrayBuffer + , ["challenge", "user", "excludeCredentials"]); + // Convert challenge from base64url to ArrayBuffer + const challenge = base64UrlToUint8Array(challengeStr).buffer; + // Convert user.id from base64url to ArrayBuffer + const user = Object.assign(Object.assign({}, userOpts), { id: base64UrlToUint8Array(userOpts.id).buffer }); + // Build the result object + const result = Object.assign(Object.assign({}, restOptions), { challenge, + user }); + // Only add excludeCredentials if it exists + if (excludeCredentials && excludeCredentials.length > 0) { + result.excludeCredentials = new Array(excludeCredentials.length); + for (let i = 0; i < excludeCredentials.length; i++) { + const cred = excludeCredentials[i]; + result.excludeCredentials[i] = Object.assign(Object.assign({}, cred), { id: base64UrlToUint8Array(cred.id).buffer, type: cred.type || 'public-key', + // Cast transports to handle future transport types like "cable" + transports: cred.transports }); + } + } + return result; +} +/** + * Convert base64url encoded strings in WebAuthn credential request options to ArrayBuffers + * as required by the WebAuthn browser API. + * Supports both native WebAuthn Level 3 parseRequestOptionsFromJSON and manual fallback. + * + * @param {ServerCredentialRequestOptions} options - JSON options from server with base64url encoded fields + * @returns {PublicKeyCredentialRequestOptionsFuture} Options ready for navigator.credentials.get() + * @see {@link https://w3c.github.io/webauthn/#sctn-parseRequestOptionsFromJSON W3C WebAuthn Spec - parseRequestOptionsFromJSON} + */ +export function deserializeCredentialRequestOptions(options) { + if (!options) { + throw new Error('Credential request options are required'); + } + // Check if the native parseRequestOptionsFromJSON method is available + if (typeof PublicKeyCredential !== 'undefined' && + 'parseRequestOptionsFromJSON' in PublicKeyCredential && + typeof PublicKeyCredential + .parseRequestOptionsFromJSON === 'function') { + // Use the native WebAuthn Level 3 method + return PublicKeyCredential.parseRequestOptionsFromJSON(options); + } + // Fallback to manual parsing for browsers that don't support the native method + // Destructure to separate fields that need transformation + const { challenge: challengeStr, allowCredentials } = options, restOptions = __rest(options + // Convert challenge from base64url to ArrayBuffer + , ["challenge", "allowCredentials"]); + // Convert challenge from base64url to ArrayBuffer + const challenge = base64UrlToUint8Array(challengeStr).buffer; + // Build the result object + const result = Object.assign(Object.assign({}, restOptions), { challenge }); + // Only add allowCredentials if it exists + if (allowCredentials && allowCredentials.length > 0) { + result.allowCredentials = new Array(allowCredentials.length); + for (let i = 0; i < allowCredentials.length; i++) { + const cred = allowCredentials[i]; + result.allowCredentials[i] = Object.assign(Object.assign({}, cred), { id: base64UrlToUint8Array(cred.id).buffer, type: cred.type || 'public-key', + // Cast transports to handle future transport types like "cable" + transports: cred.transports }); + } + } + return result; +} +/** + * Convert a registration/enrollment credential response to server format. + * Serializes binary fields to base64url for JSON transmission. + * Supports both native WebAuthn Level 3 toJSON and manual fallback. + * + * @param {RegistrationCredential} credential - Credential from navigator.credentials.create() + * @returns {RegistrationResponseJSON} JSON-serializable credential for server + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-tojson W3C WebAuthn Spec - toJSON} + */ +export function serializeCredentialCreationResponse(credential) { + var _a; + // Check if the credential instance has the toJSON method + if ('toJSON' in credential && typeof credential.toJSON === 'function') { + // Use the native WebAuthn Level 3 method + return credential.toJSON(); + } + const credentialWithAttachment = credential; + return { + id: credential.id, + rawId: credential.id, + response: { + attestationObject: bytesToBase64URL(new Uint8Array(credential.response.attestationObject)), + clientDataJSON: bytesToBase64URL(new Uint8Array(credential.response.clientDataJSON)), + }, + type: 'public-key', + clientExtensionResults: credential.getClientExtensionResults(), + // Convert null to undefined and cast to AuthenticatorAttachment type + authenticatorAttachment: ((_a = credentialWithAttachment.authenticatorAttachment) !== null && _a !== void 0 ? _a : undefined), + }; +} +/** + * Convert an authentication/verification credential response to server format. + * Serializes binary fields to base64url for JSON transmission. + * Supports both native WebAuthn Level 3 toJSON and manual fallback. + * + * @param {AuthenticationCredential} credential - Credential from navigator.credentials.get() + * @returns {AuthenticationResponseJSON} JSON-serializable credential for server + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-tojson W3C WebAuthn Spec - toJSON} + */ +export function serializeCredentialRequestResponse(credential) { + var _a; + // Check if the credential instance has the toJSON method + if ('toJSON' in credential && typeof credential.toJSON === 'function') { + // Use the native WebAuthn Level 3 method + return credential.toJSON(); + } + // Fallback to manual conversion for browsers that don't support toJSON + // Access authenticatorAttachment via type assertion to handle TypeScript version differences + // @simplewebauthn/types includes this property but base TypeScript 4.7.4 doesn't + const credentialWithAttachment = credential; + const clientExtensionResults = credential.getClientExtensionResults(); + const assertionResponse = credential.response; + return { + id: credential.id, + rawId: credential.id, // W3C spec expects rawId to match id for JSON format + response: { + authenticatorData: bytesToBase64URL(new Uint8Array(assertionResponse.authenticatorData)), + clientDataJSON: bytesToBase64URL(new Uint8Array(assertionResponse.clientDataJSON)), + signature: bytesToBase64URL(new Uint8Array(assertionResponse.signature)), + userHandle: assertionResponse.userHandle + ? bytesToBase64URL(new Uint8Array(assertionResponse.userHandle)) + : undefined, + }, + type: 'public-key', + clientExtensionResults, + // Convert null to undefined and cast to AuthenticatorAttachment type + authenticatorAttachment: ((_a = credentialWithAttachment.authenticatorAttachment) !== null && _a !== void 0 ? _a : undefined), + }; +} +/** + * A simple test to determine if a hostname is a properly-formatted domain name. + * Considers localhost valid for development environments. + * + * A "valid domain" is defined here: https://url.spec.whatwg.org/#valid-domain + * + * Regex sourced from here: + * https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch08s15.html + * + * @param {string} hostname - The hostname to validate + * @returns {boolean} True if valid domain or localhost + * @see {@link https://url.spec.whatwg.org/#valid-domain WHATWG URL Spec - Valid Domain} + */ +export function isValidDomain(hostname) { + return ( + // Consider localhost valid as well since it's okay wrt Secure Contexts + hostname === 'localhost' || /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(hostname)); +} +/** + * Determine if the browser is capable of WebAuthn. + * Checks for necessary Web APIs: PublicKeyCredential and Credential Management. + * + * @returns {boolean} True if browser supports WebAuthn + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredential#browser_compatibility MDN - PublicKeyCredential Browser Compatibility} + */ +function browserSupportsWebAuthn() { + var _a, _b; + return !!(isBrowser() && + 'PublicKeyCredential' in window && + window.PublicKeyCredential && + 'credentials' in navigator && + typeof ((_a = navigator === null || navigator === void 0 ? void 0 : navigator.credentials) === null || _a === void 0 ? void 0 : _a.create) === 'function' && + typeof ((_b = navigator === null || navigator === void 0 ? void 0 : navigator.credentials) === null || _b === void 0 ? void 0 : _b.get) === 'function'); +} +/** + * Create a WebAuthn credential using the browser's credentials API. + * Wraps navigator.credentials.create() with error handling. + * + * @param {CredentialCreationOptions} options - Options including publicKey parameters + * @returns {Promise>} Created credential or error + * @see {@link https://w3c.github.io/webauthn/#sctn-createCredential W3C WebAuthn Spec - Create Credential} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/create MDN - credentials.create} + */ +export async function createCredential(options) { + try { + const response = await navigator.credentials.create( + /** we assert the type here until typescript types are updated */ + options); + if (!response) { + return { + data: null, + error: new WebAuthnUnknownError('Empty credential response', response), + }; + } + if (!(response instanceof PublicKeyCredential)) { + return { + data: null, + error: new WebAuthnUnknownError('Browser returned unexpected credential type', response), + }; + } + return { data: response, error: null }; + } + catch (err) { + return { + data: null, + error: identifyRegistrationError({ + error: err, + options, + }), + }; + } +} +/** + * Get a WebAuthn credential using the browser's credentials API. + * Wraps navigator.credentials.get() with error handling. + * + * @param {CredentialRequestOptions} options - Options including publicKey parameters + * @returns {Promise>} Retrieved credential or error + * @see {@link https://w3c.github.io/webauthn/#sctn-getAssertion W3C WebAuthn Spec - Get Assertion} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/get MDN - credentials.get} + */ +export async function getCredential(options) { + try { + const response = await navigator.credentials.get( + /** we assert the type here until typescript types are updated */ + options); + if (!response) { + return { + data: null, + error: new WebAuthnUnknownError('Empty credential response', response), + }; + } + if (!(response instanceof PublicKeyCredential)) { + return { + data: null, + error: new WebAuthnUnknownError('Browser returned unexpected credential type', response), + }; + } + return { data: response, error: null }; + } + catch (err) { + return { + data: null, + error: identifyAuthenticationError({ + error: err, + options, + }), + }; + } +} +export const DEFAULT_CREATION_OPTIONS = { + hints: ['security-key'], + authenticatorSelection: { + authenticatorAttachment: 'cross-platform', + requireResidentKey: false, + /** set to preferred because older yubikeys don't have PIN/Biometric */ + userVerification: 'preferred', + residentKey: 'discouraged', + }, + attestation: 'direct', +}; +export const DEFAULT_REQUEST_OPTIONS = { + /** set to preferred because older yubikeys don't have PIN/Biometric */ + userVerification: 'preferred', + hints: ['security-key'], + attestation: 'direct', +}; +function deepMerge(...sources) { + const isObject = (val) => val !== null && typeof val === 'object' && !Array.isArray(val); + const isArrayBufferLike = (val) => val instanceof ArrayBuffer || ArrayBuffer.isView(val); + const result = {}; + for (const source of sources) { + if (!source) + continue; + for (const key in source) { + const value = source[key]; + if (value === undefined) + continue; + if (Array.isArray(value)) { + // preserve array reference, including unions like AuthenticatorTransport[] + result[key] = value; + } + else if (isArrayBufferLike(value)) { + result[key] = value; + } + else if (isObject(value)) { + const existing = result[key]; + if (isObject(existing)) { + result[key] = deepMerge(existing, value); + } + else { + result[key] = deepMerge(value); + } + } + else { + result[key] = value; + } + } + } + return result; +} +/** + * Merges WebAuthn credential creation options with overrides. + * Sets sensible defaults for authenticator selection and extensions. + * + * @param {PublicKeyCredentialCreationOptionsFuture} baseOptions - The base options from the server + * @param {PublicKeyCredentialCreationOptionsFuture} overrides - Optional overrides to apply + * @param {string} friendlyName - Optional friendly name for the credential + * @returns {PublicKeyCredentialCreationOptionsFuture} Merged credential creation options + * @see {@link https://w3c.github.io/webauthn/#dictdef-authenticatorselectioncriteria W3C WebAuthn Spec - AuthenticatorSelectionCriteria} + */ +export function mergeCredentialCreationOptions(baseOptions, overrides) { + return deepMerge(DEFAULT_CREATION_OPTIONS, baseOptions, overrides || {}); +} +/** + * Merges WebAuthn credential request options with overrides. + * Sets sensible defaults for user verification and hints. + * + * @param {PublicKeyCredentialRequestOptionsFuture} baseOptions - The base options from the server + * @param {PublicKeyCredentialRequestOptionsFuture} overrides - Optional overrides to apply + * @returns {PublicKeyCredentialRequestOptionsFuture} Merged credential request options + * @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialrequestoptions W3C WebAuthn Spec - PublicKeyCredentialRequestOptions} + */ +export function mergeCredentialRequestOptions(baseOptions, overrides) { + return deepMerge(DEFAULT_REQUEST_OPTIONS, baseOptions, overrides || {}); +} +/** + * WebAuthn API wrapper for Supabase Auth. + * Provides methods for enrolling, challenging, verifying, authenticating, and registering WebAuthn credentials. + * + * @experimental This API is experimental and may change in future releases + * @see {@link https://w3c.github.io/webauthn/ W3C WebAuthn Specification} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API MDN - Web Authentication API} + */ +export class WebAuthnApi { + constructor(client) { + this.client = client; + // Bind all methods so they can be destructured + this.enroll = this._enroll.bind(this); + this.challenge = this._challenge.bind(this); + this.verify = this._verify.bind(this); + this.authenticate = this._authenticate.bind(this); + this.register = this._register.bind(this); + } + /** + * Enroll a new WebAuthn factor. + * Creates an unverified WebAuthn factor that must be verified with a credential. + * + * @experimental This method is experimental and may change in future releases + * @param {Omit} params - Enrollment parameters (friendlyName required) + * @returns {Promise} Enrolled factor details or error + * @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registering a New Credential} + */ + async _enroll(params) { + return this.client.mfa.enroll(Object.assign(Object.assign({}, params), { factorType: 'webauthn' })); + } + /** + * Challenge for WebAuthn credential creation or authentication. + * Combines server challenge with browser credential operations. + * Handles both registration (create) and authentication (request) flows. + * + * @experimental This method is experimental and may change in future releases + * @param {MFAChallengeWebauthnParams & { friendlyName?: string; signal?: AbortSignal }} params - Challenge parameters including factorId + * @param {Object} overrides - Allows you to override the parameters passed to navigator.credentials + * @param {PublicKeyCredentialCreationOptionsFuture} overrides.create - Override options for credential creation + * @param {PublicKeyCredentialRequestOptionsFuture} overrides.request - Override options for credential request + * @returns {Promise} Challenge response with credential or error + * @see {@link https://w3c.github.io/webauthn/#sctn-credential-creation W3C WebAuthn Spec - Credential Creation} + * @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying Assertion} + */ + async _challenge({ factorId, webauthn, friendlyName, signal, }, overrides) { + try { + // Get challenge from server using the client's MFA methods + const { data: challengeResponse, error: challengeError } = await this.client.mfa.challenge({ + factorId, + webauthn, + }); + if (!challengeResponse) { + return { data: null, error: challengeError }; + } + const abortSignal = signal !== null && signal !== void 0 ? signal : webAuthnAbortService.createNewAbortSignal(); + /** webauthn will fail if either of the name/displayname are blank */ + if (challengeResponse.webauthn.type === 'create') { + const { user } = challengeResponse.webauthn.credential_options.publicKey; + if (!user.name) { + user.name = `${user.id}:${friendlyName}`; + } + if (!user.displayName) { + user.displayName = user.name; + } + } + switch (challengeResponse.webauthn.type) { + case 'create': { + const options = mergeCredentialCreationOptions(challengeResponse.webauthn.credential_options.publicKey, overrides === null || overrides === void 0 ? void 0 : overrides.create); + const { data, error } = await createCredential({ + publicKey: options, + signal: abortSignal, + }); + if (data) { + return { + data: { + factorId, + challengeId: challengeResponse.id, + webauthn: { + type: challengeResponse.webauthn.type, + credential_response: data, + }, + }, + error: null, + }; + } + return { data: null, error }; + } + case 'request': { + const options = mergeCredentialRequestOptions(challengeResponse.webauthn.credential_options.publicKey, overrides === null || overrides === void 0 ? void 0 : overrides.request); + const { data, error } = await getCredential(Object.assign(Object.assign({}, challengeResponse.webauthn.credential_options), { publicKey: options, signal: abortSignal })); + if (data) { + return { + data: { + factorId, + challengeId: challengeResponse.id, + webauthn: { + type: challengeResponse.webauthn.type, + credential_response: data, + }, + }, + error: null, + }; + } + return { data: null, error }; + } + } + } + catch (error) { + if (isAuthError(error)) { + return { data: null, error }; + } + return { + data: null, + error: new AuthUnknownError('Unexpected error in challenge', error), + }; + } + } + /** + * Verify a WebAuthn credential with the server. + * Completes the WebAuthn ceremony by sending the credential to the server for verification. + * + * @experimental This method is experimental and may change in future releases + * @param {Object} params - Verification parameters + * @param {string} params.challengeId - ID of the challenge being verified + * @param {string} params.factorId - ID of the WebAuthn factor + * @param {MFAVerifyWebauthnParams['webauthn']} params.webauthn - WebAuthn credential response + * @returns {Promise} Verification result with session or error + * @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying an Authentication Assertion} + * */ + async _verify({ challengeId, factorId, webauthn, }) { + return this.client.mfa.verify({ + factorId, + challengeId, + webauthn: webauthn, + }); + } + /** + * Complete WebAuthn authentication flow. + * Performs challenge and verification in a single operation for existing credentials. + * + * @experimental This method is experimental and may change in future releases + * @param {Object} params - Authentication parameters + * @param {string} params.factorId - ID of the WebAuthn factor to authenticate with + * @param {Object} params.webauthn - WebAuthn configuration + * @param {string} params.webauthn.rpId - Relying Party ID (defaults to current hostname) + * @param {string[]} params.webauthn.rpOrigins - Allowed origins (defaults to current origin) + * @param {AbortSignal} params.webauthn.signal - Optional abort signal + * @param {PublicKeyCredentialRequestOptionsFuture} overrides - Override options for navigator.credentials.get + * @returns {Promise>} Authentication result + * @see {@link https://w3c.github.io/webauthn/#sctn-authentication W3C WebAuthn Spec - Authentication Ceremony} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialRequestOptions MDN - PublicKeyCredentialRequestOptions} + */ + async _authenticate({ factorId, webauthn: { rpId = typeof window !== 'undefined' ? window.location.hostname : undefined, rpOrigins = typeof window !== 'undefined' ? [window.location.origin] : undefined, signal, } = {}, }, overrides) { + if (!rpId) { + return { + data: null, + error: new AuthError('rpId is required for WebAuthn authentication'), + }; + } + try { + if (!browserSupportsWebAuthn()) { + return { + data: null, + error: new AuthUnknownError('Browser does not support WebAuthn', null), + }; + } + // Get challenge and credential + const { data: challengeResponse, error: challengeError } = await this.challenge({ + factorId, + webauthn: { rpId, rpOrigins }, + signal, + }, { request: overrides }); + if (!challengeResponse) { + return { data: null, error: challengeError }; + } + const { webauthn } = challengeResponse; + // Verify credential + return this._verify({ + factorId, + challengeId: challengeResponse.challengeId, + webauthn: { + type: webauthn.type, + rpId, + rpOrigins, + credential_response: webauthn.credential_response, + }, + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: null, error }; + } + return { + data: null, + error: new AuthUnknownError('Unexpected error in authenticate', error), + }; + } + } + /** + * Complete WebAuthn registration flow. + * Performs enrollment, challenge, and verification in a single operation for new credentials. + * + * @experimental This method is experimental and may change in future releases + * @param {Object} params - Registration parameters + * @param {string} params.friendlyName - User-friendly name for the credential + * @param {string} params.rpId - Relying Party ID (defaults to current hostname) + * @param {string[]} params.rpOrigins - Allowed origins (defaults to current origin) + * @param {AbortSignal} params.signal - Optional abort signal + * @param {PublicKeyCredentialCreationOptionsFuture} overrides - Override options for navigator.credentials.create + * @returns {Promise>} Registration result + * @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registration Ceremony} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions MDN - PublicKeyCredentialCreationOptions} + */ + async _register({ friendlyName, webauthn: { rpId = typeof window !== 'undefined' ? window.location.hostname : undefined, rpOrigins = typeof window !== 'undefined' ? [window.location.origin] : undefined, signal, } = {}, }, overrides) { + if (!rpId) { + return { + data: null, + error: new AuthError('rpId is required for WebAuthn registration'), + }; + } + try { + if (!browserSupportsWebAuthn()) { + return { + data: null, + error: new AuthUnknownError('Browser does not support WebAuthn', null), + }; + } + // Enroll factor + const { data: factor, error: enrollError } = await this._enroll({ + friendlyName, + }); + if (!factor) { + await this.client.mfa + .listFactors() + .then((factors) => { + var _a; + return (_a = factors.data) === null || _a === void 0 ? void 0 : _a.all.find((v) => v.factor_type === 'webauthn' && + v.friendly_name === friendlyName && + v.status !== 'unverified'); + }) + .then((factor) => (factor ? this.client.mfa.unenroll({ factorId: factor === null || factor === void 0 ? void 0 : factor.id }) : void 0)); + return { data: null, error: enrollError }; + } + // Get challenge and create credential + const { data: challengeResponse, error: challengeError } = await this._challenge({ + factorId: factor.id, + friendlyName: factor.friendly_name, + webauthn: { rpId, rpOrigins }, + signal, + }, { + create: overrides, + }); + if (!challengeResponse) { + return { data: null, error: challengeError }; + } + return this._verify({ + factorId: factor.id, + challengeId: challengeResponse.challengeId, + webauthn: { + rpId, + rpOrigins, + type: challengeResponse.webauthn.type, + credential_response: challengeResponse.webauthn.credential_response, + }, + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: null, error }; + } + return { + data: null, + error: new AuthUnknownError('Unexpected error in register', error), + }; + } + } +} +//# sourceMappingURL=webauthn.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/dist/module/lib/webauthn.js.map b/backend/node_modules/@supabase/auth-js/dist/module/lib/webauthn.js.map new file mode 100644 index 0000000..bc67663 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/dist/module/lib/webauthn.js.map @@ -0,0 +1 @@ +{"version":3,"file":"webauthn.js","sourceRoot":"","sources":["../../../src/lib/webauthn.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAA;AACrE,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,UAAU,CAAA;AAYnE,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAA;AAcrC,OAAO,EACL,2BAA2B,EAC3B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E,KAAK,EAAE,cAAc,EAAE,CAAA;YAC9C,CAAC;YAED,OAAO,IAAI,CAAC,OAAO,CAAC;gBAClB,QAAQ,EAAE,MAAM,CAAC,EAAE;gBACnB,WAAW,EAAE,iBAAiB,CAAC,WAAW;gBAC1C,QAAQ,EAAE;oBACR,IAAI;oBACJ,SAAS;oBACT,IAAI,EAAE,iBAAiB,CAAC,QAAQ,CAAC,IAAI;oBACrC,mBAAmB,EAAE,iBAAiB,CAAC,QAAQ,CAAC,mBAAmB;iBACpE;aACF,CAAC,CAAA;QACJ,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,WAAW,CAAC,KAAK,CAAC,EAAE,CAAC;gBACvB,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,CAAA;YAC9B,CAAC;YACD,OAAO;gBACL,IAAI,EAAE,IAAI;gBACV,KAAK,EAAE,IAAI,gBAAgB,CAAC,8BAA8B,EAAE,KAAK,CAAC;aACnE,CAAA;QACH,CAAC;IACH,CAAC;CACF"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/auth-js/package.json b/backend/node_modules/@supabase/auth-js/package.json new file mode 100644 index 0000000..84638f4 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/package.json @@ -0,0 +1,48 @@ +{ + "name": "@supabase/auth-js", + "version": "2.87.1", + "private": false, + "description": "Official SDK for Supabase Auth", + "keywords": [ + "auth", + "supabase", + "auth", + "authentication" + ], + "homepage": "https://github.com/supabase/supabase-js/tree/master/packages/core/auth-js", + "bugs": "https://github.com/supabase/supabase-js/issues", + "license": "MIT", + "author": "Supabase", + "files": [ + "dist", + "src" + ], + "main": "dist/main/index.js", + "module": "dist/module/index.js", + "types": "dist/module/index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/supabase/supabase-js.git", + "directory": "packages/core/auth-js" + }, + "scripts": { + "build": "npm run build:main && npm run build:module", + "build:main": "tsc -p tsconfig.json", + "build:module": "tsc -p tsconfig.module.json", + "test:auth": "npm run test:clean && npm run test:infra && npm run test:suite && npm run test:clean", + "test:suite": "jest --runInBand --coverage", + "test:infra": "cd infra && docker compose down && docker compose pull && docker compose up -d && sleep 30", + "test:clean": "cd infra && docker compose down", + "docs": "typedoc src/index.ts --out docs/v2 --excludePrivate --excludeProtected", + "docs:json": "typedoc --json docs/v2/spec.json --excludeExternals --excludePrivate --excludeProtected src/index.ts" + }, + "dependencies": { + "tslib": "2.8.1" + }, + "devDependencies": { + "prettier": "^2.8.8" + }, + "engines": { + "node": ">=20.0.0" + } +} diff --git a/backend/node_modules/@supabase/auth-js/src/AuthAdminApi.ts b/backend/node_modules/@supabase/auth-js/src/AuthAdminApi.ts new file mode 100644 index 0000000..6884785 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/src/AuthAdminApi.ts @@ -0,0 +1,5 @@ +import GoTrueAdminApi from './GoTrueAdminApi' + +const AuthAdminApi = GoTrueAdminApi + +export default AuthAdminApi diff --git a/backend/node_modules/@supabase/auth-js/src/AuthClient.ts b/backend/node_modules/@supabase/auth-js/src/AuthClient.ts new file mode 100644 index 0000000..5677de4 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/src/AuthClient.ts @@ -0,0 +1,5 @@ +import GoTrueClient from './GoTrueClient' + +const AuthClient = GoTrueClient + +export default AuthClient diff --git a/backend/node_modules/@supabase/auth-js/src/GoTrueAdminApi.ts b/backend/node_modules/@supabase/auth-js/src/GoTrueAdminApi.ts new file mode 100644 index 0000000..0fcce62 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/src/GoTrueAdminApi.ts @@ -0,0 +1,551 @@ +import { + Fetch, + _generateLinkResponse, + _noResolveJsonResponse, + _request, + _userResponse, +} from './lib/fetch' +import { resolveFetch, validateUUID } from './lib/helpers' +import { + AdminUserAttributes, + GenerateLinkParams, + GenerateLinkResponse, + Pagination, + User, + UserResponse, + GoTrueAdminMFAApi, + AuthMFAAdminDeleteFactorParams, + AuthMFAAdminDeleteFactorResponse, + AuthMFAAdminListFactorsParams, + AuthMFAAdminListFactorsResponse, + PageParams, + SIGN_OUT_SCOPES, + SignOutScope, + GoTrueAdminOAuthApi, + CreateOAuthClientParams, + UpdateOAuthClientParams, + OAuthClientResponse, + OAuthClientListResponse, +} from './lib/types' +import { AuthError, isAuthError } from './lib/errors' + +export default class GoTrueAdminApi { + /** Contains all MFA administration methods. */ + mfa: GoTrueAdminMFAApi + + /** + * Contains all OAuth client administration methods. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ + oauth: GoTrueAdminOAuthApi + + protected url: string + protected headers: { + [key: string]: string + } + protected fetch: Fetch + + /** + * Creates an admin API client that can be used to manage users and OAuth clients. + * + * @example + * ```ts + * import { GoTrueAdminApi } from '@supabase/auth-js' + * + * const admin = new GoTrueAdminApi({ + * url: 'https://xyzcompany.supabase.co/auth/v1', + * headers: { Authorization: `Bearer ${process.env.SUPABASE_SERVICE_ROLE_KEY}` }, + * }) + * ``` + */ + constructor({ + url = '', + headers = {}, + fetch, + }: { + url: string + headers?: { + [key: string]: string + } + fetch?: Fetch + }) { + this.url = url + this.headers = headers + this.fetch = resolveFetch(fetch) + this.mfa = { + listFactors: this._listFactors.bind(this), + deleteFactor: this._deleteFactor.bind(this), + } + this.oauth = { + listClients: this._listOAuthClients.bind(this), + createClient: this._createOAuthClient.bind(this), + getClient: this._getOAuthClient.bind(this), + updateClient: this._updateOAuthClient.bind(this), + deleteClient: this._deleteOAuthClient.bind(this), + regenerateClientSecret: this._regenerateOAuthClientSecret.bind(this), + } + } + + /** + * Removes a logged-in session. + * @param jwt A valid, logged-in JWT. + * @param scope The logout sope. + */ + async signOut( + jwt: string, + scope: SignOutScope = SIGN_OUT_SCOPES[0] + ): Promise<{ data: null; error: AuthError | null }> { + if (SIGN_OUT_SCOPES.indexOf(scope) < 0) { + throw new Error( + `@supabase/auth-js: Parameter scope must be one of ${SIGN_OUT_SCOPES.join(', ')}` + ) + } + + try { + await _request(this.fetch, 'POST', `${this.url}/logout?scope=${scope}`, { + headers: this.headers, + jwt, + noResolveJson: true, + }) + return { data: null, error: null } + } catch (error) { + if (isAuthError(error)) { + return { data: null, error } + } + + throw error + } + } + + /** + * Sends an invite link to an email address. + * @param email The email address of the user. + * @param options Additional options to be included when inviting. + */ + async inviteUserByEmail( + email: string, + options: { + /** A custom data object to store additional metadata about the user. This maps to the `auth.users.user_metadata` column. */ + data?: object + + /** The URL which will be appended to the email link sent to the user's email address. Once clicked the user will end up on this URL. */ + redirectTo?: string + } = {} + ): Promise { + try { + return await _request(this.fetch, 'POST', `${this.url}/invite`, { + body: { email, data: options.data }, + headers: this.headers, + redirectTo: options.redirectTo, + xform: _userResponse, + }) + } catch (error) { + if (isAuthError(error)) { + return { data: { user: null }, error } + } + + throw error + } + } + + /** + * Generates email links and OTPs to be sent via a custom email provider. + * @param email The user's email. + * @param options.password User password. For signup only. + * @param options.data Optional user metadata. For signup only. + * @param options.redirectTo The redirect url which should be appended to the generated link + */ + async generateLink(params: GenerateLinkParams): Promise { + try { + const { options, ...rest } = params + const body: any = { ...rest, ...options } + if ('newEmail' in rest) { + // replace newEmail with new_email in request body + body.new_email = rest?.newEmail + delete body['newEmail'] + } + return await _request(this.fetch, 'POST', `${this.url}/admin/generate_link`, { + body: body, + headers: this.headers, + xform: _generateLinkResponse, + redirectTo: options?.redirectTo, + }) + } catch (error) { + if (isAuthError(error)) { + return { + data: { + properties: null, + user: null, + }, + error, + } + } + throw error + } + } + + // User Admin API + /** + * Creates a new user. + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async createUser(attributes: AdminUserAttributes): Promise { + try { + return await _request(this.fetch, 'POST', `${this.url}/admin/users`, { + body: attributes, + headers: this.headers, + xform: _userResponse, + }) + } catch (error) { + if (isAuthError(error)) { + return { data: { user: null }, error } + } + + throw error + } + } + + /** + * Get a list of users. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + * @param params An object which supports `page` and `perPage` as numbers, to alter the paginated results. + */ + async listUsers( + params?: PageParams + ): Promise< + | { data: { users: User[]; aud: string } & Pagination; error: null } + | { data: { users: [] }; error: AuthError } + > { + try { + const pagination: Pagination = { nextPage: null, lastPage: 0, total: 0 } + const response = await _request(this.fetch, 'GET', `${this.url}/admin/users`, { + headers: this.headers, + noResolveJson: true, + query: { + page: params?.page?.toString() ?? '', + per_page: params?.perPage?.toString() ?? '', + }, + xform: _noResolveJsonResponse, + }) + if (response.error) throw response.error + + const users = await response.json() + const total = response.headers.get('x-total-count') ?? 0 + const links = response.headers.get('link')?.split(',') ?? [] + if (links.length > 0) { + links.forEach((link: string) => { + const page = parseInt(link.split(';')[0].split('=')[1].substring(0, 1)) + const rel = JSON.parse(link.split(';')[1].split('=')[1]) + pagination[`${rel}Page`] = page + }) + + pagination.total = parseInt(total) + } + return { data: { ...users, ...pagination }, error: null } + } catch (error) { + if (isAuthError(error)) { + return { data: { users: [] }, error } + } + throw error + } + } + + /** + * Get user by id. + * + * @param uid The user's unique identifier + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async getUserById(uid: string): Promise { + validateUUID(uid) + + try { + return await _request(this.fetch, 'GET', `${this.url}/admin/users/${uid}`, { + headers: this.headers, + xform: _userResponse, + }) + } catch (error) { + if (isAuthError(error)) { + return { data: { user: null }, error } + } + + throw error + } + } + + /** + * Updates the user data. + * + * @param attributes The data you want to update. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async updateUserById(uid: string, attributes: AdminUserAttributes): Promise { + validateUUID(uid) + + try { + return await _request(this.fetch, 'PUT', `${this.url}/admin/users/${uid}`, { + body: attributes, + headers: this.headers, + xform: _userResponse, + }) + } catch (error) { + if (isAuthError(error)) { + return { data: { user: null }, error } + } + + throw error + } + } + + /** + * Delete a user. Requires a `service_role` key. + * + * @param id The user id you want to remove. + * @param shouldSoftDelete If true, then the user will be soft-deleted from the auth schema. Soft deletion allows user identification from the hashed user ID but is not reversible. + * Defaults to false for backward compatibility. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async deleteUser(id: string, shouldSoftDelete = false): Promise { + validateUUID(id) + + try { + return await _request(this.fetch, 'DELETE', `${this.url}/admin/users/${id}`, { + headers: this.headers, + body: { + should_soft_delete: shouldSoftDelete, + }, + xform: _userResponse, + }) + } catch (error) { + if (isAuthError(error)) { + return { data: { user: null }, error } + } + + throw error + } + } + + private async _listFactors( + params: AuthMFAAdminListFactorsParams + ): Promise { + validateUUID(params.userId) + + try { + const { data, error } = await _request( + this.fetch, + 'GET', + `${this.url}/admin/users/${params.userId}/factors`, + { + headers: this.headers, + xform: (factors: any) => { + return { data: { factors }, error: null } + }, + } + ) + return { data, error } + } catch (error) { + if (isAuthError(error)) { + return { data: null, error } + } + + throw error + } + } + + private async _deleteFactor( + params: AuthMFAAdminDeleteFactorParams + ): Promise { + validateUUID(params.userId) + validateUUID(params.id) + + try { + const data = await _request( + this.fetch, + 'DELETE', + `${this.url}/admin/users/${params.userId}/factors/${params.id}`, + { + headers: this.headers, + } + ) + + return { data, error: null } + } catch (error) { + if (isAuthError(error)) { + return { data: null, error } + } + + throw error + } + } + + /** + * Lists all OAuth clients with optional pagination. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + private async _listOAuthClients(params?: PageParams): Promise { + try { + const pagination: Pagination = { nextPage: null, lastPage: 0, total: 0 } + const response = await _request(this.fetch, 'GET', `${this.url}/admin/oauth/clients`, { + headers: this.headers, + noResolveJson: true, + query: { + page: params?.page?.toString() ?? '', + per_page: params?.perPage?.toString() ?? '', + }, + xform: _noResolveJsonResponse, + }) + if (response.error) throw response.error + + const clients = await response.json() + const total = response.headers.get('x-total-count') ?? 0 + const links = response.headers.get('link')?.split(',') ?? [] + if (links.length > 0) { + links.forEach((link: string) => { + const page = parseInt(link.split(';')[0].split('=')[1].substring(0, 1)) + const rel = JSON.parse(link.split(';')[1].split('=')[1]) + pagination[`${rel}Page`] = page + }) + + pagination.total = parseInt(total) + } + return { data: { ...clients, ...pagination }, error: null } + } catch (error) { + if (isAuthError(error)) { + return { data: { clients: [] }, error } + } + throw error + } + } + + /** + * Creates a new OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + private async _createOAuthClient(params: CreateOAuthClientParams): Promise { + try { + return await _request(this.fetch, 'POST', `${this.url}/admin/oauth/clients`, { + body: params, + headers: this.headers, + xform: (client: any) => { + return { data: client, error: null } + }, + }) + } catch (error) { + if (isAuthError(error)) { + return { data: null, error } + } + + throw error + } + } + + /** + * Gets details of a specific OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + private async _getOAuthClient(clientId: string): Promise { + try { + return await _request(this.fetch, 'GET', `${this.url}/admin/oauth/clients/${clientId}`, { + headers: this.headers, + xform: (client: any) => { + return { data: client, error: null } + }, + }) + } catch (error) { + if (isAuthError(error)) { + return { data: null, error } + } + + throw error + } + } + + /** + * Updates an existing OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + private async _updateOAuthClient( + clientId: string, + params: UpdateOAuthClientParams + ): Promise { + try { + return await _request(this.fetch, 'PUT', `${this.url}/admin/oauth/clients/${clientId}`, { + body: params, + headers: this.headers, + xform: (client: any) => { + return { data: client, error: null } + }, + }) + } catch (error) { + if (isAuthError(error)) { + return { data: null, error } + } + + throw error + } + } + + /** + * Deletes an OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + private async _deleteOAuthClient( + clientId: string + ): Promise<{ data: null; error: AuthError | null }> { + try { + await _request(this.fetch, 'DELETE', `${this.url}/admin/oauth/clients/${clientId}`, { + headers: this.headers, + noResolveJson: true, + }) + return { data: null, error: null } + } catch (error) { + if (isAuthError(error)) { + return { data: null, error } + } + + throw error + } + } + + /** + * Regenerates the secret for an OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + private async _regenerateOAuthClientSecret(clientId: string): Promise { + try { + return await _request( + this.fetch, + 'POST', + `${this.url}/admin/oauth/clients/${clientId}/regenerate_secret`, + { + headers: this.headers, + xform: (client: any) => { + return { data: client, error: null } + }, + } + ) + } catch (error) { + if (isAuthError(error)) { + return { data: null, error } + } + + throw error + } + } +} diff --git a/backend/node_modules/@supabase/auth-js/src/GoTrueClient.ts b/backend/node_modules/@supabase/auth-js/src/GoTrueClient.ts new file mode 100644 index 0000000..10c7384 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/src/GoTrueClient.ts @@ -0,0 +1,3819 @@ +import GoTrueAdminApi from './GoTrueAdminApi' +import { + AUTO_REFRESH_TICK_DURATION_MS, + AUTO_REFRESH_TICK_THRESHOLD, + DEFAULT_HEADERS, + EXPIRY_MARGIN_MS, + GOTRUE_URL, + JWKS_TTL, + STORAGE_KEY, +} from './lib/constants' +import { + AuthError, + AuthImplicitGrantRedirectError, + AuthInvalidCredentialsError, + AuthInvalidJwtError, + AuthInvalidTokenResponseError, + AuthPKCEGrantCodeExchangeError, + AuthSessionMissingError, + AuthUnknownError, + isAuthApiError, + isAuthError, + isAuthImplicitGrantRedirectError, + isAuthRetryableFetchError, + isAuthSessionMissingError, +} from './lib/errors' +import { + Fetch, + _request, + _sessionResponse, + _sessionResponsePassword, + _ssoResponse, + _userResponse, +} from './lib/fetch' +import { + decodeJWT, + deepClone, + Deferred, + generateCallbackId, + getAlgorithm, + getCodeChallengeAndMethod, + getItemAsync, + insecureUserWarningProxy, + isBrowser, + parseParametersFromURL, + removeItemAsync, + resolveFetch, + retryable, + setItemAsync, + sleep, + supportsLocalStorage, + userNotAvailableProxy, + validateExp, +} from './lib/helpers' +import { memoryLocalStorageAdapter } from './lib/local-storage' +import { LockAcquireTimeoutError, navigatorLock } from './lib/locks' +import { polyfillGlobalThis } from './lib/polyfills' +import { version } from './lib/version' + +import { bytesToBase64URL, stringToUint8Array } from './lib/base64url' +import type { + AuthChangeEvent, + AuthenticatorAssuranceLevels, + AuthFlowType, + AuthMFAChallengePhoneResponse, + AuthMFAChallengeResponse, + AuthMFAChallengeTOTPResponse, + AuthMFAChallengeWebauthnResponse, + AuthMFAChallengeWebauthnServerResponse, + AuthMFAEnrollPhoneResponse, + AuthMFAEnrollResponse, + AuthMFAEnrollTOTPResponse, + AuthMFAEnrollWebauthnResponse, + AuthMFAGetAuthenticatorAssuranceLevelResponse, + AuthMFAListFactorsResponse, + AuthMFAUnenrollResponse, + AuthMFAVerifyResponse, + AuthOtpResponse, + AuthResponse, + AuthResponsePassword, + AuthTokenResponse, + AuthTokenResponsePassword, + CallRefreshTokenResult, + EthereumWallet, + EthereumWeb3Credentials, + Factor, + GoTrueClientOptions, + GoTrueMFAApi, + InitializeResult, + JWK, + JwtHeader, + JwtPayload, + LockFunc, + MFAChallengeAndVerifyParams, + MFAChallengeParams, + MFAChallengePhoneParams, + MFAChallengeTOTPParams, + MFAChallengeWebauthnParams, + MFAEnrollParams, + MFAEnrollPhoneParams, + MFAEnrollTOTPParams, + MFAEnrollWebauthnParams, + MFAUnenrollParams, + MFAVerifyParams, + MFAVerifyPhoneParams, + MFAVerifyTOTPParams, + MFAVerifyWebauthnParamFields, + MFAVerifyWebauthnParams, + OAuthResponse, + AuthOAuthServerApi, + AuthOAuthAuthorizationDetailsResponse, + AuthOAuthConsentResponse, + AuthOAuthGrantsResponse, + AuthOAuthRevokeGrantResponse, + Prettify, + Provider, + ResendParams, + Session, + SignInAnonymouslyCredentials, + SignInWithIdTokenCredentials, + SignInWithOAuthCredentials, + SignInWithPasswordCredentials, + SignInWithPasswordlessCredentials, + SignInWithSSO, + SignOut, + SignUpWithPasswordCredentials, + SolanaWallet, + SolanaWeb3Credentials, + SSOResponse, + StrictOmit, + Subscription, + SupportedStorage, + User, + UserAttributes, + UserIdentity, + UserResponse, + VerifyOtpParams, + Web3Credentials, +} from './lib/types' +import { + createSiweMessage, + fromHex, + getAddress, + Hex, + SiweMessage, + toHex, +} from './lib/web3/ethereum' +import { + deserializeCredentialCreationOptions, + deserializeCredentialRequestOptions, + serializeCredentialCreationResponse, + serializeCredentialRequestResponse, + WebAuthnApi, +} from './lib/webauthn' +import { + AuthenticationCredential, + PublicKeyCredentialJSON, + RegistrationCredential, +} from './lib/webauthn.dom' + +polyfillGlobalThis() // Make "globalThis" available + +const DEFAULT_OPTIONS: Omit< + Required, + 'fetch' | 'storage' | 'userStorage' | 'lock' +> = { + url: GOTRUE_URL, + storageKey: STORAGE_KEY, + autoRefreshToken: true, + persistSession: true, + detectSessionInUrl: true, + headers: DEFAULT_HEADERS, + flowType: 'implicit', + debug: false, + hasCustomAuthorizationHeader: false, + throwOnError: false, +} + +async function lockNoOp(name: string, acquireTimeout: number, fn: () => Promise): Promise { + return await fn() +} + +/** + * Caches JWKS values for all clients created in the same environment. This is + * especially useful for shared-memory execution environments such as Vercel's + * Fluid Compute, AWS Lambda or Supabase's Edge Functions. Regardless of how + * many clients are created, if they share the same storage key they will use + * the same JWKS cache, significantly speeding up getClaims() with asymmetric + * JWTs. + */ +const GLOBAL_JWKS: { [storageKey: string]: { cachedAt: number; jwks: { keys: JWK[] } } } = {} + +export default class GoTrueClient { + private static nextInstanceID: Record = {} + + private instanceID: number + + /** + * Namespace for the GoTrue admin methods. + * These methods should only be used in a trusted server-side environment. + */ + admin: GoTrueAdminApi + /** + * Namespace for the MFA methods. + */ + mfa: GoTrueMFAApi + /** + * Namespace for the OAuth 2.1 authorization server methods. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * Used to implement the authorization code flow on the consent page. + */ + oauth: AuthOAuthServerApi + /** + * The storage key used to identify the values saved in localStorage + */ + protected storageKey: string + + protected flowType: AuthFlowType + + /** + * The JWKS used for verifying asymmetric JWTs + */ + protected get jwks() { + return GLOBAL_JWKS[this.storageKey]?.jwks ?? { keys: [] } + } + + protected set jwks(value: { keys: JWK[] }) { + GLOBAL_JWKS[this.storageKey] = { ...GLOBAL_JWKS[this.storageKey], jwks: value } + } + + protected get jwks_cached_at() { + return GLOBAL_JWKS[this.storageKey]?.cachedAt ?? Number.MIN_SAFE_INTEGER + } + + protected set jwks_cached_at(value: number) { + GLOBAL_JWKS[this.storageKey] = { ...GLOBAL_JWKS[this.storageKey], cachedAt: value } + } + + protected autoRefreshToken: boolean + protected persistSession: boolean + protected storage: SupportedStorage + /** + * @experimental + */ + protected userStorage: SupportedStorage | null = null + protected memoryStorage: { [key: string]: string } | null = null + protected stateChangeEmitters: Map = new Map() + protected autoRefreshTicker: ReturnType | null = null + protected visibilityChangedCallback: (() => Promise) | null = null + protected refreshingDeferred: Deferred | null = null + /** + * Keeps track of the async client initialization. + * When null or not yet resolved the auth state is `unknown` + * Once resolved the auth state is known and it's safe to call any further client methods. + * Keep extra care to never reject or throw uncaught errors + */ + protected initializePromise: Promise | null = null + protected detectSessionInUrl = true + protected url: string + protected headers: { + [key: string]: string + } + protected hasCustomAuthorizationHeader = false + protected suppressGetSessionWarning = false + protected fetch: Fetch + protected lock: LockFunc + protected lockAcquired = false + protected pendingInLock: Promise[] = [] + protected throwOnError: boolean + + /** + * Used to broadcast state change events to other tabs listening. + */ + protected broadcastChannel: BroadcastChannel | null = null + + protected logDebugMessages: boolean + protected logger: (message: string, ...args: any[]) => void = console.log + + /** + * Create a new client for use in the browser. + * + * @example + * ```ts + * import { GoTrueClient } from '@supabase/auth-js' + * + * const auth = new GoTrueClient({ + * url: 'https://xyzcompany.supabase.co/auth/v1', + * headers: { apikey: 'public-anon-key' }, + * storageKey: 'supabase-auth', + * }) + * ``` + */ + constructor(options: GoTrueClientOptions) { + const settings = { ...DEFAULT_OPTIONS, ...options } + this.storageKey = settings.storageKey + + this.instanceID = GoTrueClient.nextInstanceID[this.storageKey] ?? 0 + GoTrueClient.nextInstanceID[this.storageKey] = this.instanceID + 1 + + this.logDebugMessages = !!settings.debug + if (typeof settings.debug === 'function') { + this.logger = settings.debug + } + + if (this.instanceID > 0 && isBrowser()) { + const message = `${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.` + console.warn(message) + if (this.logDebugMessages) { + console.trace(message) + } + } + + this.persistSession = settings.persistSession + this.autoRefreshToken = settings.autoRefreshToken + this.admin = new GoTrueAdminApi({ + url: settings.url, + headers: settings.headers, + fetch: settings.fetch, + }) + + this.url = settings.url + this.headers = settings.headers + this.fetch = resolveFetch(settings.fetch) + this.lock = settings.lock || lockNoOp + this.detectSessionInUrl = settings.detectSessionInUrl + this.flowType = settings.flowType + this.hasCustomAuthorizationHeader = settings.hasCustomAuthorizationHeader + this.throwOnError = settings.throwOnError + + if (settings.lock) { + this.lock = settings.lock + } else if (this.persistSession && isBrowser() && globalThis?.navigator?.locks) { + this.lock = navigatorLock + } else { + this.lock = lockNoOp + } + + if (!this.jwks) { + this.jwks = { keys: [] } + this.jwks_cached_at = Number.MIN_SAFE_INTEGER + } + + this.mfa = { + verify: this._verify.bind(this), + enroll: this._enroll.bind(this), + unenroll: this._unenroll.bind(this), + challenge: this._challenge.bind(this), + listFactors: this._listFactors.bind(this), + challengeAndVerify: this._challengeAndVerify.bind(this), + getAuthenticatorAssuranceLevel: this._getAuthenticatorAssuranceLevel.bind(this), + webauthn: new WebAuthnApi(this), + } + + this.oauth = { + getAuthorizationDetails: this._getAuthorizationDetails.bind(this), + approveAuthorization: this._approveAuthorization.bind(this), + denyAuthorization: this._denyAuthorization.bind(this), + listGrants: this._listOAuthGrants.bind(this), + revokeGrant: this._revokeOAuthGrant.bind(this), + } + + if (this.persistSession) { + if (settings.storage) { + this.storage = settings.storage + } else { + if (supportsLocalStorage()) { + this.storage = globalThis.localStorage + } else { + this.memoryStorage = {} + this.storage = memoryLocalStorageAdapter(this.memoryStorage) + } + } + + if (settings.userStorage) { + this.userStorage = settings.userStorage + } + } else { + this.memoryStorage = {} + this.storage = memoryLocalStorageAdapter(this.memoryStorage) + } + + if (isBrowser() && globalThis.BroadcastChannel && this.persistSession && this.storageKey) { + try { + this.broadcastChannel = new globalThis.BroadcastChannel(this.storageKey) + } catch (e: any) { + console.error( + 'Failed to create a new BroadcastChannel, multi-tab state changes will not be available', + e + ) + } + + this.broadcastChannel?.addEventListener('message', async (event) => { + this._debug('received broadcast notification from other tab or client', event) + + await this._notifyAllSubscribers(event.data.event, event.data.session, false) // broadcast = false so we don't get an endless loop of messages + }) + } + + this.initialize() + } + + /** + * Returns whether error throwing mode is enabled for this client. + */ + public isThrowOnErrorEnabled(): boolean { + return this.throwOnError + } + + /** + * Centralizes return handling with optional error throwing. When `throwOnError` is enabled + * and the provided result contains a non-nullish error, the error is thrown instead of + * being returned. This ensures consistent behavior across all public API methods. + */ + private _returnResult(result: T): T { + if (this.throwOnError && result && result.error) { + throw result.error + } + return result + } + + private _logPrefix(): string { + return ( + 'GoTrueClient@' + + `${this.storageKey}:${this.instanceID} (${version}) ${new Date().toISOString()}` + ) + } + + private _debug(...args: any[]): GoTrueClient { + if (this.logDebugMessages) { + this.logger(this._logPrefix(), ...args) + } + + return this + } + + /** + * Initializes the client session either from the url or from storage. + * This method is automatically called when instantiating the client, but should also be called + * manually when checking for an error from an auth redirect (oauth, magiclink, password recovery, etc). + */ + async initialize(): Promise { + if (this.initializePromise) { + return await this.initializePromise + } + + this.initializePromise = (async () => { + return await this._acquireLock(-1, async () => { + return await this._initialize() + }) + })() + + return await this.initializePromise + } + + /** + * IMPORTANT: + * 1. Never throw in this method, as it is called from the constructor + * 2. Never return a session from this method as it would be cached over + * the whole lifetime of the client + */ + private async _initialize(): Promise { + try { + let params: { [parameter: string]: string } = {} + let callbackUrlType = 'none' + + if (isBrowser()) { + params = parseParametersFromURL(window.location.href) + if (this._isImplicitGrantCallback(params)) { + callbackUrlType = 'implicit' + } else if (await this._isPKCECallback(params)) { + callbackUrlType = 'pkce' + } + } + + /** + * Attempt to get the session from the URL only if these conditions are fulfilled + * + * Note: If the URL isn't one of the callback url types (implicit or pkce), + * then there could be an existing session so we don't want to prematurely remove it + */ + if (isBrowser() && this.detectSessionInUrl && callbackUrlType !== 'none') { + const { data, error } = await this._getSessionFromURL(params, callbackUrlType) + if (error) { + this._debug('#_initialize()', 'error detecting session from URL', error) + + if (isAuthImplicitGrantRedirectError(error)) { + const errorCode = error.details?.code + if ( + errorCode === 'identity_already_exists' || + errorCode === 'identity_not_found' || + errorCode === 'single_identity_not_deletable' + ) { + return { error } + } + } + + // failed login attempt via url, + // remove old session as in verifyOtp, signUp and signInWith* + await this._removeSession() + + return { error } + } + + const { session, redirectType } = data + + this._debug( + '#_initialize()', + 'detected session in URL', + session, + 'redirect type', + redirectType + ) + + await this._saveSession(session) + + setTimeout(async () => { + if (redirectType === 'recovery') { + await this._notifyAllSubscribers('PASSWORD_RECOVERY', session) + } else { + await this._notifyAllSubscribers('SIGNED_IN', session) + } + }, 0) + + return { error: null } + } + // no login attempt via callback url try to recover session from storage + await this._recoverAndRefresh() + return { error: null } + } catch (error) { + if (isAuthError(error)) { + return this._returnResult({ error }) + } + + return this._returnResult({ + error: new AuthUnknownError('Unexpected error during initialization', error), + }) + } finally { + await this._handleVisibilityChange() + this._debug('#_initialize()', 'end') + } + } + + /** + * Creates a new anonymous user. + * + * @returns A session where the is_anonymous claim in the access token JWT set to true + */ + async signInAnonymously(credentials?: SignInAnonymouslyCredentials): Promise { + try { + const res = await _request(this.fetch, 'POST', `${this.url}/signup`, { + headers: this.headers, + body: { + data: credentials?.options?.data ?? {}, + gotrue_meta_security: { captcha_token: credentials?.options?.captchaToken }, + }, + xform: _sessionResponse, + }) + const { data, error } = res + + if (error || !data) { + return this._returnResult({ data: { user: null, session: null }, error: error }) + } + const session: Session | null = data.session + const user: User | null = data.user + + if (data.session) { + await this._saveSession(data.session) + await this._notifyAllSubscribers('SIGNED_IN', session) + } + + return this._returnResult({ data: { user, session }, error: null }) + } catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: { user: null, session: null }, error }) + } + + throw error + } + } + + /** + * Creates a new user. + * + * Be aware that if a user account exists in the system you may get back an + * error message that attempts to hide this information from the user. + * This method has support for PKCE via email signups. The PKCE flow cannot be used when autoconfirm is enabled. + * + * @returns A logged-in session if the server has "autoconfirm" ON + * @returns A user if the server has "autoconfirm" OFF + */ + async signUp(credentials: SignUpWithPasswordCredentials): Promise { + try { + let res: AuthResponse + if ('email' in credentials) { + const { email, password, options } = credentials + let codeChallenge: string | null = null + let codeChallengeMethod: string | null = null + if (this.flowType === 'pkce') { + ;[codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod( + this.storage, + this.storageKey + ) + } + res = await _request(this.fetch, 'POST', `${this.url}/signup`, { + headers: this.headers, + redirectTo: options?.emailRedirectTo, + body: { + email, + password, + data: options?.data ?? {}, + gotrue_meta_security: { captcha_token: options?.captchaToken }, + code_challenge: codeChallenge, + code_challenge_method: codeChallengeMethod, + }, + xform: _sessionResponse, + }) + } else if ('phone' in credentials) { + const { phone, password, options } = credentials + res = await _request(this.fetch, 'POST', `${this.url}/signup`, { + headers: this.headers, + body: { + phone, + password, + data: options?.data ?? {}, + channel: options?.channel ?? 'sms', + gotrue_meta_security: { captcha_token: options?.captchaToken }, + }, + xform: _sessionResponse, + }) + } else { + throw new AuthInvalidCredentialsError( + 'You must provide either an email or phone number and a password' + ) + } + + const { data, error } = res + + if (error || !data) { + await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`) + return this._returnResult({ data: { user: null, session: null }, error: error }) + } + + const session: Session | null = data.session + const user: User | null = data.user + + if (data.session) { + await this._saveSession(data.session) + await this._notifyAllSubscribers('SIGNED_IN', session) + } + + return this._returnResult({ data: { user, session }, error: null }) + } catch (error) { + await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`) + if (isAuthError(error)) { + return this._returnResult({ data: { user: null, session: null }, error }) + } + + throw error + } + } + + /** + * Log in an existing user with an email and password or phone and password. + * + * Be aware that you may get back an error message that will not distinguish + * between the cases where the account does not exist or that the + * email/phone and password combination is wrong or that the account can only + * be accessed via social login. + */ + async signInWithPassword( + credentials: SignInWithPasswordCredentials + ): Promise { + try { + let res: AuthResponsePassword + if ('email' in credentials) { + const { email, password, options } = credentials + res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=password`, { + headers: this.headers, + body: { + email, + password, + gotrue_meta_security: { captcha_token: options?.captchaToken }, + }, + xform: _sessionResponsePassword, + }) + } else if ('phone' in credentials) { + const { phone, password, options } = credentials + res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=password`, { + headers: this.headers, + body: { + phone, + password, + gotrue_meta_security: { captcha_token: options?.captchaToken }, + }, + xform: _sessionResponsePassword, + }) + } else { + throw new AuthInvalidCredentialsError( + 'You must provide either an email or phone number and a password' + ) + } + const { data, error } = res + + if (error) { + return this._returnResult({ data: { user: null, session: null }, error }) + } else if (!data || !data.session || !data.user) { + const invalidTokenError = new AuthInvalidTokenResponseError() + return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError }) + } + if (data.session) { + await this._saveSession(data.session) + await this._notifyAllSubscribers('SIGNED_IN', data.session) + } + return this._returnResult({ + data: { + user: data.user, + session: data.session, + ...(data.weak_password ? { weakPassword: data.weak_password } : null), + }, + error, + }) + } catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: { user: null, session: null }, error }) + } + throw error + } + } + + /** + * Log in an existing user via a third-party provider. + * This method supports the PKCE flow. + */ + async signInWithOAuth(credentials: SignInWithOAuthCredentials): Promise { + return await this._handleProviderSignIn(credentials.provider, { + redirectTo: credentials.options?.redirectTo, + scopes: credentials.options?.scopes, + queryParams: credentials.options?.queryParams, + skipBrowserRedirect: credentials.options?.skipBrowserRedirect, + }) + } + + /** + * Log in an existing user by exchanging an Auth Code issued during the PKCE flow. + */ + async exchangeCodeForSession(authCode: string): Promise { + await this.initializePromise + + return this._acquireLock(-1, async () => { + return this._exchangeCodeForSession(authCode) + }) + } + + /** + * Signs in a user by verifying a message signed by the user's private key. + * Supports Ethereum (via Sign-In-With-Ethereum) & Solana (Sign-In-With-Solana) standards, + * both of which derive from the EIP-4361 standard + * With slight variation on Solana's side. + * @reference https://eips.ethereum.org/EIPS/eip-4361 + */ + async signInWithWeb3(credentials: Web3Credentials): Promise< + | { + data: { session: Session; user: User } + error: null + } + | { data: { session: null; user: null }; error: AuthError } + > { + const { chain } = credentials + + switch (chain) { + case 'ethereum': + return await this.signInWithEthereum(credentials) + case 'solana': + return await this.signInWithSolana(credentials) + default: + throw new Error(`@supabase/auth-js: Unsupported chain "${chain}"`) + } + } + + private async signInWithEthereum( + credentials: EthereumWeb3Credentials + ): Promise< + | { data: { session: Session; user: User }; error: null } + | { data: { session: null; user: null }; error: AuthError } + > { + // TODO: flatten type + let message: string + let signature: Hex + + if ('message' in credentials) { + message = credentials.message + signature = credentials.signature + } else { + const { chain, wallet, statement, options } = credentials + + let resolvedWallet: EthereumWallet + + if (!isBrowser()) { + if (typeof wallet !== 'object' || !options?.url) { + throw new Error( + '@supabase/auth-js: Both wallet and url must be specified in non-browser environments.' + ) + } + + resolvedWallet = wallet + } else if (typeof wallet === 'object') { + resolvedWallet = wallet + } else { + const windowAny = window as any + + if ( + 'ethereum' in windowAny && + typeof windowAny.ethereum === 'object' && + 'request' in windowAny.ethereum && + typeof windowAny.ethereum.request === 'function' + ) { + resolvedWallet = windowAny.ethereum + } else { + throw new Error( + `@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.` + ) + } + } + + const url = new URL(options?.url ?? window.location.href) + + const accounts = await resolvedWallet + .request({ + method: 'eth_requestAccounts', + }) + .then((accs) => accs as string[]) + .catch(() => { + throw new Error( + `@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid` + ) + }) + + if (!accounts || accounts.length === 0) { + throw new Error( + `@supabase/auth-js: No accounts available. Please ensure the wallet is connected.` + ) + } + + const address = getAddress(accounts[0]) + + let chainId = options?.signInWithEthereum?.chainId + if (!chainId) { + const chainIdHex = await resolvedWallet.request({ + method: 'eth_chainId', + }) + chainId = fromHex(chainIdHex as Hex) + } + + const siweMessage: SiweMessage = { + domain: url.host, + address: address, + statement: statement, + uri: url.href, + version: '1', + chainId: chainId, + nonce: options?.signInWithEthereum?.nonce, + issuedAt: options?.signInWithEthereum?.issuedAt ?? new Date(), + expirationTime: options?.signInWithEthereum?.expirationTime, + notBefore: options?.signInWithEthereum?.notBefore, + requestId: options?.signInWithEthereum?.requestId, + resources: options?.signInWithEthereum?.resources, + } + + message = createSiweMessage(siweMessage) + + // Sign message + signature = (await resolvedWallet.request({ + method: 'personal_sign', + params: [toHex(message), address], + })) as Hex + } + + try { + const { data, error } = await _request( + this.fetch, + 'POST', + `${this.url}/token?grant_type=web3`, + { + headers: this.headers, + body: { + chain: 'ethereum', + message, + signature, + ...(credentials.options?.captchaToken + ? { gotrue_meta_security: { captcha_token: credentials.options?.captchaToken } } + : null), + }, + xform: _sessionResponse, + } + ) + if (error) { + throw error + } + if (!data || !data.session || !data.user) { + const invalidTokenError = new AuthInvalidTokenResponseError() + return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError }) + } + if (data.session) { + await this._saveSession(data.session) + await this._notifyAllSubscribers('SIGNED_IN', data.session) + } + return this._returnResult({ data: { ...data }, error }) + } catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: { user: null, session: null }, error }) + } + + throw error + } + } + + private async signInWithSolana(credentials: SolanaWeb3Credentials) { + let message: string + let signature: Uint8Array + + if ('message' in credentials) { + message = credentials.message + signature = credentials.signature + } else { + const { chain, wallet, statement, options } = credentials + + let resolvedWallet: SolanaWallet + + if (!isBrowser()) { + if (typeof wallet !== 'object' || !options?.url) { + throw new Error( + '@supabase/auth-js: Both wallet and url must be specified in non-browser environments.' + ) + } + + resolvedWallet = wallet + } else if (typeof wallet === 'object') { + resolvedWallet = wallet + } else { + const windowAny = window as any + + if ( + 'solana' in windowAny && + typeof windowAny.solana === 'object' && + (('signIn' in windowAny.solana && typeof windowAny.solana.signIn === 'function') || + ('signMessage' in windowAny.solana && + typeof windowAny.solana.signMessage === 'function')) + ) { + resolvedWallet = windowAny.solana + } else { + throw new Error( + `@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.` + ) + } + } + + const url = new URL(options?.url ?? window.location.href) + + if ('signIn' in resolvedWallet && resolvedWallet.signIn) { + const output = await resolvedWallet.signIn({ + issuedAt: new Date().toISOString(), + + ...options?.signInWithSolana, + + // non-overridable properties + version: '1', + domain: url.host, + uri: url.href, + + ...(statement ? { statement } : null), + }) + + let outputToProcess: any + + if (Array.isArray(output) && output[0] && typeof output[0] === 'object') { + outputToProcess = output[0] + } else if ( + output && + typeof output === 'object' && + 'signedMessage' in output && + 'signature' in output + ) { + outputToProcess = output + } else { + throw new Error('@supabase/auth-js: Wallet method signIn() returned unrecognized value') + } + + if ( + 'signedMessage' in outputToProcess && + 'signature' in outputToProcess && + (typeof outputToProcess.signedMessage === 'string' || + outputToProcess.signedMessage instanceof Uint8Array) && + outputToProcess.signature instanceof Uint8Array + ) { + message = + typeof outputToProcess.signedMessage === 'string' + ? outputToProcess.signedMessage + : new TextDecoder().decode(outputToProcess.signedMessage) + signature = outputToProcess.signature + } else { + throw new Error( + '@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields' + ) + } + } else { + if ( + !('signMessage' in resolvedWallet) || + typeof resolvedWallet.signMessage !== 'function' || + !('publicKey' in resolvedWallet) || + typeof resolvedWallet !== 'object' || + !resolvedWallet.publicKey || + !('toBase58' in resolvedWallet.publicKey) || + typeof resolvedWallet.publicKey.toBase58 !== 'function' + ) { + throw new Error( + '@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API' + ) + } + + message = [ + `${url.host} wants you to sign in with your Solana account:`, + resolvedWallet.publicKey.toBase58(), + ...(statement ? ['', statement, ''] : ['']), + 'Version: 1', + `URI: ${url.href}`, + `Issued At: ${options?.signInWithSolana?.issuedAt ?? new Date().toISOString()}`, + ...(options?.signInWithSolana?.notBefore + ? [`Not Before: ${options.signInWithSolana.notBefore}`] + : []), + ...(options?.signInWithSolana?.expirationTime + ? [`Expiration Time: ${options.signInWithSolana.expirationTime}`] + : []), + ...(options?.signInWithSolana?.chainId + ? [`Chain ID: ${options.signInWithSolana.chainId}`] + : []), + ...(options?.signInWithSolana?.nonce ? [`Nonce: ${options.signInWithSolana.nonce}`] : []), + ...(options?.signInWithSolana?.requestId + ? [`Request ID: ${options.signInWithSolana.requestId}`] + : []), + ...(options?.signInWithSolana?.resources?.length + ? [ + 'Resources', + ...options.signInWithSolana.resources.map((resource) => `- ${resource}`), + ] + : []), + ].join('\n') + + const maybeSignature = await resolvedWallet.signMessage( + new TextEncoder().encode(message), + 'utf8' + ) + + if (!maybeSignature || !(maybeSignature instanceof Uint8Array)) { + throw new Error( + '@supabase/auth-js: Wallet signMessage() API returned an recognized value' + ) + } + + signature = maybeSignature + } + } + + try { + const { data, error } = await _request( + this.fetch, + 'POST', + `${this.url}/token?grant_type=web3`, + { + headers: this.headers, + body: { + chain: 'solana', + message, + signature: bytesToBase64URL(signature), + + ...(credentials.options?.captchaToken + ? { gotrue_meta_security: { captcha_token: credentials.options?.captchaToken } } + : null), + }, + xform: _sessionResponse, + } + ) + if (error) { + throw error + } + if (!data || !data.session || !data.user) { + const invalidTokenError = new AuthInvalidTokenResponseError() + return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError }) + } + if (data.session) { + await this._saveSession(data.session) + await this._notifyAllSubscribers('SIGNED_IN', data.session) + } + return this._returnResult({ data: { ...data }, error }) + } catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: { user: null, session: null }, error }) + } + + throw error + } + } + + private async _exchangeCodeForSession(authCode: string): Promise< + | { + data: { session: Session; user: User; redirectType: string | null } + error: null + } + | { data: { session: null; user: null; redirectType: null }; error: AuthError } + > { + const storageItem = await getItemAsync(this.storage, `${this.storageKey}-code-verifier`) + const [codeVerifier, redirectType] = ((storageItem ?? '') as string).split('/') + + try { + const { data, error } = await _request( + this.fetch, + 'POST', + `${this.url}/token?grant_type=pkce`, + { + headers: this.headers, + body: { + auth_code: authCode, + code_verifier: codeVerifier, + }, + xform: _sessionResponse, + } + ) + await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`) + if (error) { + throw error + } + if (!data || !data.session || !data.user) { + const invalidTokenError = new AuthInvalidTokenResponseError() + return this._returnResult({ + data: { user: null, session: null, redirectType: null }, + error: invalidTokenError, + }) + } + if (data.session) { + await this._saveSession(data.session) + await this._notifyAllSubscribers('SIGNED_IN', data.session) + } + return this._returnResult({ data: { ...data, redirectType: redirectType ?? null }, error }) + } catch (error) { + await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`) + if (isAuthError(error)) { + return this._returnResult({ + data: { user: null, session: null, redirectType: null }, + error, + }) + } + throw error + } + } + + /** + * Allows signing in with an OIDC ID token. The authentication provider used + * should be enabled and configured. + */ + async signInWithIdToken(credentials: SignInWithIdTokenCredentials): Promise { + try { + const { options, provider, token, access_token, nonce } = credentials + + const res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=id_token`, { + headers: this.headers, + body: { + provider, + id_token: token, + access_token, + nonce, + gotrue_meta_security: { captcha_token: options?.captchaToken }, + }, + xform: _sessionResponse, + }) + + const { data, error } = res + if (error) { + return this._returnResult({ data: { user: null, session: null }, error }) + } else if (!data || !data.session || !data.user) { + const invalidTokenError = new AuthInvalidTokenResponseError() + return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError }) + } + if (data.session) { + await this._saveSession(data.session) + await this._notifyAllSubscribers('SIGNED_IN', data.session) + } + return this._returnResult({ data, error }) + } catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: { user: null, session: null }, error }) + } + throw error + } + } + + /** + * Log in a user using magiclink or a one-time password (OTP). + * + * If the `{{ .ConfirmationURL }}` variable is specified in the email template, a magiclink will be sent. + * If the `{{ .Token }}` variable is specified in the email template, an OTP will be sent. + * If you're using phone sign-ins, only an OTP will be sent. You won't be able to send a magiclink for phone sign-ins. + * + * Be aware that you may get back an error message that will not distinguish + * between the cases where the account does not exist or, that the account + * can only be accessed via social login. + * + * Do note that you will need to configure a Whatsapp sender on Twilio + * if you are using phone sign in with the 'whatsapp' channel. The whatsapp + * channel is not supported on other providers + * at this time. + * This method supports PKCE when an email is passed. + */ + async signInWithOtp(credentials: SignInWithPasswordlessCredentials): Promise { + try { + if ('email' in credentials) { + const { email, options } = credentials + let codeChallenge: string | null = null + let codeChallengeMethod: string | null = null + if (this.flowType === 'pkce') { + ;[codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod( + this.storage, + this.storageKey + ) + } + const { error } = await _request(this.fetch, 'POST', `${this.url}/otp`, { + headers: this.headers, + body: { + email, + data: options?.data ?? {}, + create_user: options?.shouldCreateUser ?? true, + gotrue_meta_security: { captcha_token: options?.captchaToken }, + code_challenge: codeChallenge, + code_challenge_method: codeChallengeMethod, + }, + redirectTo: options?.emailRedirectTo, + }) + return this._returnResult({ data: { user: null, session: null }, error }) + } + if ('phone' in credentials) { + const { phone, options } = credentials + const { data, error } = await _request(this.fetch, 'POST', `${this.url}/otp`, { + headers: this.headers, + body: { + phone, + data: options?.data ?? {}, + create_user: options?.shouldCreateUser ?? true, + gotrue_meta_security: { captcha_token: options?.captchaToken }, + channel: options?.channel ?? 'sms', + }, + }) + return this._returnResult({ + data: { user: null, session: null, messageId: data?.message_id }, + error, + }) + } + throw new AuthInvalidCredentialsError('You must provide either an email or phone number.') + } catch (error) { + await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`) + if (isAuthError(error)) { + return this._returnResult({ data: { user: null, session: null }, error }) + } + + throw error + } + } + + /** + * Log in a user given a User supplied OTP or TokenHash received through mobile or email. + */ + async verifyOtp(params: VerifyOtpParams): Promise { + try { + let redirectTo: string | undefined = undefined + let captchaToken: string | undefined = undefined + if ('options' in params) { + redirectTo = params.options?.redirectTo + captchaToken = params.options?.captchaToken + } + const { data, error } = await _request(this.fetch, 'POST', `${this.url}/verify`, { + headers: this.headers, + body: { + ...params, + gotrue_meta_security: { captcha_token: captchaToken }, + }, + redirectTo, + xform: _sessionResponse, + }) + + if (error) { + throw error + } + if (!data) { + const tokenVerificationError = new Error('An error occurred on token verification.') + throw tokenVerificationError + } + + const session: Session | null = data.session + const user: User = data.user + + if (session?.access_token) { + await this._saveSession(session as Session) + await this._notifyAllSubscribers( + params.type == 'recovery' ? 'PASSWORD_RECOVERY' : 'SIGNED_IN', + session + ) + } + + return this._returnResult({ data: { user, session }, error: null }) + } catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: { user: null, session: null }, error }) + } + + throw error + } + } + + /** + * Attempts a single-sign on using an enterprise Identity Provider. A + * successful SSO attempt will redirect the current page to the identity + * provider authorization page. The redirect URL is implementation and SSO + * protocol specific. + * + * You can use it by providing a SSO domain. Typically you can extract this + * domain by asking users for their email address. If this domain is + * registered on the Auth instance the redirect will use that organization's + * currently active SSO Identity Provider for the login. + * + * If you have built an organization-specific login page, you can use the + * organization's SSO Identity Provider UUID directly instead. + */ + async signInWithSSO(params: SignInWithSSO): Promise { + try { + let codeChallenge: string | null = null + let codeChallengeMethod: string | null = null + if (this.flowType === 'pkce') { + ;[codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod( + this.storage, + this.storageKey + ) + } + + const result = await _request(this.fetch, 'POST', `${this.url}/sso`, { + body: { + ...('providerId' in params ? { provider_id: params.providerId } : null), + ...('domain' in params ? { domain: params.domain } : null), + redirect_to: params.options?.redirectTo ?? undefined, + ...(params?.options?.captchaToken + ? { gotrue_meta_security: { captcha_token: params.options.captchaToken } } + : null), + skip_http_redirect: true, // fetch does not handle redirects + code_challenge: codeChallenge, + code_challenge_method: codeChallengeMethod, + }, + headers: this.headers, + xform: _ssoResponse, + }) + + // Automatically redirect in browser unless skipBrowserRedirect is true + if (result.data?.url && isBrowser() && !params.options?.skipBrowserRedirect) { + window.location.assign(result.data.url) + } + + return this._returnResult(result) + } catch (error) { + await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`) + if (isAuthError(error)) { + return this._returnResult({ data: null, error }) + } + throw error + } + } + + /** + * Sends a reauthentication OTP to the user's email or phone number. + * Requires the user to be signed-in. + */ + async reauthenticate(): Promise { + await this.initializePromise + + return await this._acquireLock(-1, async () => { + return await this._reauthenticate() + }) + } + + private async _reauthenticate(): Promise { + try { + return await this._useSession(async (result) => { + const { + data: { session }, + error: sessionError, + } = result + if (sessionError) throw sessionError + if (!session) throw new AuthSessionMissingError() + + const { error } = await _request(this.fetch, 'GET', `${this.url}/reauthenticate`, { + headers: this.headers, + jwt: session.access_token, + }) + return this._returnResult({ data: { user: null, session: null }, error }) + }) + } catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: { user: null, session: null }, error }) + } + throw error + } + } + + /** + * Resends an existing signup confirmation email, email change email, SMS OTP or phone change OTP. + */ + async resend(credentials: ResendParams): Promise { + try { + const endpoint = `${this.url}/resend` + if ('email' in credentials) { + const { email, type, options } = credentials + const { error } = await _request(this.fetch, 'POST', endpoint, { + headers: this.headers, + body: { + email, + type, + gotrue_meta_security: { captcha_token: options?.captchaToken }, + }, + redirectTo: options?.emailRedirectTo, + }) + return this._returnResult({ data: { user: null, session: null }, error }) + } else if ('phone' in credentials) { + const { phone, type, options } = credentials + const { data, error } = await _request(this.fetch, 'POST', endpoint, { + headers: this.headers, + body: { + phone, + type, + gotrue_meta_security: { captcha_token: options?.captchaToken }, + }, + }) + return this._returnResult({ + data: { user: null, session: null, messageId: data?.message_id }, + error, + }) + } + throw new AuthInvalidCredentialsError( + 'You must provide either an email or phone number and a type' + ) + } catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: { user: null, session: null }, error }) + } + throw error + } + } + + /** + * Returns the session, refreshing it if necessary. + * + * The session returned can be null if the session is not detected which can happen in the event a user is not signed-in or has logged out. + * + * **IMPORTANT:** This method loads values directly from the storage attached + * to the client. If that storage is based on request cookies for example, + * the values in it may not be authentic and therefore it's strongly advised + * against using this method and its results in such circumstances. A warning + * will be emitted if this is detected. Use {@link #getUser()} instead. + */ + async getSession() { + await this.initializePromise + + const result = await this._acquireLock(-1, async () => { + return this._useSession(async (result) => { + return result + }) + }) + + return result + } + + /** + * Acquires a global lock based on the storage key. + */ + private async _acquireLock(acquireTimeout: number, fn: () => Promise): Promise { + this._debug('#_acquireLock', 'begin', acquireTimeout) + + try { + if (this.lockAcquired) { + const last = this.pendingInLock.length + ? this.pendingInLock[this.pendingInLock.length - 1] + : Promise.resolve() + + const result = (async () => { + await last + return await fn() + })() + + this.pendingInLock.push( + (async () => { + try { + await result + } catch (e: any) { + // we just care if it finished + } + })() + ) + + return result + } + + return await this.lock(`lock:${this.storageKey}`, acquireTimeout, async () => { + this._debug('#_acquireLock', 'lock acquired for storage key', this.storageKey) + + try { + this.lockAcquired = true + + const result = fn() + + this.pendingInLock.push( + (async () => { + try { + await result + } catch (e: any) { + // we just care if it finished + } + })() + ) + + await result + + // keep draining the queue until there's nothing to wait on + while (this.pendingInLock.length) { + const waitOn = [...this.pendingInLock] + + await Promise.all(waitOn) + + this.pendingInLock.splice(0, waitOn.length) + } + + return await result + } finally { + this._debug('#_acquireLock', 'lock released for storage key', this.storageKey) + + this.lockAcquired = false + } + }) + } finally { + this._debug('#_acquireLock', 'end') + } + } + + /** + * Use instead of {@link #getSession} inside the library. It is + * semantically usually what you want, as getting a session involves some + * processing afterwards that requires only one client operating on the + * session at once across multiple tabs or processes. + */ + private async _useSession( + fn: ( + result: + | { + data: { + session: Session + } + error: null + } + | { + data: { + session: null + } + error: AuthError + } + | { + data: { + session: null + } + error: null + } + ) => Promise + ): Promise { + this._debug('#_useSession', 'begin') + + try { + // the use of __loadSession here is the only correct use of the function! + const result = await this.__loadSession() + + return await fn(result) + } finally { + this._debug('#_useSession', 'end') + } + } + + /** + * NEVER USE DIRECTLY! + * + * Always use {@link #_useSession}. + */ + private async __loadSession(): Promise< + | { + data: { + session: Session + } + error: null + } + | { + data: { + session: null + } + error: AuthError + } + | { + data: { + session: null + } + error: null + } + > { + this._debug('#__loadSession()', 'begin') + + if (!this.lockAcquired) { + this._debug('#__loadSession()', 'used outside of an acquired lock!', new Error().stack) + } + + try { + let currentSession: Session | null = null + + const maybeSession = await getItemAsync(this.storage, this.storageKey) + + this._debug('#getSession()', 'session from storage', maybeSession) + + if (maybeSession !== null) { + if (this._isValidSession(maybeSession)) { + currentSession = maybeSession + } else { + this._debug('#getSession()', 'session from storage is not valid') + await this._removeSession() + } + } + + if (!currentSession) { + return { data: { session: null }, error: null } + } + + // A session is considered expired before the access token _actually_ + // expires. When the autoRefreshToken option is off (or when the tab is + // in the background), very eager users of getSession() -- like + // realtime-js -- might send a valid JWT which will expire by the time it + // reaches the server. + const hasExpired = currentSession.expires_at + ? currentSession.expires_at * 1000 - Date.now() < EXPIRY_MARGIN_MS + : false + + this._debug( + '#__loadSession()', + `session has${hasExpired ? '' : ' not'} expired`, + 'expires_at', + currentSession.expires_at + ) + + if (!hasExpired) { + if (this.userStorage) { + const maybeUser: { user?: User | null } | null = (await getItemAsync( + this.userStorage, + this.storageKey + '-user' + )) as any + + if (maybeUser?.user) { + currentSession.user = maybeUser.user + } else { + currentSession.user = userNotAvailableProxy() + } + } + + // Wrap the user object with a warning proxy on the server + // This warns when properties of the user are accessed, not when session.user itself is accessed + if ( + this.storage.isServer && + currentSession.user && + !(currentSession.user as any).__isUserNotAvailableProxy + ) { + const suppressWarningRef = { value: this.suppressGetSessionWarning } + currentSession.user = insecureUserWarningProxy(currentSession.user, suppressWarningRef) + + // Update the client-level suppression flag when the proxy suppresses the warning + if (suppressWarningRef.value) { + this.suppressGetSessionWarning = true + } + } + + return { data: { session: currentSession }, error: null } + } + + const { data: session, error } = await this._callRefreshToken(currentSession.refresh_token) + if (error) { + return this._returnResult({ data: { session: null }, error }) + } + + return this._returnResult({ data: { session }, error: null }) + } finally { + this._debug('#__loadSession()', 'end') + } + } + + /** + * Gets the current user details if there is an existing session. This method + * performs a network request to the Supabase Auth server, so the returned + * value is authentic and can be used to base authorization rules on. + * + * @param jwt Takes in an optional access token JWT. If no JWT is provided, the JWT from the current session is used. + */ + async getUser(jwt?: string): Promise { + if (jwt) { + return await this._getUser(jwt) + } + + await this.initializePromise + + const result = await this._acquireLock(-1, async () => { + return await this._getUser() + }) + + if (result.data.user) { + this.suppressGetSessionWarning = true + } + + return result + } + + private async _getUser(jwt?: string): Promise { + try { + if (jwt) { + return await _request(this.fetch, 'GET', `${this.url}/user`, { + headers: this.headers, + jwt: jwt, + xform: _userResponse, + }) + } + + return await this._useSession(async (result) => { + const { data, error } = result + if (error) { + throw error + } + + // returns an error if there is no access_token or custom authorization header + if (!data.session?.access_token && !this.hasCustomAuthorizationHeader) { + return { data: { user: null }, error: new AuthSessionMissingError() } + } + + return await _request(this.fetch, 'GET', `${this.url}/user`, { + headers: this.headers, + jwt: data.session?.access_token ?? undefined, + xform: _userResponse, + }) + }) + } catch (error) { + if (isAuthError(error)) { + if (isAuthSessionMissingError(error)) { + // JWT contains a `session_id` which does not correspond to an active + // session in the database, indicating the user is signed out. + + await this._removeSession() + await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`) + } + + return this._returnResult({ data: { user: null }, error }) + } + + throw error + } + } + + /** + * Updates user data for a logged in user. + */ + async updateUser( + attributes: UserAttributes, + options: { + emailRedirectTo?: string | undefined + } = {} + ): Promise { + await this.initializePromise + + return await this._acquireLock(-1, async () => { + return await this._updateUser(attributes, options) + }) + } + + protected async _updateUser( + attributes: UserAttributes, + options: { + emailRedirectTo?: string | undefined + } = {} + ): Promise { + try { + return await this._useSession(async (result) => { + const { data: sessionData, error: sessionError } = result + if (sessionError) { + throw sessionError + } + if (!sessionData.session) { + throw new AuthSessionMissingError() + } + const session: Session = sessionData.session + let codeChallenge: string | null = null + let codeChallengeMethod: string | null = null + if (this.flowType === 'pkce' && attributes.email != null) { + ;[codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod( + this.storage, + this.storageKey + ) + } + + const { data, error: userError } = await _request(this.fetch, 'PUT', `${this.url}/user`, { + headers: this.headers, + redirectTo: options?.emailRedirectTo, + body: { + ...attributes, + code_challenge: codeChallenge, + code_challenge_method: codeChallengeMethod, + }, + jwt: session.access_token, + xform: _userResponse, + }) + if (userError) { + throw userError + } + session.user = data.user as User + await this._saveSession(session) + await this._notifyAllSubscribers('USER_UPDATED', session) + return this._returnResult({ data: { user: session.user }, error: null }) + }) + } catch (error) { + await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`) + if (isAuthError(error)) { + return this._returnResult({ data: { user: null }, error }) + } + + throw error + } + } + + /** + * Sets the session data from the current session. If the current session is expired, setSession will take care of refreshing it to obtain a new session. + * If the refresh token or access token in the current session is invalid, an error will be thrown. + * @param currentSession The current session that minimally contains an access token and refresh token. + */ + async setSession(currentSession: { + access_token: string + refresh_token: string + }): Promise { + await this.initializePromise + + return await this._acquireLock(-1, async () => { + return await this._setSession(currentSession) + }) + } + + protected async _setSession(currentSession: { + access_token: string + refresh_token: string + }): Promise { + try { + if (!currentSession.access_token || !currentSession.refresh_token) { + throw new AuthSessionMissingError() + } + + const timeNow = Date.now() / 1000 + let expiresAt = timeNow + let hasExpired = true + let session: Session | null = null + const { payload } = decodeJWT(currentSession.access_token) + if (payload.exp) { + expiresAt = payload.exp + hasExpired = expiresAt <= timeNow + } + + if (hasExpired) { + const { data: refreshedSession, error } = await this._callRefreshToken( + currentSession.refresh_token + ) + if (error) { + return this._returnResult({ data: { user: null, session: null }, error: error }) + } + + if (!refreshedSession) { + return { data: { user: null, session: null }, error: null } + } + session = refreshedSession + } else { + const { data, error } = await this._getUser(currentSession.access_token) + if (error) { + throw error + } + session = { + access_token: currentSession.access_token, + refresh_token: currentSession.refresh_token, + user: data.user, + token_type: 'bearer', + expires_in: expiresAt - timeNow, + expires_at: expiresAt, + } + await this._saveSession(session) + await this._notifyAllSubscribers('SIGNED_IN', session) + } + + return this._returnResult({ data: { user: session.user, session }, error: null }) + } catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: { session: null, user: null }, error }) + } + + throw error + } + } + + /** + * Returns a new session, regardless of expiry status. + * Takes in an optional current session. If not passed in, then refreshSession() will attempt to retrieve it from getSession(). + * If the current session's refresh token is invalid, an error will be thrown. + * @param currentSession The current session. If passed in, it must contain a refresh token. + */ + async refreshSession(currentSession?: { refresh_token: string }): Promise { + await this.initializePromise + + return await this._acquireLock(-1, async () => { + return await this._refreshSession(currentSession) + }) + } + + protected async _refreshSession(currentSession?: { + refresh_token: string + }): Promise { + try { + return await this._useSession(async (result) => { + if (!currentSession) { + const { data, error } = result + if (error) { + throw error + } + + currentSession = data.session ?? undefined + } + + if (!currentSession?.refresh_token) { + throw new AuthSessionMissingError() + } + + const { data: session, error } = await this._callRefreshToken(currentSession.refresh_token) + if (error) { + return this._returnResult({ data: { user: null, session: null }, error: error }) + } + + if (!session) { + return this._returnResult({ data: { user: null, session: null }, error: null }) + } + + return this._returnResult({ data: { user: session.user, session }, error: null }) + }) + } catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: { user: null, session: null }, error }) + } + + throw error + } + } + + /** + * Gets the session data from a URL string + */ + private async _getSessionFromURL( + params: { [parameter: string]: string }, + callbackUrlType: string + ): Promise< + | { + data: { session: Session; redirectType: string | null } + error: null + } + | { data: { session: null; redirectType: null }; error: AuthError } + > { + try { + if (!isBrowser()) throw new AuthImplicitGrantRedirectError('No browser detected.') + + // If there's an error in the URL, it doesn't matter what flow it is, we just return the error. + if (params.error || params.error_description || params.error_code) { + // The error class returned implies that the redirect is from an implicit grant flow + // but it could also be from a redirect error from a PKCE flow. + throw new AuthImplicitGrantRedirectError( + params.error_description || 'Error in URL with unspecified error_description', + { + error: params.error || 'unspecified_error', + code: params.error_code || 'unspecified_code', + } + ) + } + + // Checks for mismatches between the flowType initialised in the client and the URL parameters + switch (callbackUrlType) { + case 'implicit': + if (this.flowType === 'pkce') { + throw new AuthPKCEGrantCodeExchangeError('Not a valid PKCE flow url.') + } + break + case 'pkce': + if (this.flowType === 'implicit') { + throw new AuthImplicitGrantRedirectError('Not a valid implicit grant flow url.') + } + break + default: + // there's no mismatch so we continue + } + + // Since this is a redirect for PKCE, we attempt to retrieve the code from the URL for the code exchange + if (callbackUrlType === 'pkce') { + this._debug('#_initialize()', 'begin', 'is PKCE flow', true) + if (!params.code) throw new AuthPKCEGrantCodeExchangeError('No code detected.') + const { data, error } = await this._exchangeCodeForSession(params.code) + if (error) throw error + + const url = new URL(window.location.href) + url.searchParams.delete('code') + + window.history.replaceState(window.history.state, '', url.toString()) + + return { data: { session: data.session, redirectType: null }, error: null } + } + + const { + provider_token, + provider_refresh_token, + access_token, + refresh_token, + expires_in, + expires_at, + token_type, + } = params + + if (!access_token || !expires_in || !refresh_token || !token_type) { + throw new AuthImplicitGrantRedirectError('No session defined in URL') + } + + const timeNow = Math.round(Date.now() / 1000) + const expiresIn = parseInt(expires_in) + let expiresAt = timeNow + expiresIn + + if (expires_at) { + expiresAt = parseInt(expires_at) + } + + const actuallyExpiresIn = expiresAt - timeNow + if (actuallyExpiresIn * 1000 <= AUTO_REFRESH_TICK_DURATION_MS) { + console.warn( + `@supabase/gotrue-js: Session as retrieved from URL expires in ${actuallyExpiresIn}s, should have been closer to ${expiresIn}s` + ) + } + + const issuedAt = expiresAt - expiresIn + if (timeNow - issuedAt >= 120) { + console.warn( + '@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale', + issuedAt, + expiresAt, + timeNow + ) + } else if (timeNow - issuedAt < 0) { + console.warn( + '@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew', + issuedAt, + expiresAt, + timeNow + ) + } + + const { data, error } = await this._getUser(access_token) + if (error) throw error + + const session: Session = { + provider_token, + provider_refresh_token, + access_token, + expires_in: expiresIn, + expires_at: expiresAt, + refresh_token, + token_type: token_type as 'bearer', + user: data.user, + } + + // Remove tokens from URL + window.location.hash = '' + this._debug('#_getSessionFromURL()', 'clearing window.location.hash') + + return this._returnResult({ data: { session, redirectType: params.type }, error: null }) + } catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: { session: null, redirectType: null }, error }) + } + + throw error + } + } + + /** + * Checks if the current URL contains parameters given by an implicit oauth grant flow (https://www.rfc-editor.org/rfc/rfc6749.html#section-4.2) + */ + private _isImplicitGrantCallback(params: { [parameter: string]: string }): boolean { + return Boolean(params.access_token || params.error_description) + } + + /** + * Checks if the current URL and backing storage contain parameters given by a PKCE flow + */ + private async _isPKCECallback(params: { [parameter: string]: string }): Promise { + const currentStorageContent = await getItemAsync( + this.storage, + `${this.storageKey}-code-verifier` + ) + + return !!(params.code && currentStorageContent) + } + + /** + * Inside a browser context, `signOut()` will remove the logged in user from the browser session and log them out - removing all items from localstorage and then trigger a `"SIGNED_OUT"` event. + * + * For server-side management, you can revoke all refresh tokens for a user by passing a user's JWT through to `auth.api.signOut(JWT: string)`. + * There is no way to revoke a user's access token jwt until it expires. It is recommended to set a shorter expiry on the jwt for this reason. + * + * If using `others` scope, no `SIGNED_OUT` event is fired! + */ + async signOut(options: SignOut = { scope: 'global' }): Promise<{ error: AuthError | null }> { + await this.initializePromise + + return await this._acquireLock(-1, async () => { + return await this._signOut(options) + }) + } + + protected async _signOut( + { scope }: SignOut = { scope: 'global' } + ): Promise<{ error: AuthError | null }> { + return await this._useSession(async (result) => { + const { data, error: sessionError } = result + if (sessionError) { + return this._returnResult({ error: sessionError }) + } + const accessToken = data.session?.access_token + if (accessToken) { + const { error } = await this.admin.signOut(accessToken, scope) + if (error) { + // ignore 404s since user might not exist anymore + // ignore 401s since an invalid or expired JWT should sign out the current session + if ( + !( + isAuthApiError(error) && + (error.status === 404 || error.status === 401 || error.status === 403) + ) + ) { + return this._returnResult({ error }) + } + } + } + if (scope !== 'others') { + await this._removeSession() + await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`) + } + return this._returnResult({ error: null }) + }) + } + + /** + * Receive a notification every time an auth event happens. + * Safe to use without an async function as callback. + * + * @param callback A callback function to be invoked when an auth event happens. + */ + onAuthStateChange(callback: (event: AuthChangeEvent, session: Session | null) => void): { + data: { subscription: Subscription } + } + + /** + * Avoid using an async function inside `onAuthStateChange` as you might end + * up with a deadlock. The callback function runs inside an exclusive lock, + * so calling other Supabase Client APIs that also try to acquire the + * exclusive lock, might cause a deadlock. This behavior is observable across + * tabs. In the next major library version, this behavior will not be supported. + * + * Receive a notification every time an auth event happens. + * + * @param callback A callback function to be invoked when an auth event happens. + * @deprecated Due to the possibility of deadlocks with async functions as callbacks, use the version without an async function. + */ + onAuthStateChange(callback: (event: AuthChangeEvent, session: Session | null) => Promise): { + data: { subscription: Subscription } + } + + onAuthStateChange( + callback: (event: AuthChangeEvent, session: Session | null) => void | Promise + ): { + data: { subscription: Subscription } + } { + const id: string | symbol = generateCallbackId() + const subscription: Subscription = { + id, + callback, + unsubscribe: () => { + this._debug('#unsubscribe()', 'state change callback with id removed', id) + + this.stateChangeEmitters.delete(id) + }, + } + + this._debug('#onAuthStateChange()', 'registered callback with id', id) + + this.stateChangeEmitters.set(id, subscription) + ;(async () => { + await this.initializePromise + + await this._acquireLock(-1, async () => { + this._emitInitialSession(id) + }) + })() + + return { data: { subscription } } + } + + private async _emitInitialSession(id: string | symbol): Promise { + return await this._useSession(async (result) => { + try { + const { + data: { session }, + error, + } = result + if (error) throw error + + await this.stateChangeEmitters.get(id)?.callback('INITIAL_SESSION', session) + this._debug('INITIAL_SESSION', 'callback id', id, 'session', session) + } catch (err) { + await this.stateChangeEmitters.get(id)?.callback('INITIAL_SESSION', null) + this._debug('INITIAL_SESSION', 'callback id', id, 'error', err) + console.error(err) + } + }) + } + + /** + * Sends a password reset request to an email address. This method supports the PKCE flow. + * + * @param email The email address of the user. + * @param options.redirectTo The URL to send the user to after they click the password reset link. + * @param options.captchaToken Verification token received when the user completes the captcha on the site. + */ + async resetPasswordForEmail( + email: string, + options: { + redirectTo?: string + captchaToken?: string + } = {} + ): Promise< + | { + data: {} + error: null + } + | { data: null; error: AuthError } + > { + let codeChallenge: string | null = null + let codeChallengeMethod: string | null = null + + if (this.flowType === 'pkce') { + ;[codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod( + this.storage, + this.storageKey, + true // isPasswordRecovery + ) + } + try { + return await _request(this.fetch, 'POST', `${this.url}/recover`, { + body: { + email, + code_challenge: codeChallenge, + code_challenge_method: codeChallengeMethod, + gotrue_meta_security: { captcha_token: options.captchaToken }, + }, + headers: this.headers, + redirectTo: options.redirectTo, + }) + } catch (error) { + await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`) + if (isAuthError(error)) { + return this._returnResult({ data: null, error }) + } + + throw error + } + } + + /** + * Gets all the identities linked to a user. + */ + async getUserIdentities(): Promise< + | { + data: { + identities: UserIdentity[] + } + error: null + } + | { data: null; error: AuthError } + > { + try { + const { data, error } = await this.getUser() + if (error) throw error + return this._returnResult({ data: { identities: data.user.identities ?? [] }, error: null }) + } catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: null, error }) + } + throw error + } + } + + /** + * Links an oauth identity to an existing user. + * This method supports the PKCE flow. + */ + async linkIdentity(credentials: SignInWithOAuthCredentials): Promise + + /** + * Links an OIDC identity to an existing user. + */ + async linkIdentity(credentials: SignInWithIdTokenCredentials): Promise + + async linkIdentity(credentials: any): Promise { + if ('token' in credentials) { + return this.linkIdentityIdToken(credentials) + } + + return this.linkIdentityOAuth(credentials) + } + + private async linkIdentityOAuth(credentials: SignInWithOAuthCredentials): Promise { + try { + const { data, error } = await this._useSession(async (result) => { + const { data, error } = result + if (error) throw error + const url: string = await this._getUrlForProvider( + `${this.url}/user/identities/authorize`, + credentials.provider, + { + redirectTo: credentials.options?.redirectTo, + scopes: credentials.options?.scopes, + queryParams: credentials.options?.queryParams, + skipBrowserRedirect: true, + } + ) + return await _request(this.fetch, 'GET', url, { + headers: this.headers, + jwt: data.session?.access_token ?? undefined, + }) + }) + if (error) throw error + if (isBrowser() && !credentials.options?.skipBrowserRedirect) { + window.location.assign(data?.url) + } + return this._returnResult({ + data: { provider: credentials.provider, url: data?.url }, + error: null, + }) + } catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: { provider: credentials.provider, url: null }, error }) + } + throw error + } + } + + private async linkIdentityIdToken( + credentials: SignInWithIdTokenCredentials + ): Promise { + return await this._useSession(async (result) => { + try { + const { + error: sessionError, + data: { session }, + } = result + if (sessionError) throw sessionError + + const { options, provider, token, access_token, nonce } = credentials + + const res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=id_token`, { + headers: this.headers, + jwt: session?.access_token ?? undefined, + body: { + provider, + id_token: token, + access_token, + nonce, + link_identity: true, + gotrue_meta_security: { captcha_token: options?.captchaToken }, + }, + xform: _sessionResponse, + }) + + const { data, error } = res + if (error) { + return this._returnResult({ data: { user: null, session: null }, error }) + } else if (!data || !data.session || !data.user) { + return this._returnResult({ + data: { user: null, session: null }, + error: new AuthInvalidTokenResponseError(), + }) + } + if (data.session) { + await this._saveSession(data.session) + await this._notifyAllSubscribers('USER_UPDATED', data.session) + } + return this._returnResult({ data, error }) + } catch (error) { + await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`) + if (isAuthError(error)) { + return this._returnResult({ data: { user: null, session: null }, error }) + } + throw error + } + }) + } + + /** + * Unlinks an identity from a user by deleting it. The user will no longer be able to sign in with that identity once it's unlinked. + */ + async unlinkIdentity(identity: UserIdentity): Promise< + | { + data: {} + error: null + } + | { data: null; error: AuthError } + > { + try { + return await this._useSession(async (result) => { + const { data, error } = result + if (error) { + throw error + } + return await _request( + this.fetch, + 'DELETE', + `${this.url}/user/identities/${identity.identity_id}`, + { + headers: this.headers, + jwt: data.session?.access_token ?? undefined, + } + ) + }) + } catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: null, error }) + } + throw error + } + } + + /** + * Generates a new JWT. + * @param refreshToken A valid refresh token that was returned on login. + */ + private async _refreshAccessToken(refreshToken: string): Promise { + const debugName = `#_refreshAccessToken(${refreshToken.substring(0, 5)}...)` + this._debug(debugName, 'begin') + + try { + const startedAt = Date.now() + + // will attempt to refresh the token with exponential backoff + return await retryable( + async (attempt) => { + if (attempt > 0) { + await sleep(200 * Math.pow(2, attempt - 1)) // 200, 400, 800, ... + } + + this._debug(debugName, 'refreshing attempt', attempt) + + return await _request(this.fetch, 'POST', `${this.url}/token?grant_type=refresh_token`, { + body: { refresh_token: refreshToken }, + headers: this.headers, + xform: _sessionResponse, + }) + }, + (attempt, error) => { + const nextBackOffInterval = 200 * Math.pow(2, attempt) + return ( + error && + isAuthRetryableFetchError(error) && + // retryable only if the request can be sent before the backoff overflows the tick duration + Date.now() + nextBackOffInterval - startedAt < AUTO_REFRESH_TICK_DURATION_MS + ) + } + ) + } catch (error) { + this._debug(debugName, 'error', error) + + if (isAuthError(error)) { + return this._returnResult({ data: { session: null, user: null }, error }) + } + throw error + } finally { + this._debug(debugName, 'end') + } + } + + private _isValidSession(maybeSession: unknown): maybeSession is Session { + const isValidSession = + typeof maybeSession === 'object' && + maybeSession !== null && + 'access_token' in maybeSession && + 'refresh_token' in maybeSession && + 'expires_at' in maybeSession + + return isValidSession + } + + private async _handleProviderSignIn( + provider: Provider, + options: { + redirectTo?: string + scopes?: string + queryParams?: { [key: string]: string } + skipBrowserRedirect?: boolean + } + ) { + const url: string = await this._getUrlForProvider(`${this.url}/authorize`, provider, { + redirectTo: options.redirectTo, + scopes: options.scopes, + queryParams: options.queryParams, + }) + + this._debug('#_handleProviderSignIn()', 'provider', provider, 'options', options, 'url', url) + + // try to open on the browser + if (isBrowser() && !options.skipBrowserRedirect) { + window.location.assign(url) + } + + return { data: { provider, url }, error: null } + } + + /** + * Recovers the session from LocalStorage and refreshes the token + * Note: this method is async to accommodate for AsyncStorage e.g. in React native. + */ + private async _recoverAndRefresh() { + const debugName = '#_recoverAndRefresh()' + this._debug(debugName, 'begin') + + try { + const currentSession = (await getItemAsync(this.storage, this.storageKey)) as Session | null + + if (currentSession && this.userStorage) { + let maybeUser: { user: User | null } | null = (await getItemAsync( + this.userStorage, + this.storageKey + '-user' + )) as any + + if (!this.storage.isServer && Object.is(this.storage, this.userStorage) && !maybeUser) { + // storage and userStorage are the same storage medium, for example + // window.localStorage if userStorage does not have the user from + // storage stored, store it first thereby migrating the user object + // from storage -> userStorage + + maybeUser = { user: currentSession.user } + await setItemAsync(this.userStorage, this.storageKey + '-user', maybeUser) + } + + currentSession.user = maybeUser?.user ?? userNotAvailableProxy() + } else if (currentSession && !currentSession.user) { + // user storage is not set, let's check if it was previously enabled so + // we bring back the storage as it should be + + if (!currentSession.user) { + // test if userStorage was previously enabled and the storage medium was the same, to move the user back under the same key + const separateUser: { user: User | null } | null = (await getItemAsync( + this.storage, + this.storageKey + '-user' + )) as any + + if (separateUser && separateUser?.user) { + currentSession.user = separateUser.user + + await removeItemAsync(this.storage, this.storageKey + '-user') + await setItemAsync(this.storage, this.storageKey, currentSession) + } else { + currentSession.user = userNotAvailableProxy() + } + } + } + + this._debug(debugName, 'session from storage', currentSession) + + if (!this._isValidSession(currentSession)) { + this._debug(debugName, 'session is not valid') + if (currentSession !== null) { + await this._removeSession() + } + + return + } + + const expiresWithMargin = + (currentSession.expires_at ?? Infinity) * 1000 - Date.now() < EXPIRY_MARGIN_MS + + this._debug( + debugName, + `session has${expiresWithMargin ? '' : ' not'} expired with margin of ${EXPIRY_MARGIN_MS}s` + ) + + if (expiresWithMargin) { + if (this.autoRefreshToken && currentSession.refresh_token) { + const { error } = await this._callRefreshToken(currentSession.refresh_token) + + if (error) { + console.error(error) + + if (!isAuthRetryableFetchError(error)) { + this._debug( + debugName, + 'refresh failed with a non-retryable error, removing the session', + error + ) + await this._removeSession() + } + } + } + } else if ( + currentSession.user && + (currentSession.user as any).__isUserNotAvailableProxy === true + ) { + // If we have a proxy user, try to get the real user data + try { + const { data, error: userError } = await this._getUser(currentSession.access_token) + + if (!userError && data?.user) { + currentSession.user = data.user + await this._saveSession(currentSession) + await this._notifyAllSubscribers('SIGNED_IN', currentSession) + } else { + this._debug(debugName, 'could not get user data, skipping SIGNED_IN notification') + } + } catch (getUserError) { + console.error('Error getting user data:', getUserError) + this._debug( + debugName, + 'error getting user data, skipping SIGNED_IN notification', + getUserError + ) + } + } else { + // no need to persist currentSession again, as we just loaded it from + // local storage; persisting it again may overwrite a value saved by + // another client with access to the same local storage + await this._notifyAllSubscribers('SIGNED_IN', currentSession) + } + } catch (err) { + this._debug(debugName, 'error', err) + + console.error(err) + return + } finally { + this._debug(debugName, 'end') + } + } + + private async _callRefreshToken(refreshToken: string): Promise { + if (!refreshToken) { + throw new AuthSessionMissingError() + } + + // refreshing is already in progress + if (this.refreshingDeferred) { + return this.refreshingDeferred.promise + } + + const debugName = `#_callRefreshToken(${refreshToken.substring(0, 5)}...)` + + this._debug(debugName, 'begin') + + try { + this.refreshingDeferred = new Deferred() + + const { data, error } = await this._refreshAccessToken(refreshToken) + if (error) throw error + if (!data.session) throw new AuthSessionMissingError() + + await this._saveSession(data.session) + await this._notifyAllSubscribers('TOKEN_REFRESHED', data.session) + + const result = { data: data.session, error: null } + + this.refreshingDeferred.resolve(result) + + return result + } catch (error) { + this._debug(debugName, 'error', error) + + if (isAuthError(error)) { + const result = { data: null, error } + + if (!isAuthRetryableFetchError(error)) { + await this._removeSession() + } + + this.refreshingDeferred?.resolve(result) + + return result + } + + this.refreshingDeferred?.reject(error) + throw error + } finally { + this.refreshingDeferred = null + this._debug(debugName, 'end') + } + } + + private async _notifyAllSubscribers( + event: AuthChangeEvent, + session: Session | null, + broadcast = true + ) { + const debugName = `#_notifyAllSubscribers(${event})` + this._debug(debugName, 'begin', session, `broadcast = ${broadcast}`) + + try { + if (this.broadcastChannel && broadcast) { + this.broadcastChannel.postMessage({ event, session }) + } + + const errors: any[] = [] + const promises = Array.from(this.stateChangeEmitters.values()).map(async (x) => { + try { + await x.callback(event, session) + } catch (e: any) { + errors.push(e) + } + }) + + await Promise.all(promises) + + if (errors.length > 0) { + for (let i = 0; i < errors.length; i += 1) { + console.error(errors[i]) + } + + throw errors[0] + } + } finally { + this._debug(debugName, 'end') + } + } + + /** + * set currentSession and currentUser + * process to _startAutoRefreshToken if possible + */ + private async _saveSession(session: Session) { + this._debug('#_saveSession()', session) + // _saveSession is always called whenever a new session has been acquired + // so we can safely suppress the warning returned by future getSession calls + this.suppressGetSessionWarning = true + await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`) + // Create a shallow copy to work with, to avoid mutating the original session object if it's used elsewhere + const sessionToProcess = { ...session } + + const userIsProxy = + sessionToProcess.user && (sessionToProcess.user as any).__isUserNotAvailableProxy === true + if (this.userStorage) { + if (!userIsProxy && sessionToProcess.user) { + // If it's a real user object, save it to userStorage. + await setItemAsync(this.userStorage, this.storageKey + '-user', { + user: sessionToProcess.user, + }) + } else if (userIsProxy) { + // If it's the proxy, it means user was not found in userStorage. + // We should ensure no stale user data for this key exists in userStorage if we were to save null, + // or simply not save the proxy. For now, we don't save the proxy here. + // If there's a need to clear userStorage if user becomes proxy, that logic would go here. + } + + // Prepare the main session data for primary storage: remove the user property before cloning + // This is important because the original session.user might be the proxy + const mainSessionData: Omit & { user?: User } = { ...sessionToProcess } + delete mainSessionData.user // Remove user (real or proxy) before cloning for main storage + + const clonedMainSessionData = deepClone(mainSessionData) + await setItemAsync(this.storage, this.storageKey, clonedMainSessionData) + } else { + // No userStorage is configured. + // In this case, session.user should ideally not be a proxy. + // If it were, structuredClone would fail. This implies an issue elsewhere if user is a proxy here + const clonedSession = deepClone(sessionToProcess) // sessionToProcess still has its original user property + await setItemAsync(this.storage, this.storageKey, clonedSession) + } + } + + private async _removeSession() { + this._debug('#_removeSession()') + + this.suppressGetSessionWarning = false + + await removeItemAsync(this.storage, this.storageKey) + await removeItemAsync(this.storage, this.storageKey + '-code-verifier') + await removeItemAsync(this.storage, this.storageKey + '-user') + + if (this.userStorage) { + await removeItemAsync(this.userStorage, this.storageKey + '-user') + } + + await this._notifyAllSubscribers('SIGNED_OUT', null) + } + + /** + * Removes any registered visibilitychange callback. + * + * {@see #startAutoRefresh} + * {@see #stopAutoRefresh} + */ + private _removeVisibilityChangedCallback() { + this._debug('#_removeVisibilityChangedCallback()') + + const callback = this.visibilityChangedCallback + this.visibilityChangedCallback = null + + try { + if (callback && isBrowser() && window?.removeEventListener) { + window.removeEventListener('visibilitychange', callback) + } + } catch (e) { + console.error('removing visibilitychange callback failed', e) + } + } + + /** + * This is the private implementation of {@link #startAutoRefresh}. Use this + * within the library. + */ + private async _startAutoRefresh() { + await this._stopAutoRefresh() + + this._debug('#_startAutoRefresh()') + + const ticker = setInterval(() => this._autoRefreshTokenTick(), AUTO_REFRESH_TICK_DURATION_MS) + this.autoRefreshTicker = ticker + + if (ticker && typeof ticker === 'object' && typeof ticker.unref === 'function') { + // ticker is a NodeJS Timeout object that has an `unref` method + // https://nodejs.org/api/timers.html#timeoutunref + // When auto refresh is used in NodeJS (like for testing) the + // `setInterval` is preventing the process from being marked as + // finished and tests run endlessly. This can be prevented by calling + // `unref()` on the returned object. + ticker.unref() + // @ts-expect-error TS has no context of Deno + } else if (typeof Deno !== 'undefined' && typeof Deno.unrefTimer === 'function') { + // similar like for NodeJS, but with the Deno API + // https://deno.land/api@latest?unstable&s=Deno.unrefTimer + // @ts-expect-error TS has no context of Deno + Deno.unrefTimer(ticker) + } + + // run the tick immediately, but in the next pass of the event loop so that + // #_initialize can be allowed to complete without recursively waiting on + // itself + setTimeout(async () => { + await this.initializePromise + await this._autoRefreshTokenTick() + }, 0) + } + + /** + * This is the private implementation of {@link #stopAutoRefresh}. Use this + * within the library. + */ + private async _stopAutoRefresh() { + this._debug('#_stopAutoRefresh()') + + const ticker = this.autoRefreshTicker + this.autoRefreshTicker = null + + if (ticker) { + clearInterval(ticker) + } + } + + /** + * Starts an auto-refresh process in the background. The session is checked + * every few seconds. Close to the time of expiration a process is started to + * refresh the session. If refreshing fails it will be retried for as long as + * necessary. + * + * If you set the {@link GoTrueClientOptions#autoRefreshToken} you don't need + * to call this function, it will be called for you. + * + * On browsers the refresh process works only when the tab/window is in the + * foreground to conserve resources as well as prevent race conditions and + * flooding auth with requests. If you call this method any managed + * visibility change callback will be removed and you must manage visibility + * changes on your own. + * + * On non-browser platforms the refresh process works *continuously* in the + * background, which may not be desirable. You should hook into your + * platform's foreground indication mechanism and call these methods + * appropriately to conserve resources. + * + * {@see #stopAutoRefresh} + */ + async startAutoRefresh() { + this._removeVisibilityChangedCallback() + await this._startAutoRefresh() + } + + /** + * Stops an active auto refresh process running in the background (if any). + * + * If you call this method any managed visibility change callback will be + * removed and you must manage visibility changes on your own. + * + * See {@link #startAutoRefresh} for more details. + */ + async stopAutoRefresh() { + this._removeVisibilityChangedCallback() + await this._stopAutoRefresh() + } + + /** + * Runs the auto refresh token tick. + */ + private async _autoRefreshTokenTick() { + this._debug('#_autoRefreshTokenTick()', 'begin') + + try { + await this._acquireLock(0, async () => { + try { + const now = Date.now() + + try { + return await this._useSession(async (result) => { + const { + data: { session }, + } = result + + if (!session || !session.refresh_token || !session.expires_at) { + this._debug('#_autoRefreshTokenTick()', 'no session') + return + } + + // session will expire in this many ticks (or has already expired if <= 0) + const expiresInTicks = Math.floor( + (session.expires_at * 1000 - now) / AUTO_REFRESH_TICK_DURATION_MS + ) + + this._debug( + '#_autoRefreshTokenTick()', + `access token expires in ${expiresInTicks} ticks, a tick lasts ${AUTO_REFRESH_TICK_DURATION_MS}ms, refresh threshold is ${AUTO_REFRESH_TICK_THRESHOLD} ticks` + ) + + if (expiresInTicks <= AUTO_REFRESH_TICK_THRESHOLD) { + await this._callRefreshToken(session.refresh_token) + } + }) + } catch (e: any) { + console.error( + 'Auto refresh tick failed with error. This is likely a transient error.', + e + ) + } + } finally { + this._debug('#_autoRefreshTokenTick()', 'end') + } + }) + } catch (e: any) { + if (e.isAcquireTimeout || e instanceof LockAcquireTimeoutError) { + this._debug('auto refresh token tick lock not available') + } else { + throw e + } + } + } + + /** + * Registers callbacks on the browser / platform, which in-turn run + * algorithms when the browser window/tab are in foreground. On non-browser + * platforms it assumes always foreground. + */ + private async _handleVisibilityChange() { + this._debug('#_handleVisibilityChange()') + + if (!isBrowser() || !window?.addEventListener) { + if (this.autoRefreshToken) { + // in non-browser environments the refresh token ticker runs always + this.startAutoRefresh() + } + + return false + } + + try { + this.visibilityChangedCallback = async () => await this._onVisibilityChanged(false) + + window?.addEventListener('visibilitychange', this.visibilityChangedCallback) + + // now immediately call the visbility changed callback to setup with the + // current visbility state + await this._onVisibilityChanged(true) // initial call + } catch (error) { + console.error('_handleVisibilityChange', error) + } + } + + /** + * Callback registered with `window.addEventListener('visibilitychange')`. + */ + private async _onVisibilityChanged(calledFromInitialize: boolean) { + const methodName = `#_onVisibilityChanged(${calledFromInitialize})` + this._debug(methodName, 'visibilityState', document.visibilityState) + + if (document.visibilityState === 'visible') { + if (this.autoRefreshToken) { + // in browser environments the refresh token ticker runs only on focused tabs + // which prevents race conditions + this._startAutoRefresh() + } + + if (!calledFromInitialize) { + // called when the visibility has changed, i.e. the browser + // transitioned from hidden -> visible so we need to see if the session + // should be recovered immediately... but to do that we need to acquire + // the lock first asynchronously + await this.initializePromise + + await this._acquireLock(-1, async () => { + if (document.visibilityState !== 'visible') { + this._debug( + methodName, + 'acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting' + ) + + // visibility has changed while waiting for the lock, abort + return + } + + // recover the session + await this._recoverAndRefresh() + }) + } + } else if (document.visibilityState === 'hidden') { + if (this.autoRefreshToken) { + this._stopAutoRefresh() + } + } + } + + /** + * Generates the relevant login URL for a third-party provider. + * @param options.redirectTo A URL or mobile address to send the user to after they are confirmed. + * @param options.scopes A space-separated list of scopes granted to the OAuth application. + * @param options.queryParams An object of key-value pairs containing query parameters granted to the OAuth application. + */ + private async _getUrlForProvider( + url: string, + provider: Provider, + options: { + redirectTo?: string + scopes?: string + queryParams?: { [key: string]: string } + skipBrowserRedirect?: boolean + } + ) { + const urlParams: string[] = [`provider=${encodeURIComponent(provider)}`] + if (options?.redirectTo) { + urlParams.push(`redirect_to=${encodeURIComponent(options.redirectTo)}`) + } + if (options?.scopes) { + urlParams.push(`scopes=${encodeURIComponent(options.scopes)}`) + } + if (this.flowType === 'pkce') { + const [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod( + this.storage, + this.storageKey + ) + + const flowParams = new URLSearchParams({ + code_challenge: `${encodeURIComponent(codeChallenge)}`, + code_challenge_method: `${encodeURIComponent(codeChallengeMethod)}`, + }) + urlParams.push(flowParams.toString()) + } + if (options?.queryParams) { + const query = new URLSearchParams(options.queryParams) + urlParams.push(query.toString()) + } + if (options?.skipBrowserRedirect) { + urlParams.push(`skip_http_redirect=${options.skipBrowserRedirect}`) + } + + return `${url}?${urlParams.join('&')}` + } + + private async _unenroll(params: MFAUnenrollParams): Promise { + try { + return await this._useSession(async (result) => { + const { data: sessionData, error: sessionError } = result + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }) + } + + return await _request(this.fetch, 'DELETE', `${this.url}/factors/${params.factorId}`, { + headers: this.headers, + jwt: sessionData?.session?.access_token, + }) + }) + } catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: null, error }) + } + throw error + } + } + + /** + * {@see GoTrueMFAApi#enroll} + */ + private async _enroll(params: MFAEnrollTOTPParams): Promise + private async _enroll(params: MFAEnrollPhoneParams): Promise + private async _enroll(params: MFAEnrollWebauthnParams): Promise + private async _enroll(params: MFAEnrollParams): Promise { + try { + return await this._useSession(async (result) => { + const { data: sessionData, error: sessionError } = result + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }) + } + + const body = { + friendly_name: params.friendlyName, + factor_type: params.factorType, + ...(params.factorType === 'phone' + ? { phone: params.phone } + : params.factorType === 'totp' + ? { issuer: params.issuer } + : {}), + } + + const { data, error } = (await _request(this.fetch, 'POST', `${this.url}/factors`, { + body, + headers: this.headers, + jwt: sessionData?.session?.access_token, + })) as AuthMFAEnrollResponse + if (error) { + return this._returnResult({ data: null, error }) + } + + if (params.factorType === 'totp' && data.type === 'totp' && data?.totp?.qr_code) { + data.totp.qr_code = `data:image/svg+xml;utf-8,${data.totp.qr_code}` + } + + return this._returnResult({ data, error: null }) + }) + } catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: null, error }) + } + throw error + } + } + + /** + * {@see GoTrueMFAApi#verify} + */ + private async _verify(params: MFAVerifyTOTPParams): Promise + private async _verify(params: MFAVerifyPhoneParams): Promise + private async _verify( + params: MFAVerifyWebauthnParams + ): Promise + private async _verify(params: MFAVerifyParams): Promise { + return this._acquireLock(-1, async () => { + try { + return await this._useSession(async (result) => { + const { data: sessionData, error: sessionError } = result + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }) + } + + const body: StrictOmit< + | Exclude + /** Exclude out the webauthn params from here because we're going to need to serialize them in the response */ + | Prettify< + StrictOmit & { + webauthn: Prettify< + StrictOmit & { + credential_response: PublicKeyCredentialJSON + } + > + } + >, + /* Exclude challengeId because the backend expects snake_case, and exclude factorId since it's passed in the path params */ + 'challengeId' | 'factorId' + > & { + challenge_id: string + } = { + challenge_id: params.challengeId, + ...('webauthn' in params + ? { + webauthn: { + ...params.webauthn, + credential_response: + params.webauthn.type === 'create' + ? serializeCredentialCreationResponse( + params.webauthn.credential_response as RegistrationCredential + ) + : serializeCredentialRequestResponse( + params.webauthn.credential_response as AuthenticationCredential + ), + }, + } + : { code: params.code }), + } + + const { data, error } = await _request( + this.fetch, + 'POST', + `${this.url}/factors/${params.factorId}/verify`, + { + body, + headers: this.headers, + jwt: sessionData?.session?.access_token, + } + ) + if (error) { + return this._returnResult({ data: null, error }) + } + + await this._saveSession({ + expires_at: Math.round(Date.now() / 1000) + data.expires_in, + ...data, + }) + await this._notifyAllSubscribers('MFA_CHALLENGE_VERIFIED', data) + + return this._returnResult({ data, error }) + }) + } catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: null, error }) + } + throw error + } + }) + } + + /** + * {@see GoTrueMFAApi#challenge} + */ + private async _challenge( + params: MFAChallengeTOTPParams + ): Promise> + private async _challenge( + params: MFAChallengePhoneParams + ): Promise> + private async _challenge( + params: MFAChallengeWebauthnParams + ): Promise> + private async _challenge(params: MFAChallengeParams): Promise { + return this._acquireLock(-1, async () => { + try { + return await this._useSession(async (result) => { + const { data: sessionData, error: sessionError } = result + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }) + } + + const response = (await _request( + this.fetch, + 'POST', + `${this.url}/factors/${params.factorId}/challenge`, + { + body: params, + headers: this.headers, + jwt: sessionData?.session?.access_token, + } + )) as + | Exclude + /** The server will send `serialized` data, so we assert the serialized response */ + | AuthMFAChallengeWebauthnServerResponse + + if (response.error) { + return response + } + + const { data } = response + + if (data.type !== 'webauthn') { + return { data, error: null } + } + + switch (data.webauthn.type) { + case 'create': + return { + data: { + ...data, + webauthn: { + ...data.webauthn, + credential_options: { + ...data.webauthn.credential_options, + publicKey: deserializeCredentialCreationOptions( + data.webauthn.credential_options.publicKey + ), + }, + }, + }, + error: null, + } + case 'request': + return { + data: { + ...data, + webauthn: { + ...data.webauthn, + credential_options: { + ...data.webauthn.credential_options, + publicKey: deserializeCredentialRequestOptions( + data.webauthn.credential_options.publicKey + ), + }, + }, + }, + error: null, + } + } + }) + } catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: null, error }) + } + throw error + } + }) + } + + /** + * {@see GoTrueMFAApi#challengeAndVerify} + */ + private async _challengeAndVerify( + params: MFAChallengeAndVerifyParams + ): Promise { + // both _challenge and _verify independently acquire the lock, so no need + // to acquire it here + + const { data: challengeData, error: challengeError } = await this._challenge({ + factorId: params.factorId, + }) + if (challengeError) { + return this._returnResult({ data: null, error: challengeError }) + } + + return await this._verify({ + factorId: params.factorId, + challengeId: challengeData.id, + code: params.code, + }) + } + + /** + * {@see GoTrueMFAApi#listFactors} + */ + private async _listFactors(): Promise { + // use #getUser instead of #_getUser as the former acquires a lock + const { + data: { user }, + error: userError, + } = await this.getUser() + if (userError) { + return { data: null, error: userError } + } + + const data: AuthMFAListFactorsResponse['data'] = { + all: [], + phone: [], + totp: [], + webauthn: [], + } + + // loop over the factors ONCE + for (const factor of user?.factors ?? []) { + data.all.push(factor) + if (factor.status === 'verified') { + ;(data[factor.factor_type] as (typeof factor)[]).push(factor) + } + } + + return { + data, + error: null, + } + } + + /** + * {@see GoTrueMFAApi#getAuthenticatorAssuranceLevel} + */ + private async _getAuthenticatorAssuranceLevel(): Promise { + const { + data: { session }, + error: sessionError, + } = await this.getSession() + + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }) + } + if (!session) { + return { + data: { currentLevel: null, nextLevel: null, currentAuthenticationMethods: [] }, + error: null, + } + } + + const { payload } = decodeJWT(session.access_token) + + let currentLevel: AuthenticatorAssuranceLevels | null = null + + if (payload.aal) { + currentLevel = payload.aal + } + + let nextLevel: AuthenticatorAssuranceLevels | null = currentLevel + + const verifiedFactors = + session.user.factors?.filter((factor: Factor) => factor.status === 'verified') ?? [] + + if (verifiedFactors.length > 0) { + nextLevel = 'aal2' + } + + const currentAuthenticationMethods = payload.amr || [] + + return { data: { currentLevel, nextLevel, currentAuthenticationMethods }, error: null } + } + + /** + * Retrieves details about an OAuth authorization request. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * Returns authorization details including client info, scopes, and user information. + * If the API returns a redirect_uri, it means consent was already given - the caller + * should handle the redirect manually if needed. + */ + private async _getAuthorizationDetails( + authorizationId: string + ): Promise { + try { + return await this._useSession(async (result) => { + const { + data: { session }, + error: sessionError, + } = result + + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }) + } + + if (!session) { + return this._returnResult({ data: null, error: new AuthSessionMissingError() }) + } + + return await _request( + this.fetch, + 'GET', + `${this.url}/oauth/authorizations/${authorizationId}`, + { + headers: this.headers, + jwt: session.access_token, + xform: (data: any) => ({ data, error: null }), + } + ) + }) + } catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: null, error }) + } + + throw error + } + } + + /** + * Approves an OAuth authorization request. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ + private async _approveAuthorization( + authorizationId: string, + options?: { skipBrowserRedirect?: boolean } + ): Promise { + try { + return await this._useSession(async (result) => { + const { + data: { session }, + error: sessionError, + } = result + + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }) + } + + if (!session) { + return this._returnResult({ data: null, error: new AuthSessionMissingError() }) + } + + const response = await _request( + this.fetch, + 'POST', + `${this.url}/oauth/authorizations/${authorizationId}/consent`, + { + headers: this.headers, + jwt: session.access_token, + body: { action: 'approve' }, + xform: (data: any) => ({ data, error: null }), + } + ) + + if (response.data && response.data.redirect_url) { + // Automatically redirect in browser unless skipBrowserRedirect is true + if (isBrowser() && !options?.skipBrowserRedirect) { + window.location.assign(response.data.redirect_url) + } + } + + return response + }) + } catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: null, error }) + } + + throw error + } + } + + /** + * Denies an OAuth authorization request. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ + private async _denyAuthorization( + authorizationId: string, + options?: { skipBrowserRedirect?: boolean } + ): Promise { + try { + return await this._useSession(async (result) => { + const { + data: { session }, + error: sessionError, + } = result + + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }) + } + + if (!session) { + return this._returnResult({ data: null, error: new AuthSessionMissingError() }) + } + + const response = await _request( + this.fetch, + 'POST', + `${this.url}/oauth/authorizations/${authorizationId}/consent`, + { + headers: this.headers, + jwt: session.access_token, + body: { action: 'deny' }, + xform: (data: any) => ({ data, error: null }), + } + ) + + if (response.data && response.data.redirect_url) { + // Automatically redirect in browser unless skipBrowserRedirect is true + if (isBrowser() && !options?.skipBrowserRedirect) { + window.location.assign(response.data.redirect_url) + } + } + + return response + }) + } catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: null, error }) + } + + throw error + } + } + + /** + * Lists all OAuth grants that the authenticated user has authorized. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ + private async _listOAuthGrants(): Promise { + try { + return await this._useSession(async (result) => { + const { + data: { session }, + error: sessionError, + } = result + + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }) + } + + if (!session) { + return this._returnResult({ data: null, error: new AuthSessionMissingError() }) + } + + return await _request(this.fetch, 'GET', `${this.url}/user/oauth/grants`, { + headers: this.headers, + jwt: session.access_token, + xform: (data: any) => ({ data, error: null }), + }) + }) + } catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: null, error }) + } + + throw error + } + } + + /** + * Revokes a user's OAuth grant for a specific client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ + private async _revokeOAuthGrant(options: { + clientId: string + }): Promise { + try { + return await this._useSession(async (result) => { + const { + data: { session }, + error: sessionError, + } = result + + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }) + } + + if (!session) { + return this._returnResult({ data: null, error: new AuthSessionMissingError() }) + } + + await _request(this.fetch, 'DELETE', `${this.url}/user/oauth/grants`, { + headers: this.headers, + jwt: session.access_token, + query: { client_id: options.clientId }, + noResolveJson: true, + }) + return { data: {}, error: null } + }) + } catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: null, error }) + } + + throw error + } + } + + private async fetchJwk(kid: string, jwks: { keys: JWK[] } = { keys: [] }): Promise { + // try fetching from the supplied jwks + let jwk = jwks.keys.find((key) => key.kid === kid) + if (jwk) { + return jwk + } + + const now = Date.now() + + // try fetching from cache + jwk = this.jwks.keys.find((key) => key.kid === kid) + + // jwk exists and jwks isn't stale + if (jwk && this.jwks_cached_at + JWKS_TTL > now) { + return jwk + } + // jwk isn't cached in memory so we need to fetch it from the well-known endpoint + const { data, error } = await _request(this.fetch, 'GET', `${this.url}/.well-known/jwks.json`, { + headers: this.headers, + }) + if (error) { + throw error + } + if (!data.keys || data.keys.length === 0) { + return null + } + + this.jwks = data + this.jwks_cached_at = now + + // Find the signing key + jwk = data.keys.find((key: any) => key.kid === kid) + if (!jwk) { + return null + } + return jwk + } + + /** + * Extracts the JWT claims present in the access token by first verifying the + * JWT against the server's JSON Web Key Set endpoint + * `/.well-known/jwks.json` which is often cached, resulting in significantly + * faster responses. Prefer this method over {@link #getUser} which always + * sends a request to the Auth server for each JWT. + * + * If the project is not using an asymmetric JWT signing key (like ECC or + * RSA) it always sends a request to the Auth server (similar to {@link + * #getUser}) to verify the JWT. + * + * @param jwt An optional specific JWT you wish to verify, not the one you + * can obtain from {@link #getSession}. + * @param options Various additional options that allow you to customize the + * behavior of this method. + */ + async getClaims( + jwt?: string, + options: { + /** + * @deprecated Please use options.jwks instead. + */ + keys?: JWK[] + + /** If set to `true` the `exp` claim will not be validated against the current time. */ + allowExpired?: boolean + + /** If set, this JSON Web Key Set is going to have precedence over the cached value available on the server. */ + jwks?: { keys: JWK[] } + } = {} + ): Promise< + | { + data: { claims: JwtPayload; header: JwtHeader; signature: Uint8Array } + error: null + } + | { data: null; error: AuthError } + | { data: null; error: null } + > { + try { + let token = jwt + if (!token) { + const { data, error } = await this.getSession() + if (error || !data.session) { + return this._returnResult({ data: null, error }) + } + token = data.session.access_token + } + + const { + header, + payload, + signature, + raw: { header: rawHeader, payload: rawPayload }, + } = decodeJWT(token) + + if (!options?.allowExpired) { + // Reject expired JWTs should only happen if jwt argument was passed + validateExp(payload.exp) + } + + const signingKey = + !header.alg || + header.alg.startsWith('HS') || + !header.kid || + !('crypto' in globalThis && 'subtle' in globalThis.crypto) + ? null + : await this.fetchJwk(header.kid, options?.keys ? { keys: options.keys } : options?.jwks) + + // If symmetric algorithm or WebCrypto API is unavailable, fallback to getUser() + if (!signingKey) { + const { error } = await this.getUser(token) + if (error) { + throw error + } + // getUser succeeds so the claims in the JWT can be trusted + return { + data: { + claims: payload, + header, + signature, + }, + error: null, + } + } + + const algorithm = getAlgorithm(header.alg) + + // Convert JWK to CryptoKey + const publicKey = await crypto.subtle.importKey('jwk', signingKey, algorithm, true, [ + 'verify', + ]) + + // Verify the signature + const isValid = await crypto.subtle.verify( + algorithm, + publicKey, + signature, + stringToUint8Array(`${rawHeader}.${rawPayload}`) + ) + + if (!isValid) { + throw new AuthInvalidJwtError('Invalid JWT signature') + } + + // If verification succeeds, decode and return claims + return { + data: { + claims: payload, + header, + signature, + }, + error: null, + } + } catch (error) { + if (isAuthError(error)) { + return this._returnResult({ data: null, error }) + } + throw error + } + } +} diff --git a/backend/node_modules/@supabase/auth-js/src/index.ts b/backend/node_modules/@supabase/auth-js/src/index.ts new file mode 100644 index 0000000..5426dcb --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/src/index.ts @@ -0,0 +1,13 @@ +import GoTrueAdminApi from './GoTrueAdminApi' +import GoTrueClient from './GoTrueClient' +import AuthAdminApi from './AuthAdminApi' +import AuthClient from './AuthClient' +export { GoTrueAdminApi, GoTrueClient, AuthAdminApi, AuthClient } +export * from './lib/types' +export * from './lib/errors' +export { + navigatorLock, + NavigatorLockAcquireTimeoutError, + internals as lockInternals, + processLock, +} from './lib/locks' diff --git a/backend/node_modules/@supabase/auth-js/src/lib/base64url.ts b/backend/node_modules/@supabase/auth-js/src/lib/base64url.ts new file mode 100644 index 0000000..1ec32e3 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/src/lib/base64url.ts @@ -0,0 +1,308 @@ +/** + * Avoid modifying this file. It's part of + * https://github.com/supabase-community/base64url-js. Submit all fixes on + * that repo! + */ + +import { Uint8Array_ } from './webauthn.dom' + +/** + * An array of characters that encode 6 bits into a Base64-URL alphabet + * character. + */ +const TO_BASE64URL = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'.split('') + +/** + * An array of characters that can appear in a Base64-URL encoded string but + * should be ignored. + */ +const IGNORE_BASE64URL = ' \t\n\r='.split('') + +/** + * An array of 128 numbers that map a Base64-URL character to 6 bits, or if -2 + * used to skip the character, or if -1 used to error out. + */ +const FROM_BASE64URL = (() => { + const charMap: number[] = new Array(128) + + for (let i = 0; i < charMap.length; i += 1) { + charMap[i] = -1 + } + + for (let i = 0; i < IGNORE_BASE64URL.length; i += 1) { + charMap[IGNORE_BASE64URL[i].charCodeAt(0)] = -2 + } + + for (let i = 0; i < TO_BASE64URL.length; i += 1) { + charMap[TO_BASE64URL[i].charCodeAt(0)] = i + } + + return charMap +})() + +/** + * Converts a byte to a Base64-URL string. + * + * @param byte The byte to convert, or null to flush at the end of the byte sequence. + * @param state The Base64 conversion state. Pass an initial value of `{ queue: 0, queuedBits: 0 }`. + * @param emit A function called with the next Base64 character when ready. + */ +export function byteToBase64URL( + byte: number | null, + state: { queue: number; queuedBits: number }, + emit: (char: string) => void +) { + if (byte !== null) { + state.queue = (state.queue << 8) | byte + state.queuedBits += 8 + + while (state.queuedBits >= 6) { + const pos = (state.queue >> (state.queuedBits - 6)) & 63 + emit(TO_BASE64URL[pos]) + state.queuedBits -= 6 + } + } else if (state.queuedBits > 0) { + state.queue = state.queue << (6 - state.queuedBits) + state.queuedBits = 6 + + while (state.queuedBits >= 6) { + const pos = (state.queue >> (state.queuedBits - 6)) & 63 + emit(TO_BASE64URL[pos]) + state.queuedBits -= 6 + } + } +} + +/** + * Converts a String char code (extracted using `string.charCodeAt(position)`) to a sequence of Base64-URL characters. + * + * @param charCode The char code of the JavaScript string. + * @param state The Base64 state. Pass an initial value of `{ queue: 0, queuedBits: 0 }`. + * @param emit A function called with the next byte. + */ +export function byteFromBase64URL( + charCode: number, + state: { queue: number; queuedBits: number }, + emit: (byte: number) => void +) { + const bits = FROM_BASE64URL[charCode] + + if (bits > -1) { + // valid Base64-URL character + state.queue = (state.queue << 6) | bits + state.queuedBits += 6 + + while (state.queuedBits >= 8) { + emit((state.queue >> (state.queuedBits - 8)) & 0xff) + state.queuedBits -= 8 + } + } else if (bits === -2) { + // ignore spaces, tabs, newlines, = + return + } else { + throw new Error(`Invalid Base64-URL character "${String.fromCharCode(charCode)}"`) + } +} + +/** + * Converts a JavaScript string (which may include any valid character) into a + * Base64-URL encoded string. The string is first encoded in UTF-8 which is + * then encoded as Base64-URL. + * + * @param str The string to convert. + */ +export function stringToBase64URL(str: string) { + const base64: string[] = [] + + const emitter = (char: string) => { + base64.push(char) + } + + const state = { queue: 0, queuedBits: 0 } + + stringToUTF8(str, (byte: number) => { + byteToBase64URL(byte, state, emitter) + }) + + byteToBase64URL(null, state, emitter) + + return base64.join('') +} + +/** + * Converts a Base64-URL encoded string into a JavaScript string. It is assumed + * that the underlying string has been encoded as UTF-8. + * + * @param str The Base64-URL encoded string. + */ +export function stringFromBase64URL(str: string) { + const conv: string[] = [] + + const utf8Emit = (codepoint: number) => { + conv.push(String.fromCodePoint(codepoint)) + } + + const utf8State = { + utf8seq: 0, + codepoint: 0, + } + + const b64State = { queue: 0, queuedBits: 0 } + + const byteEmit = (byte: number) => { + stringFromUTF8(byte, utf8State, utf8Emit) + } + + for (let i = 0; i < str.length; i += 1) { + byteFromBase64URL(str.charCodeAt(i), b64State, byteEmit) + } + + return conv.join('') +} + +/** + * Converts a Unicode codepoint to a multi-byte UTF-8 sequence. + * + * @param codepoint The Unicode codepoint. + * @param emit Function which will be called for each UTF-8 byte that represents the codepoint. + */ +export function codepointToUTF8(codepoint: number, emit: (byte: number) => void) { + if (codepoint <= 0x7f) { + emit(codepoint) + return + } else if (codepoint <= 0x7ff) { + emit(0xc0 | (codepoint >> 6)) + emit(0x80 | (codepoint & 0x3f)) + return + } else if (codepoint <= 0xffff) { + emit(0xe0 | (codepoint >> 12)) + emit(0x80 | ((codepoint >> 6) & 0x3f)) + emit(0x80 | (codepoint & 0x3f)) + return + } else if (codepoint <= 0x10ffff) { + emit(0xf0 | (codepoint >> 18)) + emit(0x80 | ((codepoint >> 12) & 0x3f)) + emit(0x80 | ((codepoint >> 6) & 0x3f)) + emit(0x80 | (codepoint & 0x3f)) + return + } + + throw new Error(`Unrecognized Unicode codepoint: ${codepoint.toString(16)}`) +} + +/** + * Converts a JavaScript string to a sequence of UTF-8 bytes. + * + * @param str The string to convert to UTF-8. + * @param emit Function which will be called for each UTF-8 byte of the string. + */ +export function stringToUTF8(str: string, emit: (byte: number) => void) { + for (let i = 0; i < str.length; i += 1) { + let codepoint = str.charCodeAt(i) + + if (codepoint > 0xd7ff && codepoint <= 0xdbff) { + // most UTF-16 codepoints are Unicode codepoints, except values in this + // range where the next UTF-16 codepoint needs to be combined with the + // current one to get the Unicode codepoint + const highSurrogate = ((codepoint - 0xd800) * 0x400) & 0xffff + const lowSurrogate = (str.charCodeAt(i + 1) - 0xdc00) & 0xffff + codepoint = (lowSurrogate | highSurrogate) + 0x10000 + i += 1 + } + + codepointToUTF8(codepoint, emit) + } +} + +/** + * Converts a UTF-8 byte to a Unicode codepoint. + * + * @param byte The UTF-8 byte next in the sequence. + * @param state The shared state between consecutive UTF-8 bytes in the + * sequence, an object with the shape `{ utf8seq: 0, codepoint: 0 }`. + * @param emit Function which will be called for each codepoint. + */ +export function stringFromUTF8( + byte: number, + state: { utf8seq: number; codepoint: number }, + emit: (codepoint: number) => void +) { + if (state.utf8seq === 0) { + if (byte <= 0x7f) { + emit(byte) + return + } + + // count the number of 1 leading bits until you reach 0 + for (let leadingBit = 1; leadingBit < 6; leadingBit += 1) { + if (((byte >> (7 - leadingBit)) & 1) === 0) { + state.utf8seq = leadingBit + break + } + } + + if (state.utf8seq === 2) { + state.codepoint = byte & 31 + } else if (state.utf8seq === 3) { + state.codepoint = byte & 15 + } else if (state.utf8seq === 4) { + state.codepoint = byte & 7 + } else { + throw new Error('Invalid UTF-8 sequence') + } + + state.utf8seq -= 1 + } else if (state.utf8seq > 0) { + if (byte <= 0x7f) { + throw new Error('Invalid UTF-8 sequence') + } + + state.codepoint = (state.codepoint << 6) | (byte & 63) + state.utf8seq -= 1 + + if (state.utf8seq === 0) { + emit(state.codepoint) + } + } +} + +/** + * Helper functions to convert different types of strings to Uint8Array + */ + +export function base64UrlToUint8Array(str: string): Uint8Array_ { + const result: number[] = [] + const state = { queue: 0, queuedBits: 0 } + + const onByte = (byte: number) => { + result.push(byte) + } + + for (let i = 0; i < str.length; i += 1) { + byteFromBase64URL(str.charCodeAt(i), state, onByte) + } + + return new Uint8Array(result) +} + +export function stringToUint8Array(str: string): Uint8Array_ { + const result: number[] = [] + stringToUTF8(str, (byte: number) => result.push(byte)) + return new Uint8Array(result) +} + +export function bytesToBase64URL(bytes: Uint8Array) { + const result: string[] = [] + const state = { queue: 0, queuedBits: 0 } + + const onChar = (char: string) => { + result.push(char) + } + + bytes.forEach((byte) => byteToBase64URL(byte, state, onChar)) + + // always call with `null` after processing all bytes + byteToBase64URL(null, state, onChar) + + return result.join('') +} diff --git a/backend/node_modules/@supabase/auth-js/src/lib/constants.ts b/backend/node_modules/@supabase/auth-js/src/lib/constants.ts new file mode 100644 index 0000000..edb77ef --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/src/lib/constants.ts @@ -0,0 +1,34 @@ +import { version } from './version' + +/** Current session will be checked for refresh at this interval. */ +export const AUTO_REFRESH_TICK_DURATION_MS = 30 * 1000 + +/** + * A token refresh will be attempted this many ticks before the current session expires. */ +export const AUTO_REFRESH_TICK_THRESHOLD = 3 + +/* + * Earliest time before an access token expires that the session should be refreshed. + */ +export const EXPIRY_MARGIN_MS = AUTO_REFRESH_TICK_THRESHOLD * AUTO_REFRESH_TICK_DURATION_MS + +export const GOTRUE_URL = 'http://localhost:9999' +export const STORAGE_KEY = 'supabase.auth.token' +export const AUDIENCE = '' +export const DEFAULT_HEADERS = { 'X-Client-Info': `gotrue-js/${version}` } +export const NETWORK_FAILURE = { + MAX_RETRIES: 10, + RETRY_INTERVAL: 2, // in deciseconds +} + +export const API_VERSION_HEADER_NAME = 'X-Supabase-Api-Version' +export const API_VERSIONS = { + '2024-01-01': { + timestamp: Date.parse('2024-01-01T00:00:00.0Z'), + name: '2024-01-01', + }, +} + +export const BASE64URL_REGEX = /^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i + +export const JWKS_TTL = 10 * 60 * 1000 // 10 minutes diff --git a/backend/node_modules/@supabase/auth-js/src/lib/error-codes.ts b/backend/node_modules/@supabase/auth-js/src/lib/error-codes.ts new file mode 100644 index 0000000..6c3d339 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/src/lib/error-codes.ts @@ -0,0 +1,90 @@ +/** + * Known error codes. Note that the server may also return other error codes + * not included in this list (if the SDK is older than the version + * on the server). + */ +export type ErrorCode = + | 'unexpected_failure' + | 'validation_failed' + | 'bad_json' + | 'email_exists' + | 'phone_exists' + | 'bad_jwt' + | 'not_admin' + | 'no_authorization' + | 'user_not_found' + | 'session_not_found' + | 'session_expired' + | 'refresh_token_not_found' + | 'refresh_token_already_used' + | 'flow_state_not_found' + | 'flow_state_expired' + | 'signup_disabled' + | 'user_banned' + | 'provider_email_needs_verification' + | 'invite_not_found' + | 'bad_oauth_state' + | 'bad_oauth_callback' + | 'oauth_provider_not_supported' + | 'unexpected_audience' + | 'single_identity_not_deletable' + | 'email_conflict_identity_not_deletable' + | 'identity_already_exists' + | 'email_provider_disabled' + | 'phone_provider_disabled' + | 'too_many_enrolled_mfa_factors' + | 'mfa_factor_name_conflict' + | 'mfa_factor_not_found' + | 'mfa_ip_address_mismatch' + | 'mfa_challenge_expired' + | 'mfa_verification_failed' + | 'mfa_verification_rejected' + | 'insufficient_aal' + | 'captcha_failed' + | 'saml_provider_disabled' + | 'manual_linking_disabled' + | 'sms_send_failed' + | 'email_not_confirmed' + | 'phone_not_confirmed' + | 'reauth_nonce_missing' + | 'saml_relay_state_not_found' + | 'saml_relay_state_expired' + | 'saml_idp_not_found' + | 'saml_assertion_no_user_id' + | 'saml_assertion_no_email' + | 'user_already_exists' + | 'sso_provider_not_found' + | 'saml_metadata_fetch_failed' + | 'saml_idp_already_exists' + | 'sso_domain_already_exists' + | 'saml_entity_id_mismatch' + | 'conflict' + | 'provider_disabled' + | 'user_sso_managed' + | 'reauthentication_needed' + | 'same_password' + | 'reauthentication_not_valid' + | 'otp_expired' + | 'otp_disabled' + | 'identity_not_found' + | 'weak_password' + | 'over_request_rate_limit' + | 'over_email_send_rate_limit' + | 'over_sms_send_rate_limit' + | 'bad_code_verifier' + | 'anonymous_provider_disabled' + | 'hook_timeout' + | 'hook_timeout_after_retry' + | 'hook_payload_over_size_limit' + | 'hook_payload_invalid_content_type' + | 'request_timeout' + | 'mfa_phone_enroll_not_enabled' + | 'mfa_phone_verify_not_enabled' + | 'mfa_totp_enroll_not_enabled' + | 'mfa_totp_verify_not_enabled' + | 'mfa_webauthn_enroll_not_enabled' + | 'mfa_webauthn_verify_not_enabled' + | 'mfa_verified_factor_exists' + | 'invalid_credentials' + | 'email_address_not_authorized' + | 'email_address_invalid' diff --git a/backend/node_modules/@supabase/auth-js/src/lib/errors.ts b/backend/node_modules/@supabase/auth-js/src/lib/errors.ts new file mode 100644 index 0000000..28270e0 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/src/lib/errors.ts @@ -0,0 +1,292 @@ +import { WeakPasswordReasons } from './types' +import { ErrorCode } from './error-codes' + +/** + * Base error thrown by Supabase Auth helpers. + * + * @example + * ```ts + * import { AuthError } from '@supabase/auth-js' + * + * throw new AuthError('Unexpected auth error', 500, 'unexpected') + * ``` + */ +export class AuthError extends Error { + /** + * Error code associated with the error. Most errors coming from + * HTTP responses will have a code, though some errors that occur + * before a response is received will not have one present. In that + * case {@link #status} will also be undefined. + */ + code: ErrorCode | (string & {}) | undefined + + /** HTTP status code that caused the error. */ + status: number | undefined + + protected __isAuthError = true + + constructor(message: string, status?: number, code?: string) { + super(message) + this.name = 'AuthError' + this.status = status + this.code = code + } +} + +export function isAuthError(error: unknown): error is AuthError { + return typeof error === 'object' && error !== null && '__isAuthError' in error +} + +/** + * Error returned directly from the GoTrue REST API. + * + * @example + * ```ts + * import { AuthApiError } from '@supabase/auth-js' + * + * throw new AuthApiError('Invalid credentials', 400, 'invalid_credentials') + * ``` + */ +export class AuthApiError extends AuthError { + status: number + + constructor(message: string, status: number, code: string | undefined) { + super(message, status, code) + this.name = 'AuthApiError' + this.status = status + this.code = code + } +} + +export function isAuthApiError(error: unknown): error is AuthApiError { + return isAuthError(error) && error.name === 'AuthApiError' +} + +/** + * Wraps non-standard errors so callers can inspect the root cause. + * + * @example + * ```ts + * import { AuthUnknownError } from '@supabase/auth-js' + * + * try { + * await someAuthCall() + * } catch (err) { + * throw new AuthUnknownError('Auth failed', err) + * } + * ``` + */ +export class AuthUnknownError extends AuthError { + originalError: unknown + + constructor(message: string, originalError: unknown) { + super(message) + this.name = 'AuthUnknownError' + this.originalError = originalError + } +} + +/** + * Flexible error class used to create named auth errors at runtime. + * + * @example + * ```ts + * import { CustomAuthError } from '@supabase/auth-js' + * + * throw new CustomAuthError('My custom auth error', 'MyAuthError', 400, 'custom_code') + * ``` + */ +export class CustomAuthError extends AuthError { + name: string + status: number + + constructor(message: string, name: string, status: number, code: string | undefined) { + super(message, status, code) + this.name = name + this.status = status + } +} + +/** + * Error thrown when an operation requires a session but none is present. + * + * @example + * ```ts + * import { AuthSessionMissingError } from '@supabase/auth-js' + * + * throw new AuthSessionMissingError() + * ``` + */ +export class AuthSessionMissingError extends CustomAuthError { + constructor() { + super('Auth session missing!', 'AuthSessionMissingError', 400, undefined) + } +} + +export function isAuthSessionMissingError(error: any): error is AuthSessionMissingError { + return isAuthError(error) && error.name === 'AuthSessionMissingError' +} + +/** + * Error thrown when the token response is malformed. + * + * @example + * ```ts + * import { AuthInvalidTokenResponseError } from '@supabase/auth-js' + * + * throw new AuthInvalidTokenResponseError() + * ``` + */ +export class AuthInvalidTokenResponseError extends CustomAuthError { + constructor() { + super('Auth session or user missing', 'AuthInvalidTokenResponseError', 500, undefined) + } +} + +/** + * Error thrown when email/password credentials are invalid. + * + * @example + * ```ts + * import { AuthInvalidCredentialsError } from '@supabase/auth-js' + * + * throw new AuthInvalidCredentialsError('Email or password is incorrect') + * ``` + */ +export class AuthInvalidCredentialsError extends CustomAuthError { + constructor(message: string) { + super(message, 'AuthInvalidCredentialsError', 400, undefined) + } +} + +/** + * Error thrown when implicit grant redirects contain an error. + * + * @example + * ```ts + * import { AuthImplicitGrantRedirectError } from '@supabase/auth-js' + * + * throw new AuthImplicitGrantRedirectError('OAuth redirect failed', { + * error: 'access_denied', + * code: 'oauth_error', + * }) + * ``` + */ +export class AuthImplicitGrantRedirectError extends CustomAuthError { + details: { error: string; code: string } | null = null + constructor(message: string, details: { error: string; code: string } | null = null) { + super(message, 'AuthImplicitGrantRedirectError', 500, undefined) + this.details = details + } + + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + details: this.details, + } + } +} + +export function isAuthImplicitGrantRedirectError( + error: any +): error is AuthImplicitGrantRedirectError { + return isAuthError(error) && error.name === 'AuthImplicitGrantRedirectError' +} + +/** + * Error thrown during PKCE code exchanges. + * + * @example + * ```ts + * import { AuthPKCEGrantCodeExchangeError } from '@supabase/auth-js' + * + * throw new AuthPKCEGrantCodeExchangeError('PKCE exchange failed') + * ``` + */ +export class AuthPKCEGrantCodeExchangeError extends CustomAuthError { + details: { error: string; code: string } | null = null + + constructor(message: string, details: { error: string; code: string } | null = null) { + super(message, 'AuthPKCEGrantCodeExchangeError', 500, undefined) + this.details = details + } + + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + details: this.details, + } + } +} + +/** + * Error thrown when a transient fetch issue occurs. + * + * @example + * ```ts + * import { AuthRetryableFetchError } from '@supabase/auth-js' + * + * throw new AuthRetryableFetchError('Service temporarily unavailable', 503) + * ``` + */ +export class AuthRetryableFetchError extends CustomAuthError { + constructor(message: string, status: number) { + super(message, 'AuthRetryableFetchError', status, undefined) + } +} + +export function isAuthRetryableFetchError(error: unknown): error is AuthRetryableFetchError { + return isAuthError(error) && error.name === 'AuthRetryableFetchError' +} + +/** + * This error is thrown on certain methods when the password used is deemed + * weak. Inspect the reasons to identify what password strength rules are + * inadequate. + */ +/** + * Error thrown when a supplied password is considered weak. + * + * @example + * ```ts + * import { AuthWeakPasswordError } from '@supabase/auth-js' + * + * throw new AuthWeakPasswordError('Password too short', 400, ['min_length']) + * ``` + */ +export class AuthWeakPasswordError extends CustomAuthError { + /** + * Reasons why the password is deemed weak. + */ + reasons: WeakPasswordReasons[] + + constructor(message: string, status: number, reasons: WeakPasswordReasons[]) { + super(message, 'AuthWeakPasswordError', status, 'weak_password') + + this.reasons = reasons + } +} + +export function isAuthWeakPasswordError(error: unknown): error is AuthWeakPasswordError { + return isAuthError(error) && error.name === 'AuthWeakPasswordError' +} + +/** + * Error thrown when a JWT cannot be verified or parsed. + * + * @example + * ```ts + * import { AuthInvalidJwtError } from '@supabase/auth-js' + * + * throw new AuthInvalidJwtError('Token signature is invalid') + * ``` + */ +export class AuthInvalidJwtError extends CustomAuthError { + constructor(message: string) { + super(message, 'AuthInvalidJwtError', 400, 'invalid_jwt') + } +} diff --git a/backend/node_modules/@supabase/auth-js/src/lib/fetch.ts b/backend/node_modules/@supabase/auth-js/src/lib/fetch.ts new file mode 100644 index 0000000..014e9b2 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/src/lib/fetch.ts @@ -0,0 +1,283 @@ +import { API_VERSIONS, API_VERSION_HEADER_NAME } from './constants' +import { expiresAt, looksLikeFetchResponse, parseResponseAPIVersion } from './helpers' +import { + AuthResponse, + AuthResponsePassword, + SSOResponse, + GenerateLinkProperties, + GenerateLinkResponse, + User, + UserResponse, +} from './types' +import { + AuthApiError, + AuthRetryableFetchError, + AuthWeakPasswordError, + AuthUnknownError, + AuthSessionMissingError, +} from './errors' + +export type Fetch = typeof fetch + +export interface FetchOptions { + headers?: { + [key: string]: string + } + noResolveJson?: boolean +} + +export interface FetchParameters { + signal?: AbortSignal +} + +export type RequestMethodType = 'GET' | 'POST' | 'PUT' | 'DELETE' + +const _getErrorMessage = (err: any): string => + err.msg || err.message || err.error_description || err.error || JSON.stringify(err) + +const NETWORK_ERROR_CODES = [502, 503, 504] + +export async function handleError(error: unknown) { + if (!looksLikeFetchResponse(error)) { + throw new AuthRetryableFetchError(_getErrorMessage(error), 0) + } + + if (NETWORK_ERROR_CODES.includes(error.status)) { + // status in 500...599 range - server had an error, request might be retryed. + throw new AuthRetryableFetchError(_getErrorMessage(error), error.status) + } + + let data: any + try { + data = await error.json() + } catch (e: any) { + throw new AuthUnknownError(_getErrorMessage(e), e) + } + + let errorCode: string | undefined = undefined + + const responseAPIVersion = parseResponseAPIVersion(error) + if ( + responseAPIVersion && + responseAPIVersion.getTime() >= API_VERSIONS['2024-01-01'].timestamp && + typeof data === 'object' && + data && + typeof data.code === 'string' + ) { + errorCode = data.code + } else if (typeof data === 'object' && data && typeof data.error_code === 'string') { + errorCode = data.error_code + } + + if (!errorCode) { + // Legacy support for weak password errors, when there were no error codes + if ( + typeof data === 'object' && + data && + typeof data.weak_password === 'object' && + data.weak_password && + Array.isArray(data.weak_password.reasons) && + data.weak_password.reasons.length && + data.weak_password.reasons.reduce((a: boolean, i: any) => a && typeof i === 'string', true) + ) { + throw new AuthWeakPasswordError( + _getErrorMessage(data), + error.status, + data.weak_password.reasons + ) + } + } else if (errorCode === 'weak_password') { + throw new AuthWeakPasswordError( + _getErrorMessage(data), + error.status, + data.weak_password?.reasons || [] + ) + } else if (errorCode === 'session_not_found') { + // The `session_id` inside the JWT does not correspond to a row in the + // `sessions` table. This usually means the user has signed out, has been + // deleted, or their session has somehow been terminated. + throw new AuthSessionMissingError() + } + + throw new AuthApiError(_getErrorMessage(data), error.status || 500, errorCode) +} + +const _getRequestParams = ( + method: RequestMethodType, + options?: FetchOptions, + parameters?: FetchParameters, + body?: object +) => { + const params: { [k: string]: any } = { method, headers: options?.headers || {} } + + if (method === 'GET') { + return params + } + + params.headers = { 'Content-Type': 'application/json;charset=UTF-8', ...options?.headers } + params.body = JSON.stringify(body) + return { ...params, ...parameters } +} + +interface GotrueRequestOptions extends FetchOptions { + jwt?: string + redirectTo?: string + body?: object + query?: { [key: string]: string } + /** + * Function that transforms api response from gotrue into a desirable / standardised format + */ + xform?: (data: any) => any +} + +export async function _request( + fetcher: Fetch, + method: RequestMethodType, + url: string, + options?: GotrueRequestOptions +) { + const headers = { + ...options?.headers, + } + + if (!headers[API_VERSION_HEADER_NAME]) { + headers[API_VERSION_HEADER_NAME] = API_VERSIONS['2024-01-01'].name + } + + if (options?.jwt) { + headers['Authorization'] = `Bearer ${options.jwt}` + } + + const qs = options?.query ?? {} + if (options?.redirectTo) { + qs['redirect_to'] = options.redirectTo + } + + const queryString = Object.keys(qs).length ? '?' + new URLSearchParams(qs).toString() : '' + const data = await _handleRequest( + fetcher, + method, + url + queryString, + { + headers, + noResolveJson: options?.noResolveJson, + }, + {}, + options?.body + ) + return options?.xform ? options?.xform(data) : { data: { ...data }, error: null } +} + +async function _handleRequest( + fetcher: Fetch, + method: RequestMethodType, + url: string, + options?: FetchOptions, + parameters?: FetchParameters, + body?: object +): Promise { + const requestParams = _getRequestParams(method, options, parameters, body) + + let result: any + + try { + result = await fetcher(url, { + ...requestParams, + }) + } catch (e) { + console.error(e) + + // fetch failed, likely due to a network or CORS error + throw new AuthRetryableFetchError(_getErrorMessage(e), 0) + } + + if (!result.ok) { + await handleError(result) + } + + if (options?.noResolveJson) { + return result + } + + try { + return await result.json() + } catch (e: any) { + await handleError(e) + } +} + +export function _sessionResponse(data: any): AuthResponse { + let session = null + if (hasSession(data)) { + session = { ...data } + + if (!data.expires_at) { + session.expires_at = expiresAt(data.expires_in) + } + } + + const user: User = data.user ?? (data as User) + return { data: { session, user }, error: null } +} + +export function _sessionResponsePassword(data: any): AuthResponsePassword { + const response = _sessionResponse(data) as AuthResponsePassword + + if ( + !response.error && + data.weak_password && + typeof data.weak_password === 'object' && + Array.isArray(data.weak_password.reasons) && + data.weak_password.reasons.length && + data.weak_password.message && + typeof data.weak_password.message === 'string' && + data.weak_password.reasons.reduce((a: boolean, i: any) => a && typeof i === 'string', true) + ) { + response.data.weak_password = data.weak_password + } + + return response +} + +export function _userResponse(data: any): UserResponse { + const user: User = data.user ?? (data as User) + return { data: { user }, error: null } +} + +export function _ssoResponse(data: any): SSOResponse { + return { data, error: null } +} + +export function _generateLinkResponse(data: any): GenerateLinkResponse { + const { action_link, email_otp, hashed_token, redirect_to, verification_type, ...rest } = data + + const properties: GenerateLinkProperties = { + action_link, + email_otp, + hashed_token, + redirect_to, + verification_type, + } + + const user: User = { ...rest } + return { + data: { + properties, + user, + }, + error: null, + } +} + +export function _noResolveJsonResponse(data: any): Response { + return data +} + +/** + * hasSession checks if the response object contains a valid session + * @param data A response object + * @returns true if a session is in the response + */ +function hasSession(data: any): boolean { + return data.access_token && data.refresh_token && data.expires_in +} diff --git a/backend/node_modules/@supabase/auth-js/src/lib/helpers.ts b/backend/node_modules/@supabase/auth-js/src/lib/helpers.ts new file mode 100644 index 0000000..659e82d --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/src/lib/helpers.ts @@ -0,0 +1,463 @@ +import { API_VERSION_HEADER_NAME, BASE64URL_REGEX } from './constants' +import { AuthInvalidJwtError } from './errors' +import { base64UrlToUint8Array, stringFromBase64URL } from './base64url' +import { JwtHeader, JwtPayload, SupportedStorage, User } from './types' +import { Uint8Array_ } from './webauthn.dom' + +export function expiresAt(expiresIn: number) { + const timeNow = Math.round(Date.now() / 1000) + return timeNow + expiresIn +} + +/** + * Generates a unique identifier for internal callback subscriptions. + * + * This function uses JavaScript Symbols to create guaranteed-unique identifiers + * for auth state change callbacks. Symbols are ideal for this use case because: + * - They are guaranteed unique by the JavaScript runtime + * - They work in all environments (browser, SSR, Node.js) + * - They avoid issues with Next.js 16 deterministic rendering requirements + * - They are perfect for internal, non-serializable identifiers + * + * Note: This function is only used for internal subscription management, + * not for security-critical operations like session tokens. + */ +export function generateCallbackId(): symbol { + return Symbol('auth-callback') +} + +export const isBrowser = () => typeof window !== 'undefined' && typeof document !== 'undefined' + +const localStorageWriteTests = { + tested: false, + writable: false, +} + +/** + * Checks whether localStorage is supported on this browser. + */ +export const supportsLocalStorage = () => { + if (!isBrowser()) { + return false + } + + try { + if (typeof globalThis.localStorage !== 'object') { + return false + } + } catch (e) { + // DOM exception when accessing `localStorage` + return false + } + + if (localStorageWriteTests.tested) { + return localStorageWriteTests.writable + } + + const randomKey = `lswt-${Math.random()}${Math.random()}` + + try { + globalThis.localStorage.setItem(randomKey, randomKey) + globalThis.localStorage.removeItem(randomKey) + + localStorageWriteTests.tested = true + localStorageWriteTests.writable = true + } catch (e) { + // localStorage can't be written to + // https://www.chromium.org/for-testers/bug-reporting-guidelines/uncaught-securityerror-failed-to-read-the-localstorage-property-from-window-access-is-denied-for-this-document + + localStorageWriteTests.tested = true + localStorageWriteTests.writable = false + } + + return localStorageWriteTests.writable +} + +/** + * Extracts parameters encoded in the URL both in the query and fragment. + */ +export function parseParametersFromURL(href: string) { + const result: { [parameter: string]: string } = {} + + const url = new URL(href) + + if (url.hash && url.hash[0] === '#') { + try { + const hashSearchParams = new URLSearchParams(url.hash.substring(1)) + hashSearchParams.forEach((value, key) => { + result[key] = value + }) + } catch (e: any) { + // hash is not a query string + } + } + + // search parameters take precedence over hash parameters + url.searchParams.forEach((value, key) => { + result[key] = value + }) + + return result +} + +type Fetch = typeof fetch + +export const resolveFetch = (customFetch?: Fetch): Fetch => { + if (customFetch) { + return (...args) => customFetch(...args) + } + return (...args) => fetch(...args) +} + +export const looksLikeFetchResponse = (maybeResponse: unknown): maybeResponse is Response => { + return ( + typeof maybeResponse === 'object' && + maybeResponse !== null && + 'status' in maybeResponse && + 'ok' in maybeResponse && + 'json' in maybeResponse && + typeof (maybeResponse as any).json === 'function' + ) +} + +// Storage helpers +export const setItemAsync = async ( + storage: SupportedStorage, + key: string, + data: any +): Promise => { + await storage.setItem(key, JSON.stringify(data)) +} + +export const getItemAsync = async (storage: SupportedStorage, key: string): Promise => { + const value = await storage.getItem(key) + + if (!value) { + return null + } + + try { + return JSON.parse(value) + } catch { + return value + } +} + +export const removeItemAsync = async (storage: SupportedStorage, key: string): Promise => { + await storage.removeItem(key) +} + +/** + * A deferred represents some asynchronous work that is not yet finished, which + * may or may not culminate in a value. + * Taken from: https://github.com/mike-north/types/blob/master/src/async.ts + */ +export class Deferred { + public static promiseConstructor: PromiseConstructor = Promise + + public readonly promise!: PromiseLike + + public readonly resolve!: (value?: T | PromiseLike) => void + + public readonly reject!: (reason?: any) => any + + public constructor() { + // eslint-disable-next-line @typescript-eslint/no-extra-semi + ;(this as any).promise = new Deferred.promiseConstructor((res, rej) => { + // eslint-disable-next-line @typescript-eslint/no-extra-semi + ;(this as any).resolve = res + // eslint-disable-next-line @typescript-eslint/no-extra-semi + ;(this as any).reject = rej + }) + } +} + +export function decodeJWT(token: string): { + header: JwtHeader + payload: JwtPayload + signature: Uint8Array_ + raw: { + header: string + payload: string + } +} { + const parts = token.split('.') + + if (parts.length !== 3) { + throw new AuthInvalidJwtError('Invalid JWT structure') + } + + // Regex checks for base64url format + for (let i = 0; i < parts.length; i++) { + if (!BASE64URL_REGEX.test(parts[i] as string)) { + throw new AuthInvalidJwtError('JWT not in base64url format') + } + } + const data = { + // using base64url lib + header: JSON.parse(stringFromBase64URL(parts[0])), + payload: JSON.parse(stringFromBase64URL(parts[1])), + signature: base64UrlToUint8Array(parts[2]), + raw: { + header: parts[0], + payload: parts[1], + }, + } + return data +} + +/** + * Creates a promise that resolves to null after some time. + */ +export async function sleep(time: number): Promise { + return await new Promise((accept) => { + setTimeout(() => accept(null), time) + }) +} + +/** + * Converts the provided async function into a retryable function. Each result + * or thrown error is sent to the isRetryable function which should return true + * if the function should run again. + */ +export function retryable( + fn: (attempt: number) => Promise, + isRetryable: (attempt: number, error: any | null, result?: T) => boolean +): Promise { + const promise = new Promise((accept, reject) => { + // eslint-disable-next-line @typescript-eslint/no-extra-semi + ;(async () => { + for (let attempt = 0; attempt < Infinity; attempt++) { + try { + const result = await fn(attempt) + + if (!isRetryable(attempt, null, result)) { + accept(result) + return + } + } catch (e: any) { + if (!isRetryable(attempt, e)) { + reject(e) + return + } + } + } + })() + }) + + return promise +} + +function dec2hex(dec: number) { + return ('0' + dec.toString(16)).substr(-2) +} + +// Functions below taken from: https://stackoverflow.com/questions/63309409/creating-a-code-verifier-and-challenge-for-pkce-auth-on-spotify-api-in-reactjs +export function generatePKCEVerifier() { + const verifierLength = 56 + const array = new Uint32Array(verifierLength) + if (typeof crypto === 'undefined') { + const charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~' + const charSetLen = charSet.length + let verifier = '' + for (let i = 0; i < verifierLength; i++) { + verifier += charSet.charAt(Math.floor(Math.random() * charSetLen)) + } + return verifier + } + crypto.getRandomValues(array) + return Array.from(array, dec2hex).join('') +} + +async function sha256(randomString: string) { + const encoder = new TextEncoder() + const encodedData = encoder.encode(randomString) + const hash = await crypto.subtle.digest('SHA-256', encodedData) + const bytes = new Uint8Array(hash) + + return Array.from(bytes) + .map((c) => String.fromCharCode(c)) + .join('') +} + +export async function generatePKCEChallenge(verifier: string) { + const hasCryptoSupport = + typeof crypto !== 'undefined' && + typeof crypto.subtle !== 'undefined' && + typeof TextEncoder !== 'undefined' + + if (!hasCryptoSupport) { + console.warn( + 'WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256.' + ) + return verifier + } + const hashed = await sha256(verifier) + return btoa(hashed).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') +} + +export async function getCodeChallengeAndMethod( + storage: SupportedStorage, + storageKey: string, + isPasswordRecovery = false +) { + const codeVerifier = generatePKCEVerifier() + let storedCodeVerifier = codeVerifier + if (isPasswordRecovery) { + storedCodeVerifier += '/PASSWORD_RECOVERY' + } + await setItemAsync(storage, `${storageKey}-code-verifier`, storedCodeVerifier) + const codeChallenge = await generatePKCEChallenge(codeVerifier) + const codeChallengeMethod = codeVerifier === codeChallenge ? 'plain' : 's256' + return [codeChallenge, codeChallengeMethod] +} + +/** Parses the API version which is 2YYY-MM-DD. */ +const API_VERSION_REGEX = /^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i + +export function parseResponseAPIVersion(response: Response) { + const apiVersion = response.headers.get(API_VERSION_HEADER_NAME) + + if (!apiVersion) { + return null + } + + if (!apiVersion.match(API_VERSION_REGEX)) { + return null + } + + try { + const date = new Date(`${apiVersion}T00:00:00.0Z`) + return date + } catch (e: any) { + return null + } +} + +export function validateExp(exp: number) { + if (!exp) { + throw new Error('Missing exp claim') + } + const timeNow = Math.floor(Date.now() / 1000) + if (exp <= timeNow) { + throw new Error('JWT has expired') + } +} + +export function getAlgorithm( + alg: 'HS256' | 'RS256' | 'ES256' +): RsaHashedImportParams | EcKeyImportParams { + switch (alg) { + case 'RS256': + return { + name: 'RSASSA-PKCS1-v1_5', + hash: { name: 'SHA-256' }, + } + case 'ES256': + return { + name: 'ECDSA', + namedCurve: 'P-256', + hash: { name: 'SHA-256' }, + } + default: + throw new Error('Invalid alg claim') + } +} + +const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/ + +export function validateUUID(str: string) { + if (!UUID_REGEX.test(str)) { + throw new Error('@supabase/auth-js: Expected parameter to be UUID but is not') + } +} + +export function userNotAvailableProxy(): User { + const proxyTarget = {} as User + + return new Proxy(proxyTarget, { + get: (target: any, prop: string) => { + if (prop === '__isUserNotAvailableProxy') { + return true + } + // Preventative check for common problematic symbols during cloning/inspection + // These symbols might be accessed by structuredClone or other internal mechanisms. + if (typeof prop === 'symbol') { + const sProp = (prop as symbol).toString() + if ( + sProp === 'Symbol(Symbol.toPrimitive)' || + sProp === 'Symbol(Symbol.toStringTag)' || + sProp === 'Symbol(util.inspect.custom)' + ) { + // Node.js util.inspect + return undefined + } + } + throw new Error( + `@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${prop}" property of the session object is not supported. Please use getUser() instead.` + ) + }, + set: (_target: any, prop: string) => { + throw new Error( + `@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${prop}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.` + ) + }, + deleteProperty: (_target: any, prop: string) => { + throw new Error( + `@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${prop}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.` + ) + }, + }) +} + +/** + * Creates a proxy around a user object that warns when properties are accessed on the server. + * This is used to alert developers that using user data from getSession() on the server is insecure. + * + * @param user The actual user object to wrap + * @param suppressWarningRef An object with a 'value' property that controls warning suppression + * @returns A proxied user object that warns on property access + */ +export function insecureUserWarningProxy(user: User, suppressWarningRef: { value: boolean }): User { + return new Proxy(user, { + get: (target: any, prop: string | symbol, receiver: any) => { + // Allow internal checks without warning + if (prop === '__isInsecureUserWarningProxy') { + return true + } + + // Preventative check for common problematic symbols during cloning/inspection + // These symbols might be accessed by structuredClone or other internal mechanisms + if (typeof prop === 'symbol') { + const sProp = prop.toString() + if ( + sProp === 'Symbol(Symbol.toPrimitive)' || + sProp === 'Symbol(Symbol.toStringTag)' || + sProp === 'Symbol(util.inspect.custom)' || + sProp === 'Symbol(nodejs.util.inspect.custom)' + ) { + // Return the actual value for these symbols to allow proper inspection + return Reflect.get(target, prop, receiver) + } + } + + // Emit warning on first property access + if (!suppressWarningRef.value && typeof prop === 'string') { + console.warn( + 'Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server.' + ) + suppressWarningRef.value = true + } + + return Reflect.get(target, prop, receiver) + }, + }) +} + +/** + * Deep clones a JSON-serializable object using JSON.parse(JSON.stringify(obj)). + * Note: Only works for JSON-safe data. + */ +export function deepClone(obj: T): T { + return JSON.parse(JSON.stringify(obj)) +} diff --git a/backend/node_modules/@supabase/auth-js/src/lib/local-storage.ts b/backend/node_modules/@supabase/auth-js/src/lib/local-storage.ts new file mode 100644 index 0000000..0424b63 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/src/lib/local-storage.ts @@ -0,0 +1,21 @@ +import { SupportedStorage } from './types' + +/** + * Returns a localStorage-like object that stores the key-value pairs in + * memory. + */ +export function memoryLocalStorageAdapter(store: { [key: string]: string } = {}): SupportedStorage { + return { + getItem: (key) => { + return store[key] || null + }, + + setItem: (key, value) => { + store[key] = value + }, + + removeItem: (key) => { + delete store[key] + }, + } +} diff --git a/backend/node_modules/@supabase/auth-js/src/lib/locks.ts b/backend/node_modules/@supabase/auth-js/src/lib/locks.ts new file mode 100644 index 0000000..5dc448e --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/src/lib/locks.ts @@ -0,0 +1,268 @@ +import { supportsLocalStorage } from './helpers' + +/** + * @experimental + */ +export const internals = { + /** + * @experimental + */ + debug: !!( + globalThis && + supportsLocalStorage() && + globalThis.localStorage && + globalThis.localStorage.getItem('supabase.gotrue-js.locks.debug') === 'true' + ), +} + +/** + * An error thrown when a lock cannot be acquired after some amount of time. + * + * Use the {@link #isAcquireTimeout} property instead of checking with `instanceof`. + * + * @example + * ```ts + * import { LockAcquireTimeoutError } from '@supabase/auth-js' + * + * class CustomLockError extends LockAcquireTimeoutError { + * constructor() { + * super('Lock timed out') + * } + * } + * ``` + */ +export abstract class LockAcquireTimeoutError extends Error { + public readonly isAcquireTimeout = true + + constructor(message: string) { + super(message) + } +} + +/** + * Error thrown when the browser Navigator Lock API fails to acquire a lock. + * + * @example + * ```ts + * import { NavigatorLockAcquireTimeoutError } from '@supabase/auth-js' + * + * throw new NavigatorLockAcquireTimeoutError('Lock timed out') + * ``` + */ +export class NavigatorLockAcquireTimeoutError extends LockAcquireTimeoutError {} +/** + * Error thrown when the process-level lock helper cannot acquire a lock. + * + * @example + * ```ts + * import { ProcessLockAcquireTimeoutError } from '@supabase/auth-js' + * + * throw new ProcessLockAcquireTimeoutError('Lock timed out') + * ``` + */ +export class ProcessLockAcquireTimeoutError extends LockAcquireTimeoutError {} + +/** + * Implements a global exclusive lock using the Navigator LockManager API. It + * is available on all browsers released after 2022-03-15 with Safari being the + * last one to release support. If the API is not available, this function will + * throw. Make sure you check availablility before configuring {@link + * GoTrueClient}. + * + * You can turn on debugging by setting the `supabase.gotrue-js.locks.debug` + * local storage item to `true`. + * + * Internals: + * + * Since the LockManager API does not preserve stack traces for the async + * function passed in the `request` method, a trick is used where acquiring the + * lock releases a previously started promise to run the operation in the `fn` + * function. The lock waits for that promise to finish (with or without error), + * while the function will finally wait for the result anyway. + * + * @param name Name of the lock to be acquired. + * @param acquireTimeout If negative, no timeout. If 0 an error is thrown if + * the lock can't be acquired without waiting. If positive, the lock acquire + * will time out after so many milliseconds. An error is + * a timeout if it has `isAcquireTimeout` set to true. + * @param fn The operation to run once the lock is acquired. + * @example + * ```ts + * await navigatorLock('sync-user', 1000, async () => { + * await refreshSession() + * }) + * ``` + */ +export async function navigatorLock( + name: string, + acquireTimeout: number, + fn: () => Promise +): Promise { + if (internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock: acquire lock', name, acquireTimeout) + } + + const abortController = new globalThis.AbortController() + + if (acquireTimeout > 0) { + setTimeout(() => { + abortController.abort() + if (internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock acquire timed out', name) + } + }, acquireTimeout) + } + + // MDN article: https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request + + // Wrapping navigator.locks.request() with a plain Promise is done as some + // libraries like zone.js patch the Promise object to track the execution + // context. However, it appears that most browsers use an internal promise + // implementation when using the navigator.locks.request() API causing them + // to lose context and emit confusing log messages or break certain features. + // This wrapping is believed to help zone.js track the execution context + // better. + return await Promise.resolve().then(() => + globalThis.navigator.locks.request( + name, + acquireTimeout === 0 + ? { + mode: 'exclusive', + ifAvailable: true, + } + : { + mode: 'exclusive', + signal: abortController.signal, + }, + async (lock) => { + if (lock) { + if (internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock: acquired', name, lock.name) + } + + try { + return await fn() + } finally { + if (internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock: released', name, lock.name) + } + } + } else { + if (acquireTimeout === 0) { + if (internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock: not immediately available', name) + } + + throw new NavigatorLockAcquireTimeoutError( + `Acquiring an exclusive Navigator LockManager lock "${name}" immediately failed` + ) + } else { + if (internals.debug) { + try { + const result = await globalThis.navigator.locks.query() + + console.log( + '@supabase/gotrue-js: Navigator LockManager state', + JSON.stringify(result, null, ' ') + ) + } catch (e: any) { + console.warn( + '@supabase/gotrue-js: Error when querying Navigator LockManager state', + e + ) + } + } + + // Browser is not following the Navigator LockManager spec, it + // returned a null lock when we didn't use ifAvailable. So we can + // pretend the lock is acquired in the name of backward compatibility + // and user experience and just run the function. + console.warn( + '@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request' + ) + + return await fn() + } + } + } + ) + ) +} + +const PROCESS_LOCKS: { [name: string]: Promise } = {} + +/** + * Implements a global exclusive lock that works only in the current process. + * Useful for environments like React Native or other non-browser + * single-process (i.e. no concept of "tabs") environments. + * + * Use {@link #navigatorLock} in browser environments. + * + * @param name Name of the lock to be acquired. + * @param acquireTimeout If negative, no timeout. If 0 an error is thrown if + * the lock can't be acquired without waiting. If positive, the lock acquire + * will time out after so many milliseconds. An error is + * a timeout if it has `isAcquireTimeout` set to true. + * @param fn The operation to run once the lock is acquired. + * @example + * ```ts + * await processLock('migrate', 5000, async () => { + * await runMigration() + * }) + * ``` + */ +export async function processLock( + name: string, + acquireTimeout: number, + fn: () => Promise +): Promise { + const previousOperation = PROCESS_LOCKS[name] ?? Promise.resolve() + + const currentOperation = Promise.race( + [ + previousOperation.catch(() => { + // ignore error of previous operation that we're waiting to finish + return null + }), + acquireTimeout >= 0 + ? new Promise((_, reject) => { + setTimeout(() => { + reject( + new ProcessLockAcquireTimeoutError( + `Acquring process lock with name "${name}" timed out` + ) + ) + }, acquireTimeout) + }) + : null, + ].filter((x) => x) + ) + .catch((e: any) => { + if (e && e.isAcquireTimeout) { + throw e + } + + return null + }) + .then(async () => { + // previous operations finished and we didn't get a race on the acquire + // timeout, so the current operation can finally start + return await fn() + }) + + PROCESS_LOCKS[name] = currentOperation.catch(async (e: any) => { + if (e && e.isAcquireTimeout) { + // if the current operation timed out, it doesn't mean that the previous + // operation finished, so we need contnue waiting for it to finish + await previousOperation + + return null + } + + throw e + }) + + // finally wait for the current operation to finish successfully, with an + // error or with an acquire timeout error + return await currentOperation +} diff --git a/backend/node_modules/@supabase/auth-js/src/lib/polyfills.ts b/backend/node_modules/@supabase/auth-js/src/lib/polyfills.ts new file mode 100644 index 0000000..49aa2d8 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/src/lib/polyfills.ts @@ -0,0 +1,23 @@ +/** + * https://mathiasbynens.be/notes/globalthis + */ +export function polyfillGlobalThis() { + if (typeof globalThis === 'object') return + try { + Object.defineProperty(Object.prototype, '__magic__', { + get: function () { + return this + }, + configurable: true, + }) + // @ts-expect-error 'Allow access to magic' + __magic__.globalThis = __magic__ + // @ts-expect-error 'Allow access to magic' + delete Object.prototype.__magic__ + } catch (e) { + if (typeof self !== 'undefined') { + // @ts-expect-error 'Allow access to globals' + self.globalThis = self + } + } +} diff --git a/backend/node_modules/@supabase/auth-js/src/lib/types.ts b/backend/node_modules/@supabase/auth-js/src/lib/types.ts new file mode 100644 index 0000000..2840d9e --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/src/lib/types.ts @@ -0,0 +1,1816 @@ +import { AuthError } from './errors' +import { Fetch } from './fetch' +import { EIP1193Provider, EthereumSignInInput, Hex } from './web3/ethereum' +import type { SolanaSignInInput, SolanaSignInOutput } from './web3/solana' +import { + ServerCredentialCreationOptions, + ServerCredentialRequestOptions, + WebAuthnApi, +} from './webauthn' +import { + AuthenticationCredential, + PublicKeyCredentialCreationOptionsFuture, + PublicKeyCredentialRequestOptionsFuture, + RegistrationCredential, +} from './webauthn.dom' + +/** One of the providers supported by GoTrue. */ +export type Provider = + | 'apple' + | 'azure' + | 'bitbucket' + | 'discord' + | 'facebook' + | 'figma' + | 'github' + | 'gitlab' + | 'google' + | 'kakao' + | 'keycloak' + | 'linkedin' + | 'linkedin_oidc' + | 'notion' + | 'slack' + | 'slack_oidc' + | 'spotify' + | 'twitch' + | 'twitter' + | 'workos' + | 'zoom' + | 'fly' + +export type AuthChangeEventMFA = 'MFA_CHALLENGE_VERIFIED' + +export type AuthChangeEvent = + | 'INITIAL_SESSION' + | 'PASSWORD_RECOVERY' + | 'SIGNED_IN' + | 'SIGNED_OUT' + | 'TOKEN_REFRESHED' + | 'USER_UPDATED' + | AuthChangeEventMFA + +/** + * Provide your own global lock implementation instead of the default + * implementation. The function should acquire a lock for the duration of the + * `fn` async function, such that no other client instances will be able to + * hold it at the same time. + * + * @experimental + * + * @param name Name of the lock to be acquired. + * @param acquireTimeout If negative, no timeout should occur. If positive it + * should throw an Error with an `isAcquireTimeout` + * property set to true if the operation fails to be + * acquired after this much time (ms). + * @param fn The operation to execute when the lock is acquired. + */ +export type LockFunc = (name: string, acquireTimeout: number, fn: () => Promise) => Promise + +export type GoTrueClientOptions = { + /* The URL of the GoTrue server. */ + url?: string + /* Any additional headers to send to the GoTrue server. */ + headers?: { [key: string]: string } + /* Optional key name used for storing tokens in local storage. */ + storageKey?: string + /* Set to "true" if you want to automatically detects OAuth grants in the URL and signs in the user. */ + detectSessionInUrl?: boolean + /* Set to "true" if you want to automatically refresh the token before expiring. */ + autoRefreshToken?: boolean + /* Set to "true" if you want to automatically save the user session into local storage. If set to false, session will just be saved in memory. */ + persistSession?: boolean + /* Provide your own local storage implementation to use instead of the browser's local storage. */ + storage?: SupportedStorage + /** + * Stores the user object in a separate storage location from the rest of the session data. When non-null, `storage` will only store a JSON object containing the access and refresh token and some adjacent metadata, while `userStorage` will only contain the user object under the key `storageKey + '-user'`. + * + * When this option is set and cookie storage is used, `getSession()` and other functions that load a session from the cookie store might not return back a user. It's very important to always use `getUser()` to fetch a user object in those scenarios. + * + * @experimental + */ + userStorage?: SupportedStorage + /* A custom fetch implementation. */ + fetch?: Fetch + /* If set to 'pkce' PKCE flow. Defaults to the 'implicit' flow otherwise */ + flowType?: AuthFlowType + /* If debug messages are emitted. Can be used to inspect the behavior of the library. If set to a function, the provided function will be used instead of `console.log()` to perform the logging. */ + debug?: boolean | ((message: string, ...args: any[]) => void) + /** + * Provide your own locking mechanism based on the environment. By default no locking is done at this time. + * + * @experimental + */ + lock?: LockFunc + /** + * Set to "true" if there is a custom authorization header set globally. + * @experimental + */ + hasCustomAuthorizationHeader?: boolean + /** + * If there is an error with the query, throwOnError will reject the promise by + * throwing the error instead of returning it as part of a successful response. + */ + throwOnError?: boolean +} + +const WeakPasswordReasons = ['length', 'characters', 'pwned'] as const + +export type WeakPasswordReasons = (typeof WeakPasswordReasons)[number] +export type WeakPassword = { + reasons: WeakPasswordReasons[] + message: string +} + +/** + * Resolve mapped types and show the derived keys and their types when hovering in + * VS Code, instead of just showing the names those mapped types are defined with. + */ +export type Prettify = T extends Function ? T : { [K in keyof T]: T[K] } + +/** + * A stricter version of TypeScript's Omit that only allows omitting keys that actually exist. + * This prevents typos and ensures type safety at compile time. + * Unlike regular Omit, this will error if you try to omit a non-existent key. + */ +export type StrictOmit = Omit + +/** + * a shared result type that encapsulates errors instead of throwing them, allows you to optionally specify the ErrorType + */ +export type RequestResult = + | { + data: T + error: null + } + | { + data: null + error: Error extends AuthError ? AuthError : ErrorType + } + +/** + * similar to RequestResult except it allows you to destructure the possible shape of the success response + * {@see RequestResult} + */ +export type RequestResultSafeDestructure = + | { data: T; error: null } + | { + data: T extends object ? { [K in keyof T]: null } : null + error: AuthError + } + +export type AuthResponse = RequestResultSafeDestructure<{ + user: User | null + session: Session | null +}> + +export type AuthResponsePassword = RequestResultSafeDestructure<{ + user: User | null + session: Session | null + weak_password?: WeakPassword | null +}> + +/** + * AuthOtpResponse is returned when OTP is used. + * + * {@see AuthResponse} + */ +export type AuthOtpResponse = RequestResultSafeDestructure<{ + user: null + session: null + messageId?: string | null +}> + +export type AuthTokenResponse = RequestResultSafeDestructure<{ + user: User + session: Session +}> + +export type AuthTokenResponsePassword = RequestResultSafeDestructure<{ + user: User + session: Session + weakPassword?: WeakPassword +}> + +export type OAuthResponse = + | { + data: { + provider: Provider + url: string + } + error: null + } + | { + data: { + provider: Provider + url: null + } + error: AuthError + } + +export type SSOResponse = RequestResult<{ + /** + * URL to open in a browser which will complete the sign-in flow by + * taking the user to the identity provider's authentication flow. + * + * On browsers you can set the URL to `window.location.href` to take + * the user to the authentication flow. + */ + url: string +}> + +export type UserResponse = RequestResultSafeDestructure<{ + user: User +}> + +export interface Session { + /** + * The oauth provider token. If present, this can be used to make external API requests to the oauth provider used. + */ + provider_token?: string | null + /** + * The oauth provider refresh token. If present, this can be used to refresh the provider_token via the oauth provider's API. + * Not all oauth providers return a provider refresh token. If the provider_refresh_token is missing, please refer to the oauth provider's documentation for information on how to obtain the provider refresh token. + */ + provider_refresh_token?: string | null + /** + * The access token jwt. It is recommended to set the JWT_EXPIRY to a shorter expiry value. + */ + access_token: string + /** + * A one-time used refresh token that never expires. + */ + refresh_token: string + /** + * The number of seconds until the token expires (since it was issued). Returned when a login is confirmed. + */ + expires_in: number + /** + * A timestamp of when the token will expire. Returned when a login is confirmed. + */ + expires_at?: number + token_type: 'bearer' + + /** + * When using a separate user storage, accessing properties of this object will throw an error. + */ + user: User +} + +const AMRMethods = [ + 'password', + 'otp', + 'oauth', + 'totp', + 'mfa/totp', + 'mfa/phone', + 'mfa/webauthn', + 'anonymous', + 'sso/saml', + 'magiclink', + 'web3', +] as const + +export type AMRMethod = (typeof AMRMethods)[number] | (string & {}) + +/** + * An authentication methord reference (AMR) entry. + * + * An entry designates what method was used by the user to verify their + * identity and at what time. + * + * @see {@link GoTrueMFAApi#getAuthenticatorAssuranceLevel}. + */ +export interface AMREntry { + /** Authentication method name. */ + method: AMRMethod + + /** + * Timestamp when the method was successfully used. Represents number of + * seconds since 1st January 1970 (UNIX epoch) in UTC. + */ + timestamp: number +} + +export interface UserIdentity { + id: string + user_id: string + identity_data?: { + [key: string]: any + } + identity_id: string + provider: string + created_at?: string + last_sign_in_at?: string + updated_at?: string +} + +const FactorTypes = ['totp', 'phone', 'webauthn'] as const + +/** + * Type of factor. `totp` and `phone` supported with this version + */ +export type FactorType = (typeof FactorTypes)[number] + +const FactorVerificationStatuses = ['verified', 'unverified'] as const + +/** + * The verification status of the factor, default is `unverified` after `.enroll()`, then `verified` after the user verifies it with `.verify()` + */ +type FactorVerificationStatus = (typeof FactorVerificationStatuses)[number] + +/** + * A MFA factor. + * + * @see {@link GoTrueMFAApi#enroll} + * @see {@link GoTrueMFAApi#listFactors} + * @see {@link GoTrueMFAAdminApi#listFactors} + */ +export type Factor< + Type extends FactorType = FactorType, + Status extends FactorVerificationStatus = (typeof FactorVerificationStatuses)[number], +> = { + /** ID of the factor. */ + id: string + + /** Friendly name of the factor, useful to disambiguate between multiple factors. */ + friendly_name?: string + + /** + * Type of factor. `totp` and `phone` supported with this version + */ + factor_type: Type + + /** + * The verification status of the factor, default is `unverified` after `.enroll()`, then `verified` after the user verifies it with `.verify()` + */ + status: Status + + created_at: string + updated_at: string +} + +export interface UserAppMetadata { + /** + * The first provider that the user used to sign up with. + */ + provider?: string + /** + * A list of all providers that the user has linked to their account. + */ + providers?: string[] + [key: string]: any +} + +export interface UserMetadata { + [key: string]: any +} + +export interface User { + id: string + app_metadata: UserAppMetadata + user_metadata: UserMetadata + aud: string + confirmation_sent_at?: string + recovery_sent_at?: string + email_change_sent_at?: string + new_email?: string + new_phone?: string + invited_at?: string + action_link?: string + email?: string + phone?: string + created_at: string + confirmed_at?: string + email_confirmed_at?: string + phone_confirmed_at?: string + last_sign_in_at?: string + role?: string + updated_at?: string + identities?: UserIdentity[] + is_anonymous?: boolean + is_sso_user?: boolean + factors?: (Factor | Factor)[] + deleted_at?: string +} + +export interface UserAttributes { + /** + * The user's email. + */ + email?: string + + /** + * The user's phone. + */ + phone?: string + + /** + * The user's password. + */ + password?: string + + /** + * The nonce sent for reauthentication if the user's password is to be updated. + * + * Call reauthenticate() to obtain the nonce first. + */ + nonce?: string + + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.raw_user_meta_data` column. + * + * The `data` should be a JSON object that includes user-specific info, such as their first and last name. + * + */ + data?: object +} + +export interface AdminUserAttributes extends Omit { + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.raw_user_meta_data` column. + * + * + * The `user_metadata` should be a JSON object that includes user-specific info, such as their first and last name. + * + * Note: When using the GoTrueAdminApi and wanting to modify a user's metadata, + * this attribute is used instead of UserAttributes data. + * + */ + user_metadata?: object + + /** + * A custom data object to store the user's application specific metadata. This maps to the `auth.users.app_metadata` column. + * + * Only a service role can modify. + * + * The `app_metadata` should be a JSON object that includes app-specific info, such as identity providers, roles, and other + * access control information. + */ + app_metadata?: object + + /** + * Confirms the user's email address if set to true. + * + * Only a service role can modify. + */ + email_confirm?: boolean + + /** + * Confirms the user's phone number if set to true. + * + * Only a service role can modify. + */ + phone_confirm?: boolean + + /** + * Determines how long a user is banned for. + * + * The format for the ban duration follows a strict sequence of decimal numbers with a unit suffix. + * Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h". + * + * For example, some possible durations include: '300ms', '2h45m'. + * + * Setting the ban duration to 'none' lifts the ban on the user. + */ + ban_duration?: string | 'none' + + /** + * The `role` claim set in the user's access token JWT. + * + * When a user signs up, this role is set to `authenticated` by default. You should only modify the `role` if you need to provision several levels of admin access that have different permissions on individual columns in your database. + * + * Setting this role to `service_role` is not recommended as it grants the user admin privileges. + */ + role?: string + + /** + * The `password_hash` for the user's password. + * + * Allows you to specify a password hash for the user. This is useful for migrating a user's password hash from another service. + * + * Supports bcrypt, scrypt (firebase), and argon2 password hashes. + */ + password_hash?: string + + /** + * The `id` for the user. + * + * Allows you to overwrite the default `id` set for the user. + */ + id?: string +} + +export interface Subscription { + /** + * A unique identifier for this subscription, set by the client. + * This is an internal identifier used for managing callbacks and should not be + * relied upon by application code. Use the unsubscribe() method to remove listeners. + */ + id: string | symbol + /** + * The function to call every time there is an event. eg: (eventName) => {} + */ + callback: (event: AuthChangeEvent, session: Session | null) => void + /** + * Call this to remove the listener. + */ + unsubscribe: () => void +} + +export type SignInAnonymouslyCredentials = { + options?: { + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.raw_user_meta_data` column. + * + * The `data` should be a JSON object that includes user-specific info, such as their first and last name. + */ + data?: object + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string + } +} + +export type SignUpWithPasswordCredentials = Prettify< + PasswordCredentialsBase & { + options?: { + emailRedirectTo?: string // only for email + data?: object + captchaToken?: string + channel?: 'sms' | 'whatsapp' // only for phone + } + } +> + +type PasswordCredentialsBase = + | { email: string; password: string } + | { phone: string; password: string } + +export type SignInWithPasswordCredentials = PasswordCredentialsBase & { + options?: { + captchaToken?: string + } +} + +export type SignInWithPasswordlessCredentials = + | { + /** The user's email address. */ + email: string + options?: { + /** The redirect url embedded in the email link */ + emailRedirectTo?: string + /** If set to false, this method will not create a new user. Defaults to true. */ + shouldCreateUser?: boolean + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.raw_user_meta_data` column. + * + * The `data` should be a JSON object that includes user-specific info, such as their first and last name. + */ + data?: object + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string + } + } + | { + /** The user's phone number. */ + phone: string + options?: { + /** If set to false, this method will not create a new user. Defaults to true. */ + shouldCreateUser?: boolean + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.raw_user_meta_data` column. + * + * The `data` should be a JSON object that includes user-specific info, such as their first and last name. + */ + data?: object + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string + /** Messaging channel to use (e.g. whatsapp or sms) */ + channel?: 'sms' | 'whatsapp' + } + } + +export type AuthFlowType = 'implicit' | 'pkce' +export type SignInWithOAuthCredentials = { + /** One of the providers supported by GoTrue. */ + provider: Provider + options?: { + /** A URL to send the user to after they are confirmed. */ + redirectTo?: string + /** A space-separated list of scopes granted to the OAuth application. */ + scopes?: string + /** An object of query params */ + queryParams?: { [key: string]: string } + /** If set to true does not immediately redirect the current browser context to visit the OAuth authorization page for the provider. */ + skipBrowserRedirect?: boolean + } +} + +export type SignInWithIdTokenCredentials = { + /** Provider name or OIDC `iss` value identifying which provider should be used to verify the provided token. Supported names: `google`, `apple`, `azure`, `facebook`, `kakao`, `keycloak` (deprecated). */ + provider: 'google' | 'apple' | 'azure' | 'facebook' | 'kakao' | (string & {}) + /** OIDC ID token issued by the specified provider. The `iss` claim in the ID token must match the supplied provider. Some ID tokens contain an `at_hash` which require that you provide an `access_token` value to be accepted properly. If the token contains a `nonce` claim you must supply the nonce used to obtain the ID token. */ + token: string + /** If the ID token contains an `at_hash` claim, then the hash of this value is compared to the value in the ID token. */ + access_token?: string + /** If the ID token contains a `nonce` claim, then the hash of this value is compared to the value in the ID token. */ + nonce?: string + options?: { + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string + } +} + +export type SolanaWallet = { + signIn?: (...inputs: SolanaSignInInput[]) => Promise + publicKey?: { + toBase58: () => string + } | null + + signMessage?: (message: Uint8Array, encoding?: 'utf8' | string) => Promise | undefined +} + +export type SolanaWeb3Credentials = + | { + chain: 'solana' + + /** Wallet interface to use. If not specified will default to `window.solana`. */ + wallet?: SolanaWallet + + /** Optional statement to include in the Sign in with Solana message. Must not include new line characters. Most wallets like Phantom **require specifying a statement!** */ + statement?: string + + options?: { + /** URL to use with the wallet interface. Some wallets do not allow signing a message for URLs different from the current page. */ + url?: string + + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string + + signInWithSolana?: Partial< + Omit + > + } + } + | { + chain: 'solana' + + /** Sign in with Solana compatible message. Must include `Issued At`, `URI` and `Version`. */ + message: string + + /** Ed25519 signature of the message. */ + signature: Uint8Array + + options?: { + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string + } + } + +export type EthereumWallet = EIP1193Provider + +export type EthereumWeb3Credentials = + | { + chain: 'ethereum' + + /** Wallet interface to use. If not specified will default to `window.ethereum`. */ + wallet?: EthereumWallet + + /** Optional statement to include in the Sign in with Ethereum message. Must not include new line characters. Most wallets like Phantom **require specifying a statement!** */ + statement?: string + + options?: { + /** URL to use with the wallet interface. Some wallets do not allow signing a message for URLs different from the current page. */ + url?: string + + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string + + signInWithEthereum?: Partial< + Omit + > + } + } + | { + chain: 'ethereum' + + /** Sign in with Ethereum compatible message. Must include `Issued At`, `URI` and `Version`. */ + message: string + + /** Ethereum curve (secp256k1) signature of the message. */ + signature: Hex + + options?: { + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string + } + } + +export type Web3Credentials = SolanaWeb3Credentials | EthereumWeb3Credentials + +export type VerifyOtpParams = VerifyMobileOtpParams | VerifyEmailOtpParams | VerifyTokenHashParams +export interface VerifyMobileOtpParams { + /** The user's phone number. */ + phone: string + /** The otp sent to the user's phone number. */ + token: string + /** The user's verification type. */ + type: MobileOtpType + options?: { + /** A URL to send the user to after they are confirmed. */ + redirectTo?: string + + /** + * Verification token received when the user completes the captcha on the site. + * + * @deprecated + */ + captchaToken?: string + } +} +export interface VerifyEmailOtpParams { + /** The user's email address. */ + email: string + /** The otp sent to the user's email address. */ + token: string + /** The user's verification type. */ + type: EmailOtpType + options?: { + /** A URL to send the user to after they are confirmed. */ + redirectTo?: string + + /** Verification token received when the user completes the captcha on the site. + * + * @deprecated + */ + captchaToken?: string + } +} + +export interface VerifyTokenHashParams { + /** The token hash used in an email link */ + token_hash: string + + /** The user's verification type. */ + type: EmailOtpType +} + +export type MobileOtpType = 'sms' | 'phone_change' +export type EmailOtpType = 'signup' | 'invite' | 'magiclink' | 'recovery' | 'email_change' | 'email' + +export type ResendParams = + | { + type: Extract + email: string + options?: { + /** A URL to send the user to after they have signed-in. */ + emailRedirectTo?: string + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string + } + } + | { + type: Extract + phone: string + options?: { + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string + } + } + +export type SignInWithSSO = + | { + /** UUID of the SSO provider to invoke single-sign on to. */ + providerId: string + + options?: { + /** A URL to send the user to after they have signed-in. */ + redirectTo?: string + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string + /** + * If set to true, the redirect will not happen on the client side. + * This parameter is used when you wish to handle the redirect yourself. + * Defaults to false. + */ + skipBrowserRedirect?: boolean + } + } + | { + /** Domain name of the organization for which to invoke single-sign on. */ + domain: string + + options?: { + /** A URL to send the user to after they have signed-in. */ + redirectTo?: string + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string + /** + * If set to true, the redirect will not happen on the client side. + * This parameter is used when you wish to handle the redirect yourself. + * Defaults to false. + */ + skipBrowserRedirect?: boolean + } + } + +export type GenerateSignupLinkParams = { + type: 'signup' + email: string + password: string + options?: Pick +} + +export type GenerateInviteOrMagiclinkParams = { + type: 'invite' | 'magiclink' + /** The user's email */ + email: string + options?: Pick +} + +export type GenerateRecoveryLinkParams = { + type: 'recovery' + /** The user's email */ + email: string + options?: Pick +} + +export type GenerateEmailChangeLinkParams = { + type: 'email_change_current' | 'email_change_new' + /** The user's email */ + email: string + /** + * The user's new email. Only required if type is 'email_change_current' or 'email_change_new'. + */ + newEmail: string + options?: Pick +} + +export interface GenerateLinkOptions { + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.raw_user_meta_data` column. + * + * The `data` should be a JSON object that includes user-specific info, such as their first and last name. + */ + data?: object + /** The URL which will be appended to the email link generated. */ + redirectTo?: string +} + +export type GenerateLinkParams = + | GenerateSignupLinkParams + | GenerateInviteOrMagiclinkParams + | GenerateRecoveryLinkParams + | GenerateEmailChangeLinkParams + +export type GenerateLinkResponse = RequestResultSafeDestructure<{ + properties: GenerateLinkProperties + user: User +}> + +/** The properties related to the email link generated */ +export type GenerateLinkProperties = { + /** + * The email link to send to the user. + * The action_link follows the following format: auth/v1/verify?type={verification_type}&token={hashed_token}&redirect_to={redirect_to} + * */ + action_link: string + /** + * The raw email OTP. + * You should send this in the email if you want your users to verify using an OTP instead of the action link. + * */ + email_otp: string + /** + * The hashed token appended to the action link. + * */ + hashed_token: string + /** The URL appended to the action link. */ + redirect_to: string + /** The verification type that the email link is associated to. */ + verification_type: GenerateLinkType +} + +export type GenerateLinkType = + | 'signup' + | 'invite' + | 'magiclink' + | 'recovery' + | 'email_change_current' + | 'email_change_new' + +export type MFAEnrollParams = MFAEnrollTOTPParams | MFAEnrollPhoneParams | MFAEnrollWebauthnParams + +export type MFAUnenrollParams = { + /** ID of the factor being unenrolled. */ + factorId: string +} + +type MFAVerifyParamsBase = { + /** ID of the factor being verified. Returned in enroll(). */ + factorId: string + /** ID of the challenge being verified. Returned in challenge(). */ + challengeId: string +} + +type MFAVerifyTOTPParamFields = { + /** Verification code provided by the user. */ + code: string +} + +export type MFAVerifyTOTPParams = Prettify + +type MFAVerifyPhoneParamFields = MFAVerifyTOTPParamFields + +export type MFAVerifyPhoneParams = Prettify + +type MFAVerifyWebauthnParamFieldsBase = { + /** Relying party ID */ + rpId: string + /** Relying party origins */ + rpOrigins?: string[] +} + +type MFAVerifyWebauthnCredentialParamFields = + { + /** Operation type */ + type: T + /** Creation response from the authenticator (for enrollment/unverified factors) */ + credential_response: T extends 'create' ? RegistrationCredential : AuthenticationCredential + } + +/** + * WebAuthn-specific fields for MFA verification. + * Supports both credential creation (registration) and request (authentication) flows. + * @template T - Type of WebAuthn operation: 'create' for registration, 'request' for authentication + */ +export type MFAVerifyWebauthnParamFields = { + webauthn: MFAVerifyWebauthnParamFieldsBase & MFAVerifyWebauthnCredentialParamFields +} + +/** + * Parameters for WebAuthn MFA verification. + * Used to verify WebAuthn credentials after challenge. + * @template T - Type of WebAuthn operation: 'create' for registration, 'request' for authentication + * @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying an Authentication Assertion} + */ +export type MFAVerifyWebauthnParams = + Prettify> + +export type MFAVerifyParams = MFAVerifyTOTPParams | MFAVerifyPhoneParams | MFAVerifyWebauthnParams + +type MFAChallengeParamsBase = { + /** ID of the factor to be challenged. Returned in enroll(). */ + factorId: string +} + +const MFATOTPChannels = ['sms', 'whatsapp'] as const +export type MFATOTPChannel = (typeof MFATOTPChannels)[number] + +export type MFAChallengeTOTPParams = Prettify + +type MFAChallengePhoneParamFields = { + /** Messaging channel to use (e.g. whatsapp or sms). Only relevant for phone factors */ + channel: Channel +} + +export type MFAChallengePhoneParams = Prettify< + MFAChallengeParamsBase & MFAChallengePhoneParamFields +> + +/** WebAuthn parameters for WebAuthn factor challenge */ +type MFAChallengeWebauthnParamFields = { + webauthn: { + /** Relying party ID */ + rpId: string + /** Relying party origins*/ + rpOrigins?: string[] + } +} + +/** + * Parameters for initiating a WebAuthn MFA challenge. + * Includes Relying Party information needed for WebAuthn ceremonies. + * @see {@link https://w3c.github.io/webauthn/#sctn-rp-operations W3C WebAuthn Spec - Relying Party Operations} + */ +export type MFAChallengeWebauthnParams = Prettify< + MFAChallengeParamsBase & MFAChallengeWebauthnParamFields +> + +export type MFAChallengeParams = + | MFAChallengeTOTPParams + | MFAChallengePhoneParams + | MFAChallengeWebauthnParams + +type MFAChallengeAndVerifyParamsBase = Omit + +type MFAChallengeAndVerifyTOTPParamFields = MFAVerifyTOTPParamFields + +type MFAChallengeAndVerifyTOTPParams = Prettify< + MFAChallengeAndVerifyParamsBase & MFAChallengeAndVerifyTOTPParamFields +> + +export type MFAChallengeAndVerifyParams = MFAChallengeAndVerifyTOTPParams + +/** + * Data returned after successful MFA verification. + * Contains new session tokens and updated user information. + */ +export type AuthMFAVerifyResponseData = { + /** New access token (JWT) after successful verification. */ + access_token: string + + /** Type of token, always `bearer`. */ + token_type: 'bearer' + + /** Number of seconds in which the access token will expire. */ + expires_in: number + + /** Refresh token you can use to obtain new access tokens when expired. */ + refresh_token: string + + /** Updated user profile. */ + user: User +} + +/** + * Response type for MFA verification operations. + * Returns session tokens on successful verification. + */ +export type AuthMFAVerifyResponse = RequestResult + +export type AuthMFAEnrollResponse = + | AuthMFAEnrollTOTPResponse + | AuthMFAEnrollPhoneResponse + | AuthMFAEnrollWebauthnResponse + +export type AuthMFAUnenrollResponse = RequestResult<{ + /** ID of the factor that was successfully unenrolled. */ + id: string +}> + +type AuthMFAChallengeResponseBase = { + /** ID of the newly created challenge. */ + id: string + + /** Factor Type which generated the challenge */ + type: T + + /** Timestamp in UNIX seconds when this challenge will no longer be usable. */ + expires_at: number +} + +type AuthMFAChallengeTOTPResponseFields = { + /** no extra fields for now, kept for consistency and for possible future changes */ +} + +export type AuthMFAChallengeTOTPResponse = RequestResult< + Prettify & AuthMFAChallengeTOTPResponseFields> +> + +type AuthMFAChallengePhoneResponseFields = { + /** no extra fields for now, kept for consistency and for possible future changes */ +} + +export type AuthMFAChallengePhoneResponse = RequestResult< + Prettify & AuthMFAChallengePhoneResponseFields> +> + +type AuthMFAChallengeWebauthnResponseFields = { + webauthn: + | { + type: 'create' + credential_options: { publicKey: PublicKeyCredentialCreationOptionsFuture } + } + | { + type: 'request' + credential_options: { publicKey: PublicKeyCredentialRequestOptionsFuture } + } +} + +/** + * Response type for WebAuthn MFA challenge. + * Contains credential creation or request options from the server. + * @see {@link https://w3c.github.io/webauthn/#sctn-credential-creation W3C WebAuthn Spec - Credential Creation} + */ +export type AuthMFAChallengeWebauthnResponse = RequestResult< + Prettify & AuthMFAChallengeWebauthnResponseFields> +> + +type AuthMFAChallengeWebauthnResponseFieldsJSON = { + webauthn: + | { + type: 'create' + credential_options: { publicKey: ServerCredentialCreationOptions } + } + | { + type: 'request' + credential_options: { publicKey: ServerCredentialRequestOptions } + } +} + +/** + * JSON-serializable version of WebAuthn challenge response. + * Used for server communication with base64url-encoded binary fields. + */ +export type AuthMFAChallengeWebauthnResponseDataJSON = Prettify< + AuthMFAChallengeResponseBase<'webauthn'> & AuthMFAChallengeWebauthnResponseFieldsJSON +> + +/** + * Server response type for WebAuthn MFA challenge. + * Contains JSON-formatted WebAuthn options ready for browser API. + */ +export type AuthMFAChallengeWebauthnServerResponse = + RequestResult + +export type AuthMFAChallengeResponse = + | AuthMFAChallengeTOTPResponse + | AuthMFAChallengePhoneResponse + | AuthMFAChallengeWebauthnResponse + +/** response of ListFactors, which should contain all the types of factors that are available, this ensures we always include all */ +export type AuthMFAListFactorsResponse = + RequestResult< + { + /** All available factors (verified and unverified). */ + all: Prettify[] + + // Dynamically create a property for each factor type with only verified factors + } & { + [K in T[number]]: Prettify>[] + } + > + +export type AuthenticatorAssuranceLevels = 'aal1' | 'aal2' + +export type AuthMFAGetAuthenticatorAssuranceLevelResponse = RequestResult<{ + /** Current AAL level of the session. */ + currentLevel: AuthenticatorAssuranceLevels | null + + /** + * Next possible AAL level for the session. If the next level is higher + * than the current one, the user should go through MFA. + * + * @see {@link GoTrueMFAApi#challenge} + */ + nextLevel: AuthenticatorAssuranceLevels | null + + /** + * A list of all authentication methods attached to this session. Use + * the information here to detect the last time a user verified a + * factor, for example if implementing a step-up scenario. + */ + currentAuthenticationMethods: AMREntry[] +}> + +/** + * Contains the full multi-factor authentication API. + * + */ +export interface GoTrueMFAApi { + /** + * Starts the enrollment process for a new Multi-Factor Authentication (MFA) + * factor. This method creates a new `unverified` factor. + * To verify a factor, present the QR code or secret to the user and ask them to add it to their + * authenticator app. + * The user has to enter the code from their authenticator app to verify it. + * + * Upon verifying a factor, all other sessions are logged out and the current session's authenticator level is promoted to `aal2`. + */ + enroll(params: MFAEnrollTOTPParams): Promise + enroll(params: MFAEnrollPhoneParams): Promise + enroll(params: MFAEnrollWebauthnParams): Promise + enroll(params: MFAEnrollParams): Promise + + /** + * Prepares a challenge used to verify that a user has access to a MFA + * factor. + */ + challenge(params: MFAChallengeTOTPParams): Promise> + challenge(params: MFAChallengePhoneParams): Promise> + challenge(params: MFAChallengeWebauthnParams): Promise> + challenge(params: MFAChallengeParams): Promise + + /** + * Verifies a code against a challenge. The verification code is + * provided by the user by entering a code seen in their authenticator app. + */ + verify(params: MFAVerifyTOTPParams): Promise + verify(params: MFAVerifyPhoneParams): Promise + verify(params: MFAVerifyWebauthnParams): Promise + verify(params: MFAVerifyParams): Promise + + /** + * Unenroll removes a MFA factor. + * A user has to have an `aal2` authenticator level in order to unenroll a `verified` factor. + */ + unenroll(params: MFAUnenrollParams): Promise + + /** + * Helper method which creates a challenge and immediately uses the given code to verify against it thereafter. The verification code is + * provided by the user by entering a code seen in their authenticator app. + */ + challengeAndVerify(params: MFAChallengeAndVerifyParams): Promise + + /** + * Returns the list of MFA factors enabled for this user. + * + * @see {@link GoTrueMFAApi#enroll} + * @see {@link GoTrueMFAApi#getAuthenticatorAssuranceLevel} + * @see {@link GoTrueClient#getUser} + * + */ + listFactors(): Promise + + /** + * Returns the Authenticator Assurance Level (AAL) for the active session. + * + * - `aal1` (or `null`) means that the user's identity has been verified only + * with a conventional login (email+password, OTP, magic link, social login, + * etc.). + * - `aal2` means that the user's identity has been verified both with a conventional login and at least one MFA factor. + * + * Although this method returns a promise, it's fairly quick (microseconds) + * and rarely uses the network. You can use this to check whether the current + * user needs to be shown a screen to verify their MFA factors. + * + */ + getAuthenticatorAssuranceLevel(): Promise + + // namespace for the webauthn methods + webauthn: WebAuthnApi +} + +/** + * @expermental + */ +export type AuthMFAAdminDeleteFactorResponse = RequestResult<{ + /** ID of the factor that was successfully deleted. */ + id: string +}> +/** + * @expermental + */ +export type AuthMFAAdminDeleteFactorParams = { + /** ID of the MFA factor to delete. */ + id: string + + /** ID of the user whose factor is being deleted. */ + userId: string +} + +/** + * @expermental + */ +export type AuthMFAAdminListFactorsResponse = RequestResult<{ + /** All factors attached to the user. */ + factors: Factor[] +}> + +/** + * @expermental + */ +export type AuthMFAAdminListFactorsParams = { + /** ID of the user. */ + userId: string +} + +/** + * Contains the full multi-factor authentication administration API. + * + * @expermental + */ +export interface GoTrueAdminMFAApi { + /** + * Lists all factors associated to a user. + * + */ + listFactors(params: AuthMFAAdminListFactorsParams): Promise + + /** + * Deletes a factor on a user. This will log the user out of all active + * sessions if the deleted factor was verified. + * + * @see {@link GoTrueMFAApi#unenroll} + * + * @expermental + */ + deleteFactor(params: AuthMFAAdminDeleteFactorParams): Promise +} + +type AnyFunction = (...args: any[]) => any +type MaybePromisify = T | Promise + +type PromisifyMethods = { + [K in keyof T]: T[K] extends AnyFunction + ? (...args: Parameters) => MaybePromisify> + : T[K] +} + +export type SupportedStorage = PromisifyMethods< + Pick +> & { + /** + * If set to `true` signals to the library that the storage medium is used + * on a server and the values may not be authentic, such as reading from + * request cookies. Implementations should not set this to true if the client + * is used on a server that reads storage information from authenticated + * sources, such as a secure database or file. + */ + isServer?: boolean +} + +export type InitializeResult = { error: AuthError | null } + +export type CallRefreshTokenResult = RequestResult + +export type Pagination = { + [key: string]: any + nextPage: number | null + lastPage: number + total: number +} + +export type PageParams = { + /** The page number */ + page?: number + /** Number of items returned per page */ + perPage?: number +} + +export type SignOut = { + /** + * Determines which sessions should be + * logged out. Global means all + * sessions by this account. Local + * means only this session. Others + * means all other sessions except the + * current one. When using others, + * there is no sign-out event fired on + * the current session! + */ + scope?: 'global' | 'local' | 'others' +} + +type MFAEnrollParamsBase = { + /** The type of factor being enrolled. */ + factorType: T + /** Human readable name assigned to the factor. */ + friendlyName?: string +} + +type MFAEnrollTOTPParamFields = { + /** Domain which the user is enrolled with. */ + issuer?: string +} + +export type MFAEnrollTOTPParams = Prettify & MFAEnrollTOTPParamFields> + +type MFAEnrollPhoneParamFields = { + /** Phone number associated with a factor. Number should conform to E.164 format */ + phone: string +} +export type MFAEnrollPhoneParams = Prettify< + MFAEnrollParamsBase<'phone'> & MFAEnrollPhoneParamFields +> + +type MFAEnrollWebauthnFields = { + /** no extra fields for now, kept for consistency and for possible future changes */ +} + +/** + * Parameters for enrolling a WebAuthn factor. + * Creates an unverified WebAuthn factor that must be verified with a credential. + * @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registering a New Credential} + */ +export type MFAEnrollWebauthnParams = Prettify< + MFAEnrollParamsBase<'webauthn'> & MFAEnrollWebauthnFields +> + +type AuthMFAEnrollResponseBase = { + /** ID of the factor that was just enrolled (in an unverified state). */ + id: string + + /** Type of MFA factor.*/ + type: T + + /** Friendly name of the factor, useful for distinguishing between factors **/ + friendly_name?: string +} + +type AuthMFAEnrollTOTPResponseFields = { + /** TOTP enrollment information. */ + totp: { + /** Contains a QR code encoding the authenticator URI. You can + * convert it to a URL by prepending `data:image/svg+xml;utf-8,` to + * the value. Avoid logging this value to the console. */ + qr_code: string + + /** The TOTP secret (also encoded in the QR code). Show this secret + * in a password-style field to the user, in case they are unable to + * scan the QR code. Avoid logging this value to the console. */ + secret: string + + /** The authenticator URI encoded within the QR code, should you need + * to use it. Avoid loggin this value to the console. */ + uri: string + } +} + +export type AuthMFAEnrollTOTPResponse = RequestResult< + Prettify & AuthMFAEnrollTOTPResponseFields> +> + +type AuthMFAEnrollPhoneResponseFields = { + /** Phone number of the MFA factor in E.164 format. Used to send messages */ + phone: string +} + +export type AuthMFAEnrollPhoneResponse = RequestResult< + Prettify & AuthMFAEnrollPhoneResponseFields> +> + +type AuthMFAEnrollWebauthnFields = { + /** no extra fields for now, kept for consistency and for possible future changes */ +} + +/** + * Response type for WebAuthn factor enrollment. + * Returns the enrolled factor ID and metadata. + * @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registering a New Credential} + */ +export type AuthMFAEnrollWebauthnResponse = RequestResult< + Prettify & AuthMFAEnrollWebauthnFields> +> + +export type JwtHeader = { + alg: 'RS256' | 'ES256' | 'HS256' + kid: string + typ: string +} + +export type RequiredClaims = { + iss: string + sub: string + aud: string | string[] + exp: number + iat: number + role: string + aal: AuthenticatorAssuranceLevels + session_id: string +} + +/** + * JWT Payload containing claims for Supabase authentication tokens. + * + * Required claims (iss, aud, exp, iat, sub, role, aal, session_id) are inherited from RequiredClaims. + * All other claims are optional as they can be customized via Custom Access Token Hooks. + * + * @see https://supabase.com/docs/guides/auth/jwt-fields + */ +export interface JwtPayload extends RequiredClaims { + // Standard optional claims (can be customized via custom access token hooks) + email?: string + phone?: string + is_anonymous?: boolean + + // Optional claims + jti?: string + nbf?: number + app_metadata?: UserAppMetadata + user_metadata?: UserMetadata + amr?: AMREntry[] + + // Special claims (only in anon/service role tokens) + ref?: string + + // Allow custom claims via custom access token hooks + [key: string]: any +} + +export interface JWK { + kty: 'RSA' | 'EC' | 'oct' + key_ops: string[] + alg?: string + kid?: string + [key: string]: any +} + +export const SIGN_OUT_SCOPES = ['global', 'local', 'others'] as const +export type SignOutScope = (typeof SIGN_OUT_SCOPES)[number] + +/** + * OAuth client grant types supported by the OAuth 2.1 server. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type OAuthClientGrantType = 'authorization_code' | 'refresh_token' + +/** + * OAuth client response types supported by the OAuth 2.1 server. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type OAuthClientResponseType = 'code' + +/** + * OAuth client type indicating whether the client can keep credentials confidential. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type OAuthClientType = 'public' | 'confidential' + +/** + * OAuth client registration type. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type OAuthClientRegistrationType = 'dynamic' | 'manual' + +/** + * OAuth client object returned from the OAuth 2.1 server. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type OAuthClient = { + /** Unique identifier for the OAuth client */ + client_id: string + /** Human-readable name of the OAuth client */ + client_name: string + /** Client secret (only returned on registration and regeneration) */ + client_secret?: string + /** Type of OAuth client */ + client_type: OAuthClientType + /** Token endpoint authentication method */ + token_endpoint_auth_method: string + /** Registration type of the client */ + registration_type: OAuthClientRegistrationType + /** URI of the OAuth client */ + client_uri?: string + /** URI of the OAuth client's logo */ + logo_uri?: string + /** Array of allowed redirect URIs */ + redirect_uris: string[] + /** Array of allowed grant types */ + grant_types: OAuthClientGrantType[] + /** Array of allowed response types */ + response_types: OAuthClientResponseType[] + /** Scope of the OAuth client */ + scope?: string + /** Timestamp when the client was created */ + created_at: string + /** Timestamp when the client was last updated */ + updated_at: string +} + +/** + * Parameters for creating a new OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type CreateOAuthClientParams = { + /** Human-readable name of the OAuth client */ + client_name: string + /** URI of the OAuth client */ + client_uri?: string + /** Array of allowed redirect URIs */ + redirect_uris: string[] + /** Array of allowed grant types (optional, defaults to authorization_code and refresh_token) */ + grant_types?: OAuthClientGrantType[] + /** Array of allowed response types (optional, defaults to code) */ + response_types?: OAuthClientResponseType[] + /** Scope of the OAuth client */ + scope?: string +} + +/** + * Parameters for updating an existing OAuth client. + * All fields are optional. Only provided fields will be updated. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type UpdateOAuthClientParams = { + /** Human-readable name of the OAuth client */ + client_name?: string + /** URI of the OAuth client */ + client_uri?: string + /** URI of the OAuth client's logo */ + logo_uri?: string + /** Array of allowed redirect URIs */ + redirect_uris?: string[] + /** Array of allowed grant types */ + grant_types?: OAuthClientGrantType[] +} + +/** + * Response type for OAuth client operations. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type OAuthClientResponse = RequestResult + +/** + * Response type for listing OAuth clients. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type OAuthClientListResponse = + | { + data: { clients: OAuthClient[]; aud: string } & Pagination + error: null + } + | { + data: { clients: [] } + error: AuthError + } + +/** + * Contains all OAuth client administration methods. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export interface GoTrueAdminOAuthApi { + /** + * Lists all OAuth clients with optional pagination. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + listClients(params?: PageParams): Promise + + /** + * Creates a new OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + createClient(params: CreateOAuthClientParams): Promise + + /** + * Gets details of a specific OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + getClient(clientId: string): Promise + + /** + * Updates an existing OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + updateClient(clientId: string, params: UpdateOAuthClientParams): Promise + + /** + * Deletes an OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + deleteClient(clientId: string): Promise<{ data: null; error: AuthError | null }> + + /** + * Regenerates the secret for an OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + regenerateClientSecret(clientId: string): Promise +} + +/** + * OAuth client details in an authorization request. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type OAuthAuthorizationClient = { + /** Unique identifier for the OAuth client (UUID) */ + id: string + /** Human-readable name of the OAuth client */ + name: string + /** URI of the OAuth client's website */ + uri: string + /** URI of the OAuth client's logo */ + logo_uri: string +} + +/** + * OAuth authorization details for the consent flow. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type OAuthAuthorizationDetails = { + /** The authorization ID */ + authorization_id: string + /** Redirect URL - present if user already consented (can be used to trigger immediate redirect) */ + redirect_url?: string + /** OAuth client requesting authorization */ + client: OAuthAuthorizationClient + /** User object associated with the authorization */ + user: { + /** User ID (UUID) */ + id: string + /** User email */ + email: string + } + /** Space-separated list of requested scopes */ + scope: string +} + +/** + * Response type for getting OAuth authorization details. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type AuthOAuthAuthorizationDetailsResponse = RequestResult + +/** + * Response type for OAuth consent decision (approve/deny). + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type AuthOAuthConsentResponse = RequestResult<{ + /** URL to redirect the user back to the OAuth client */ + redirect_url: string +}> + +/** + * An OAuth grant representing a user's authorization of an OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type OAuthGrant = { + /** OAuth client information */ + client: OAuthAuthorizationClient + /** Array of scopes granted to this client */ + scopes: string[] + /** Timestamp when the grant was created (ISO 8601 date-time) */ + granted_at: string +} + +/** + * Response type for listing user's OAuth grants. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type AuthOAuthGrantsResponse = RequestResult + +/** + * Response type for revoking an OAuth grant. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ +export type AuthOAuthRevokeGrantResponse = RequestResult<{}> + +/** + * Contains all OAuth 2.1 authorization server user-facing methods. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * These methods are used to implement the consent page. + */ +export interface AuthOAuthServerApi { + /** + * Retrieves details about an OAuth authorization request. + * Used to display consent information to the user. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This method returns authorization details including client info, scopes, and user information. + * If the response includes a redirect_uri, it means consent was already given - the caller + * should handle the redirect manually if needed. + * + * @param authorizationId - The authorization ID from the authorization request + * @returns Authorization details including client info and requested scopes + */ + getAuthorizationDetails(authorizationId: string): Promise + + /** + * Approves an OAuth authorization request. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * @param authorizationId - The authorization ID to approve + * @param options - Optional parameters including skipBrowserRedirect + * @returns Redirect URL to send the user back to the OAuth client + */ + approveAuthorization( + authorizationId: string, + options?: { skipBrowserRedirect?: boolean } + ): Promise + + /** + * Denies an OAuth authorization request. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * @param authorizationId - The authorization ID to deny + * @param options - Optional parameters including skipBrowserRedirect + * @returns Redirect URL to send the user back to the OAuth client + */ + denyAuthorization( + authorizationId: string, + options?: { skipBrowserRedirect?: boolean } + ): Promise + + /** + * Lists all OAuth grants that the authenticated user has authorized. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * @returns Response with array of OAuth grants with client information and granted scopes + */ + listGrants(): Promise + + /** + * Revokes a user's OAuth grant for a specific client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * Revocation marks consent as revoked, deletes active sessions for that OAuth client, + * and invalidates associated refresh tokens. + * + * @param options - Revocation options + * @param options.clientId - The OAuth client identifier (UUID) to revoke access for + * @returns Empty response on successful revocation + */ + revokeGrant(options: { clientId: string }): Promise +} diff --git a/backend/node_modules/@supabase/auth-js/src/lib/version.ts b/backend/node_modules/@supabase/auth-js/src/lib/version.ts new file mode 100644 index 0000000..57a6913 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/src/lib/version.ts @@ -0,0 +1,7 @@ +// Generated automatically during releases by scripts/update-version-files.ts +// This file provides runtime access to the package version for: +// - HTTP request headers (e.g., X-Client-Info header for API requests) +// - Debugging and support (identifying which version is running) +// - Telemetry and logging (version reporting in errors/analytics) +// - Ensuring build artifacts match the published package version +export const version = '2.87.1' diff --git a/backend/node_modules/@supabase/auth-js/src/lib/web3/ethereum.ts b/backend/node_modules/@supabase/auth-js/src/lib/web3/ethereum.ts new file mode 100644 index 0000000..053e41f --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/src/lib/web3/ethereum.ts @@ -0,0 +1,184 @@ +// types and functions copied over from viem so this library doesn't depend on it + +export type Hex = `0x${string}` + +export type Address = Hex + +export type EIP1193EventMap = { + accountsChanged(accounts: Address[]): void + chainChanged(chainId: string): void + connect(connectInfo: { chainId: string }): void + disconnect(error: { code: number; message: string }): void + message(message: { type: string; data: unknown }): void +} + +export type EIP1193Events = { + on(event: event, listener: EIP1193EventMap[event]): void + removeListener( + event: event, + listener: EIP1193EventMap[event] + ): void +} + +export type EIP1193RequestFn = (args: { method: string; params?: unknown }) => Promise + +export type EIP1193Provider = EIP1193Events & { + address: string + request: EIP1193RequestFn +} + +export type EthereumWallet = EIP1193Provider + +/** + * EIP-4361 message fields + */ +export type SiweMessage = { + /** + * The Ethereum address performing the signing. + */ + address: Address + /** + * The [EIP-155](https://eips.ethereum.org/EIPS/eip-155) Chain ID to which the session is bound, + */ + chainId: number + /** + * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) authority that is requesting the signing. + */ + domain: string + /** + * Time when the signed authentication message is no longer valid. + */ + expirationTime?: Date | undefined + /** + * Time when the message was generated, typically the current time. + */ + issuedAt?: Date | undefined + /** + * A random string typically chosen by the relying party and used to prevent replay attacks. + */ + nonce?: string + /** + * Time when the signed authentication message will become valid. + */ + notBefore?: Date | undefined + /** + * A system-specific identifier that may be used to uniquely refer to the sign-in request. + */ + requestId?: string | undefined + /** + * A list of information or references to information the user wishes to have resolved as part of authentication by the relying party. + */ + resources?: string[] | undefined + /** + * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) URI scheme of the origin of the request. + */ + scheme?: string | undefined + /** + * A human-readable ASCII assertion that the user will sign. + */ + statement?: string | undefined + /** + * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) URI referring to the resource that is the subject of the signing (as in the subject of a claim). + */ + uri: string + /** + * The current version of the SIWE Message. + */ + version: '1' +} + +export type EthereumSignInInput = SiweMessage + +export function getAddress(address: string): Address { + if (!/^0x[a-fA-F0-9]{40}$/.test(address)) { + throw new Error(`@supabase/auth-js: Address "${address}" is invalid.`) + } + return address.toLowerCase() as Address +} + +export function fromHex(hex: Hex): number { + return parseInt(hex, 16) +} + +export function toHex(value: string): Hex { + const bytes = new TextEncoder().encode(value) + const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('') + return ('0x' + hex) as Hex +} + +/** + * Creates EIP-4361 formatted message. + */ +export function createSiweMessage(parameters: SiweMessage): string { + const { + chainId, + domain, + expirationTime, + issuedAt = new Date(), + nonce, + notBefore, + requestId, + resources, + scheme, + uri, + version, + } = parameters + + // Validate fields + { + if (!Number.isInteger(chainId)) + throw new Error( + `@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${chainId}` + ) + + if (!domain) + throw new Error( + `@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.` + ) + + if (nonce && nonce.length < 8) + throw new Error( + `@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${nonce}` + ) + + if (!uri) + throw new Error(`@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.`) + + if (version !== '1') + throw new Error( + `@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${version}` + ) + + if (parameters.statement?.includes('\n')) + throw new Error( + `@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${parameters.statement}` + ) + } + + // Construct message + const address = getAddress(parameters.address) + const origin = scheme ? `${scheme}://${domain}` : domain + const statement = parameters.statement ? `${parameters.statement}\n` : '' + const prefix = `${origin} wants you to sign in with your Ethereum account:\n${address}\n\n${statement}` + + let suffix = `URI: ${uri}\nVersion: ${version}\nChain ID: ${chainId}${ + nonce ? `\nNonce: ${nonce}` : '' + }\nIssued At: ${issuedAt.toISOString()}` + + if (expirationTime) suffix += `\nExpiration Time: ${expirationTime.toISOString()}` + if (notBefore) suffix += `\nNot Before: ${notBefore.toISOString()}` + if (requestId) suffix += `\nRequest ID: ${requestId}` + if (resources) { + let content = '\nResources:' + for (const resource of resources) { + if (!resource || typeof resource !== 'string') + throw new Error( + `@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${resource}` + ) + content += `\n- ${resource}` + } + suffix += content + } + + return `${prefix}\n${suffix}` +} diff --git a/backend/node_modules/@supabase/auth-js/src/lib/web3/solana.ts b/backend/node_modules/@supabase/auth-js/src/lib/web3/solana.ts new file mode 100644 index 0000000..f6fbe87 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/src/lib/web3/solana.ts @@ -0,0 +1,186 @@ +// types copied over from @solana/wallet-standard-features and @wallet-standard/base so this library doesn't depend on them + +/** + * A namespaced identifier in the format `${namespace}:${reference}`. + * + * Used by {@link IdentifierArray} and {@link IdentifierRecord}. + * + * @group Identifier + */ +export type IdentifierString = `${string}:${string}` + +/** + * A read-only array of namespaced identifiers in the format `${namespace}:${reference}`. + * + * Used by {@link Wallet.chains | Wallet::chains}, {@link WalletAccount.chains | WalletAccount::chains}, and + * {@link WalletAccount.features | WalletAccount::features}. + * + * @group Identifier + */ +export type IdentifierArray = readonly IdentifierString[] + +/** + * Version of the Wallet Standard implemented by a {@link Wallet}. + * + * Used by {@link Wallet.version | Wallet::version}. + * + * Note that this is _NOT_ a version of the Wallet, but a version of the Wallet Standard itself that the Wallet + * supports. + * + * This may be used by the app to determine compatibility and feature detect. + * + * @group Wallet + */ +export type WalletVersion = '1.0.0' + +/** + * A data URI containing a base64-encoded SVG, WebP, PNG, or GIF image. + * + * Used by {@link Wallet.icon | Wallet::icon} and {@link WalletAccount.icon | WalletAccount::icon}. + * + * @group Wallet + */ +export type WalletIcon = `data:image/${'svg+xml' | 'webp' | 'png' | 'gif'};base64,${string}` + +/** + * Interface of a **WalletAccount**, also referred to as an **Account**. + * + * An account is a _read-only data object_ that is provided from the Wallet to the app, authorizing the app to use it. + * + * The app can use an account to display and query information from a chain. + * + * The app can also act using an account by passing it to {@link Wallet.features | features} of the Wallet. + * + * Wallets may use or extend {@link "@wallet-standard/wallet".ReadonlyWalletAccount} which implements this interface. + * + * @group Wallet + */ +export interface WalletAccount { + /** Address of the account, corresponding with a public key. */ + readonly address: string + + /** Public key of the account, corresponding with a secret key to use. */ + readonly publicKey: Uint8Array + + /** + * Chains supported by the account. + * + * This must be a subset of the {@link Wallet.chains | chains} of the Wallet. + */ + readonly chains: IdentifierArray + + /** + * Feature names supported by the account. + * + * This must be a subset of the names of {@link Wallet.features | features} of the Wallet. + */ + readonly features: IdentifierArray + + /** Optional user-friendly descriptive label or name for the account. This may be displayed by the app. */ + readonly label?: string + + /** Optional user-friendly icon for the account. This may be displayed by the app. */ + readonly icon?: WalletIcon +} + +/** Input for signing in. */ +export interface SolanaSignInInput { + /** + * Optional EIP-4361 Domain. + * If not provided, the wallet must determine the Domain to include in the message. + */ + readonly domain?: string + + /** + * Optional EIP-4361 Address. + * If not provided, the wallet must determine the Address to include in the message. + */ + readonly address?: string + + /** + * Optional EIP-4361 Statement. + * If not provided, the wallet must not include Statement in the message. + */ + readonly statement?: string + + /** + * Optional EIP-4361 URI. + * If not provided, the wallet must not include URI in the message. + */ + readonly uri?: string + + /** + * Optional EIP-4361 Version. + * If not provided, the wallet must not include Version in the message. + */ + readonly version?: string + + /** + * Optional EIP-4361 Chain ID. + * If not provided, the wallet must not include Chain ID in the message. + */ + readonly chainId?: string + + /** + * Optional EIP-4361 Nonce. + * If not provided, the wallet must not include Nonce in the message. + */ + readonly nonce?: string + + /** + * Optional EIP-4361 Issued At. + * If not provided, the wallet must not include Issued At in the message. + */ + readonly issuedAt?: string + + /** + * Optional EIP-4361 Expiration Time. + * If not provided, the wallet must not include Expiration Time in the message. + */ + readonly expirationTime?: string + + /** + * Optional EIP-4361 Not Before. + * If not provided, the wallet must not include Not Before in the message. + */ + readonly notBefore?: string + + /** + * Optional EIP-4361 Request ID. + * If not provided, the wallet must not include Request ID in the message. + */ + readonly requestId?: string + + /** + * Optional EIP-4361 Resources. + * If not provided, the wallet must not include Resources in the message. + */ + readonly resources?: readonly string[] +} + +/** Output of signing in. */ +export interface SolanaSignInOutput { + /** + * Account that was signed in. + * The address of the account may be different from the provided input Address. + */ + readonly account: WalletAccount + + /** + * Message bytes that were signed. + * The wallet may prefix or otherwise modify the message before signing it. + */ + readonly signedMessage: Uint8Array + + /** + * Message signature produced. + * If the signature type is provided, the signature must be Ed25519. + */ + readonly signature: Uint8Array + + /** + * Optional type of the message signature produced. + * If not provided, the signature must be Ed25519. + */ + readonly signatureType?: 'ed25519' +} diff --git a/backend/node_modules/@supabase/auth-js/src/lib/webauthn.dom.ts b/backend/node_modules/@supabase/auth-js/src/lib/webauthn.dom.ts new file mode 100644 index 0000000..7502347 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/src/lib/webauthn.dom.ts @@ -0,0 +1,636 @@ +// from https://github.com/MasterKale/SimpleWebAuthn/blob/master/packages/browser/src/types/index.ts + +import { StrictOmit } from './types' + +/** + * A variant of PublicKeyCredentialCreationOptions suitable for JSON transmission to the browser to + * (eventually) get passed into navigator.credentials.create(...) in the browser. + * + * This should eventually get replaced with official TypeScript DOM types when WebAuthn Level 3 types + * eventually make it into the language: + * + * @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialcreationoptionsjson W3C WebAuthn Spec - PublicKeyCredentialCreationOptionsJSON} + */ +export interface PublicKeyCredentialCreationOptionsJSON { + /** + * Information about the Relying Party responsible for the request. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-rp W3C - rp} + */ + rp: PublicKeyCredentialRpEntity + /** + * Information about the user account for which the credential is being created. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-user W3C - user} + */ + user: PublicKeyCredentialUserEntityJSON + /** + * A server-generated challenge in base64url format. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-challenge W3C - challenge} + */ + challenge: Base64URLString + /** + * Information about desired properties of the credential to be created. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-pubkeycredparams W3C - pubKeyCredParams} + */ + pubKeyCredParams: PublicKeyCredentialParameters[] + /** + * Time in milliseconds that the caller is willing to wait for the operation to complete. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-timeout W3C - timeout} + */ + timeout?: number + /** + * Credentials that the authenticator should not create a new credential for. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-excludecredentials W3C - excludeCredentials} + */ + excludeCredentials?: PublicKeyCredentialDescriptorJSON[] + /** + * Criteria for authenticator selection. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-authenticatorselection W3C - authenticatorSelection} + */ + authenticatorSelection?: AuthenticatorSelectionCriteria + /** + * Hints about what types of authenticators the user might want to use. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-hints W3C - hints} + */ + hints?: PublicKeyCredentialHint[] + /** + * How the attestation statement should be transported. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-attestation W3C - attestation} + */ + attestation?: AttestationConveyancePreference + /** + * The attestation statement formats that the Relying Party will accept. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-attestationformats W3C - attestationFormats} + */ + attestationFormats?: AttestationFormat[] + /** + * Additional parameters requesting additional processing by the client and authenticator. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-extensions W3C - extensions} + */ + extensions?: AuthenticationExtensionsClientInputs +} + +/** + * A variant of PublicKeyCredentialRequestOptions suitable for JSON transmission to the browser to + * (eventually) get passed into navigator.credentials.get(...) in the browser. + * + * @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialrequestoptionsjson W3C WebAuthn Spec - PublicKeyCredentialRequestOptionsJSON} + */ +export interface PublicKeyCredentialRequestOptionsJSON { + /** + * A server-generated challenge in base64url format. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialrequestoptions-challenge W3C - challenge} + */ + challenge: Base64URLString + /** + * Time in milliseconds that the caller is willing to wait for the operation to complete. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialrequestoptions-timeout W3C - timeout} + */ + timeout?: number + /** + * The relying party identifier claimed by the caller. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialrequestoptions-rpid W3C - rpId} + */ + rpId?: string + /** + * A list of credentials acceptable for authentication. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialrequestoptions-allowcredentials W3C - allowCredentials} + */ + allowCredentials?: PublicKeyCredentialDescriptorJSON[] + /** + * Whether user verification should be performed by the authenticator. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialrequestoptions-userverification W3C - userVerification} + */ + userVerification?: UserVerificationRequirement + /** + * Hints about what types of authenticators the user might want to use. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialrequestoptions-hints W3C - hints} + */ + hints?: PublicKeyCredentialHint[] + /** + * Additional parameters requesting additional processing by the client and authenticator. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialrequestoptions-extensions W3C - extensions} + */ + extensions?: AuthenticationExtensionsClientInputs +} + +/** + * Represents a public key credential descriptor in JSON format. + * Used to identify credentials for exclusion or allowance during WebAuthn ceremonies. + * + * @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialdescriptorjson W3C WebAuthn Spec - PublicKeyCredentialDescriptorJSON} + */ +export interface PublicKeyCredentialDescriptorJSON { + /** + * The credential ID in base64url format. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialdescriptor-id W3C - id} + */ + id: Base64URLString + /** + * The type of the public key credential (always "public-key"). + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialdescriptor-type W3C - type} + */ + type: PublicKeyCredentialType + /** + * How the authenticator communicates with clients. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialdescriptor-transports W3C - transports} + */ + transports?: AuthenticatorTransportFuture[] +} + +/** + * Represents user account information in JSON format for WebAuthn registration. + * Contains identifiers and display information for the user being registered. + * + * @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialuserentityjson W3C WebAuthn Spec - PublicKeyCredentialUserEntityJSON} + */ +export interface PublicKeyCredentialUserEntityJSON { + /** + * A unique identifier for the user account (base64url encoded). + * Maximum 64 bytes. Should not contain PII. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialuserentity-id W3C - user.id} + */ + id: string + /** + * A human-readable identifier for the account (e.g., email, username). + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialentity-name W3C - user.name} + */ + name: string + /** + * A human-friendly display name for the user (e.g., "John Doe"). + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialuserentity-displayname W3C - user.displayName} + */ + displayName: string +} + +/** + * Represents user account information for WebAuthn registration with binary data. + * Contains identifiers and display information for the user being registered. + * + * @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialuserentity W3C WebAuthn Spec - PublicKeyCredentialUserEntity} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialUserEntity MDN - PublicKeyCredentialUserEntity} + */ +export interface PublicKeyCredentialUserEntity { + /** + * A unique identifier for the user account. + * Maximum 64 bytes. Should not contain PII. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialuserentity-id W3C - user.id} + */ + id: BufferSource // ArrayBuffer | TypedArray | DataView + + /** + * A human-readable identifier for the account. + * Typically an email, username, or phone number. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialentity-name W3C - user.name} + */ + name: string + + /** + * A human-friendly display name for the user. + * Example: "John Doe" + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialuserentity-displayname W3C - user.displayName} + */ + displayName: string +} + +/** + * The credential returned from navigator.credentials.create() during WebAuthn registration. + * Contains the new credential's public key and attestation information. + * + * @see {@link https://w3c.github.io/webauthn/#registrationceremony W3C WebAuthn Spec - Registration} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredential MDN - PublicKeyCredential} + */ +export interface RegistrationCredential + extends PublicKeyCredentialFuture { + response: AuthenticatorAttestationResponseFuture +} + +/** + * A slightly-modified RegistrationCredential to simplify working with ArrayBuffers that + * are Base64URL-encoded in the browser so that they can be sent as JSON to the server. + * + * @see {@link https://w3c.github.io/webauthn/#dictdef-registrationresponsejson W3C WebAuthn Spec - RegistrationResponseJSON} + */ +export interface RegistrationResponseJSON { + /** + * The credential ID (same as rawId for JSON). + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-id W3C - id} + */ + id: Base64URLString + /** + * The raw credential ID in base64url format. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-rawid W3C - rawId} + */ + rawId: Base64URLString + /** + * The authenticator's response to the client's request to create a credential. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-response W3C - response} + */ + response: AuthenticatorAttestationResponseJSON + /** + * The authenticator attachment modality in effect at the time of credential creation. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-authenticatorattachment W3C - authenticatorAttachment} + */ + authenticatorAttachment?: AuthenticatorAttachment + /** + * The results of processing client extensions. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-getclientextensionresults W3C - getClientExtensionResults} + */ + clientExtensionResults: AuthenticationExtensionsClientOutputs + /** + * The type of the credential (always "public-key"). + * @see {@link https://w3c.github.io/webauthn/#dom-credential-type W3C - type} + */ + type: PublicKeyCredentialType +} + +/** + * The credential returned from navigator.credentials.get() during WebAuthn authentication. + * Contains the assertion signature proving possession of the private key. + * + * @see {@link https://w3c.github.io/webauthn/#authentication W3C WebAuthn Spec - Authentication} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredential MDN - PublicKeyCredential} + */ +export interface AuthenticationCredential + extends PublicKeyCredentialFuture { + response: AuthenticatorAssertionResponse +} + +/** + * A slightly-modified AuthenticationCredential to simplify working with ArrayBuffers that + * are Base64URL-encoded in the browser so that they can be sent as JSON to the server. + * + * @see {@link https://w3c.github.io/webauthn/#dictdef-authenticationresponsejson W3C WebAuthn Spec - AuthenticationResponseJSON} + */ +export interface AuthenticationResponseJSON { + /** + * The credential ID (same as rawId for JSON). + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-id W3C - id} + */ + id: Base64URLString + /** + * The raw credential ID in base64url format. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-rawid W3C - rawId} + */ + rawId: Base64URLString + /** + * The authenticator's response to the client's request to authenticate. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-response W3C - response} + */ + response: AuthenticatorAssertionResponseJSON + /** + * The authenticator attachment modality in effect at the time of authentication. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-authenticatorattachment W3C - authenticatorAttachment} + */ + authenticatorAttachment?: AuthenticatorAttachment + /** + * The results of processing client extensions. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-getclientextensionresults W3C - getClientExtensionResults} + */ + clientExtensionResults: AuthenticationExtensionsClientOutputs + /** + * The type of the credential (always "public-key"). + * @see {@link https://w3c.github.io/webauthn/#dom-credential-type W3C - type} + */ + type: PublicKeyCredentialType +} + +/** + * A slightly-modified AuthenticatorAttestationResponse to simplify working with ArrayBuffers that + * are Base64URL-encoded in the browser so that they can be sent as JSON to the server. + * + * @see {@link https://w3c.github.io/webauthn/#dictdef-authenticatorattestationresponsejson W3C WebAuthn Spec - AuthenticatorAttestationResponseJSON} + */ +export interface AuthenticatorAttestationResponseJSON { + /** + * JSON-serialized client data passed to the authenticator. + * @see {@link https://w3c.github.io/webauthn/#dom-authenticatorresponse-clientdatajson W3C - clientDataJSON} + */ + clientDataJSON: Base64URLString + /** + * The attestation object in base64url format. + * @see {@link https://w3c.github.io/webauthn/#dom-authenticatorattestationresponse-attestationobject W3C - attestationObject} + */ + attestationObject: Base64URLString + /** + * The authenticator data contained within the attestation object. + * Optional in L2, but becomes required in L3. Play it safe until L3 becomes Recommendation + * @see {@link https://w3c.github.io/webauthn/#dom-authenticatorattestationresponse-getauthenticatordata W3C - getAuthenticatorData} + */ + authenticatorData?: Base64URLString + /** + * The transports that the authenticator supports. + * Optional in L2, but becomes required in L3. Play it safe until L3 becomes Recommendation + * @see {@link https://w3c.github.io/webauthn/#dom-authenticatorattestationresponse-gettransports W3C - getTransports} + */ + transports?: AuthenticatorTransportFuture[] + /** + * The COSEAlgorithmIdentifier for the public key. + * Optional in L2, but becomes required in L3. Play it safe until L3 becomes Recommendation + * @see {@link https://w3c.github.io/webauthn/#dom-authenticatorattestationresponse-getpublickeyalgorithm W3C - getPublicKeyAlgorithm} + */ + publicKeyAlgorithm?: COSEAlgorithmIdentifier + /** + * The public key in base64url format. + * @see {@link https://w3c.github.io/webauthn/#dom-authenticatorattestationresponse-getpublickey W3C - getPublicKey} + */ + publicKey?: Base64URLString +} + +/** + * A slightly-modified AuthenticatorAssertionResponse to simplify working with ArrayBuffers that + * are Base64URL-encoded in the browser so that they can be sent as JSON to the server. + * + * @see {@link https://w3c.github.io/webauthn/#dictdef-authenticatorassertionresponsejson W3C WebAuthn Spec - AuthenticatorAssertionResponseJSON} + */ +export interface AuthenticatorAssertionResponseJSON { + /** + * JSON-serialized client data passed to the authenticator. + * @see {@link https://w3c.github.io/webauthn/#dom-authenticatorresponse-clientdatajson W3C - clientDataJSON} + */ + clientDataJSON: Base64URLString + /** + * The authenticator data returned by the authenticator. + * @see {@link https://w3c.github.io/webauthn/#dom-authenticatorassertionresponse-authenticatordata W3C - authenticatorData} + */ + authenticatorData: Base64URLString + /** + * The signature generated by the authenticator. + * @see {@link https://w3c.github.io/webauthn/#dom-authenticatorassertionresponse-signature W3C - signature} + */ + signature: Base64URLString + /** + * The user handle returned by the authenticator, if any. + * @see {@link https://w3c.github.io/webauthn/#dom-authenticatorassertionresponse-userhandle W3C - userHandle} + */ + userHandle?: Base64URLString +} + +/** + * Public key credential information needed to verify authentication responses. + * Stores the credential's public key and metadata for server-side verification. + * + * @see {@link https://w3c.github.io/webauthn/#sctn-credential-storage-modality W3C WebAuthn Spec - Credential Storage} + */ +export type WebAuthnCredential = { + /** + * The credential ID in base64url format. + * @see {@link https://w3c.github.io/webauthn/#credential-id W3C - Credential ID} + */ + id: Base64URLString + /** + * The credential's public key. + * @see {@link https://w3c.github.io/webauthn/#credential-public-key W3C - Credential Public Key} + */ + publicKey: Uint8Array_ + /** + * Number of times this authenticator is expected to have been used. + * @see {@link https://w3c.github.io/webauthn/#signature-counter W3C - Signature Counter} + */ + counter: number + /** + * The transports that the authenticator supports. + * From browser's `startRegistration()` -> RegistrationCredentialJSON.transports (API L2 and up) + * @see {@link https://w3c.github.io/webauthn/#dom-authenticatorattestationresponse-gettransports W3C - getTransports} + */ + transports?: AuthenticatorTransportFuture[] +} + +/** + * An attempt to communicate that this isn't just any string, but a Base64URL-encoded string. + * Base64URL encoding is used throughout WebAuthn for binary data transmission. + * + * @see {@link https://datatracker.ietf.org/doc/html/rfc4648#section-5 RFC 4648 - Base64URL Encoding} + */ +export type Base64URLString = string + +/** + * AuthenticatorAttestationResponse in TypeScript's DOM lib is outdated (up through v3.9.7). + * Maintain an augmented version here so we can implement additional properties as the WebAuthn + * spec evolves. + * + * Properties marked optional are not supported in all browsers. + * + * @see {@link https://www.w3.org/TR/webauthn-2/#iface-authenticatorattestationresponse W3C WebAuthn Spec - AuthenticatorAttestationResponse} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AuthenticatorAttestationResponse MDN - AuthenticatorAttestationResponse} + */ +export interface AuthenticatorAttestationResponseFuture extends AuthenticatorAttestationResponse { + /** + * Returns the transports that the authenticator supports. + * @see {@link https://w3c.github.io/webauthn/#dom-authenticatorattestationresponse-gettransports W3C - getTransports} + */ + getTransports(): AuthenticatorTransportFuture[] +} + +/** + * A super class of TypeScript's `AuthenticatorTransport` that includes support for the latest + * transports. Should eventually be replaced by TypeScript's when TypeScript gets updated to + * know about it (sometime after 4.6.3) + * + * @see {@link https://w3c.github.io/webauthn/#enum-transport W3C WebAuthn Spec - AuthenticatorTransport} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AuthenticatorAttestationResponse/getTransports MDN - getTransports} + */ +export type AuthenticatorTransportFuture = + | 'ble' + | 'cable' + | 'hybrid' + | 'internal' + | 'nfc' + | 'smart-card' + | 'usb' + +/** + * A super class of TypeScript's `PublicKeyCredentialDescriptor` that knows about the latest + * transports. Should eventually be replaced by TypeScript's when TypeScript gets updated to + * know about it (sometime after 4.6.3) + * + * @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialdescriptor W3C WebAuthn Spec - PublicKeyCredentialDescriptor} + */ +export interface PublicKeyCredentialDescriptorFuture + extends Omit { + /** + * How the authenticator communicates with clients. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialdescriptor-transports W3C - transports} + */ + transports?: AuthenticatorTransportFuture[] +} + +/** + * Enhanced PublicKeyCredentialCreationOptions that knows about the latest features. + * Used for WebAuthn registration ceremonies. + * + * @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialcreationoptions W3C WebAuthn Spec - PublicKeyCredentialCreationOptions} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions MDN - PublicKeyCredentialCreationOptions} + */ +export interface PublicKeyCredentialCreationOptionsFuture + extends StrictOmit { + /** + * Credentials that the authenticator should not create a new credential for. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-excludecredentials W3C - excludeCredentials} + */ + excludeCredentials?: PublicKeyCredentialDescriptorFuture[] + /** + * Information about the user account for which the credential is being created. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-user W3C - user} + */ + user: PublicKeyCredentialUserEntity + /** + * Hints about what types of authenticators the user might want to use. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-hints W3C - hints} + */ + hints?: PublicKeyCredentialHint[] + /** + * Criteria for authenticator selection. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-authenticatorselection W3C - authenticatorSelection} + */ + authenticatorSelection?: AuthenticatorSelectionCriteria + /** + * Information about desired properties of the credential to be created. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-pubkeycredparams W3C - pubKeyCredParams} + */ + pubKeyCredParams: PublicKeyCredentialParameters[] + /** + * Information about the Relying Party responsible for the request. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-rp W3C - rp} + */ + rp: PublicKeyCredentialRpEntity +} + +/** + * Enhanced PublicKeyCredentialRequestOptions that knows about the latest features. + * Used for WebAuthn authentication ceremonies. + * + * @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialrequestoptions W3C WebAuthn Spec - PublicKeyCredentialRequestOptions} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialRequestOptions MDN - PublicKeyCredentialRequestOptions} + */ +export interface PublicKeyCredentialRequestOptionsFuture + extends StrictOmit { + /** + * A list of credentials acceptable for authentication. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialrequestoptions-allowcredentials W3C - allowCredentials} + */ + allowCredentials?: PublicKeyCredentialDescriptorFuture[] + /** + * Hints about what types of authenticators the user might want to use. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialrequestoptions-hints W3C - hints} + */ + hints?: PublicKeyCredentialHint[] + /** + * The attestation conveyance preference for the authentication ceremony. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-attestation W3C - attestation} + */ + attestation?: AttestationConveyancePreference +} + +/** + * Union type for all WebAuthn credential responses in JSON format. + * Can be either a registration response (for new credentials) or authentication response (for existing credentials). + */ +export type PublicKeyCredentialJSON = RegistrationResponseJSON | AuthenticationResponseJSON + +/** + * A super class of TypeScript's `PublicKeyCredential` that knows about upcoming WebAuthn features. + * Includes WebAuthn Level 3 methods for JSON serialization and parsing. + * + * @see {@link https://w3c.github.io/webauthn/#publickeycredential W3C WebAuthn Spec - PublicKeyCredential} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredential MDN - PublicKeyCredential} + */ +export interface PublicKeyCredentialFuture< + T extends PublicKeyCredentialJSON = PublicKeyCredentialJSON, +> extends PublicKeyCredential { + /** + * The type of the credential (always "public-key"). + * @see {@link https://w3c.github.io/webauthn/#dom-credential-type W3C - type} + */ + type: PublicKeyCredentialType + /** + * Checks if conditional mediation is available. + * @see {@link https://github.com/w3c/webauthn/issues/1745 GitHub - Conditional Mediation} + */ + isConditionalMediationAvailable?(): Promise + /** + * Parses JSON to create PublicKeyCredentialCreationOptions. + * @see {@link https://w3c.github.io/webauthn/#sctn-parseCreationOptionsFromJSON W3C - parseCreationOptionsFromJSON} + */ + parseCreationOptionsFromJSON( + options: PublicKeyCredentialCreationOptionsJSON + ): PublicKeyCredentialCreationOptionsFuture + /** + * Parses JSON to create PublicKeyCredentialRequestOptions. + * @see {@link https://w3c.github.io/webauthn/#sctn-parseRequestOptionsFromJSON W3C - parseRequestOptionsFromJSON} + */ + parseRequestOptionsFromJSON( + options: PublicKeyCredentialRequestOptionsJSON + ): PublicKeyCredentialRequestOptionsFuture + /** + * Serializes the credential to JSON format. + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-tojson W3C - toJSON} + */ + toJSON(): T +} + +/** + * The two types of credentials as defined by bit 3 ("Backup Eligibility") in authenticator data: + * - `"singleDevice"` credentials will never be backed up + * - `"multiDevice"` credentials can be backed up + * + * @see {@link https://w3c.github.io/webauthn/#sctn-authenticator-data W3C WebAuthn Spec - Authenticator Data} + */ +export type CredentialDeviceType = 'singleDevice' | 'multiDevice' + +/** + * Categories of authenticators that Relying Parties can pass along to browsers during + * registration. Browsers that understand these values can optimize their modal experience to + * start the user off in a particular registration flow: + * + * - `hybrid`: A platform authenticator on a mobile device + * - `security-key`: A portable FIDO2 authenticator capable of being used on multiple devices via a USB or NFC connection + * - `client-device`: The device that WebAuthn is being called on. Typically synonymous with platform authenticators + * + * These values are less strict than `authenticatorAttachment` + * + * @see {@link https://w3c.github.io/webauthn/#enumdef-publickeycredentialhint W3C WebAuthn Spec - PublicKeyCredentialHint} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions#hints MDN - hints} + */ +export type PublicKeyCredentialHint = 'hybrid' | 'security-key' | 'client-device' + +/** + * Values for an attestation object's `fmt`. + * Defines the format of the attestation statement from the authenticator. + * + * @see {@link https://www.iana.org/assignments/webauthn/webauthn.xhtml#webauthn-attestation-statement-format-ids IANA - WebAuthn Attestation Statement Format Identifiers} + * @see {@link https://w3c.github.io/webauthn/#sctn-attestation-formats W3C WebAuthn Spec - Attestation Statement Formats} + */ +export type AttestationFormat = + | 'fido-u2f' + | 'packed' + | 'android-safetynet' + | 'android-key' + | 'tpm' + | 'apple' + | 'none' + +/** + * Equivalent to `Uint8Array` before TypeScript 5.7, and `Uint8Array` in TypeScript 5.7 + * and beyond. + * + * **Context** + * + * `Uint8Array` became a generic type in TypeScript 5.7, requiring types defined simply as + * `Uint8Array` to be refactored to `Uint8Array` starting in Deno 2.2. `Uint8Array` is + * _not_ generic in Deno 2.1.x and earlier, though, so this type helps bridge this gap. + * + * Inspired by Deno's std library: + * + * https://github.com/denoland/std/blob/b5a5fe4f96b91c1fe8dba5cc0270092dd11d3287/bytes/_types.ts#L11 + */ +export type Uint8Array_ = ReturnType + +/** + * Specifies the preferred authenticator attachment modality. + * - `platform`: A platform authenticator attached to the client device (e.g., Touch ID, Windows Hello) + * - `cross-platform`: A roaming authenticator not attached to the client device (e.g., USB security key) + * + * @see {@link https://w3c.github.io/webauthn/#enum-attachment W3C WebAuthn Spec - AuthenticatorAttachment} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions/authenticatorSelection#authenticatorattachment MDN - authenticatorAttachment} + */ +export type AuthenticatorAttachment = 'cross-platform' | 'platform' diff --git a/backend/node_modules/@supabase/auth-js/src/lib/webauthn.errors.ts b/backend/node_modules/@supabase/auth-js/src/lib/webauthn.errors.ts new file mode 100644 index 0000000..2900eb8 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/src/lib/webauthn.errors.ts @@ -0,0 +1,317 @@ +/* eslint-disable @typescript-eslint/ban-ts-comment */ + +import { StrictOmit } from './types' +import { isValidDomain } from './webauthn' +import { + PublicKeyCredentialCreationOptionsFuture, + PublicKeyCredentialRequestOptionsFuture, +} from './webauthn.dom' + +/** + * A custom Error used to return a more nuanced error detailing _why_ one of the eight documented + * errors in the spec was raised after calling `navigator.credentials.create()` or + * `navigator.credentials.get()`: + * + * - `AbortError` + * - `ConstraintError` + * - `InvalidStateError` + * - `NotAllowedError` + * - `NotSupportedError` + * - `SecurityError` + * - `TypeError` + * - `UnknownError` + * + * Error messages were determined through investigation of the spec to determine under which + * scenarios a given error would be raised. + */ +export class WebAuthnError extends Error { + code: WebAuthnErrorCode + + protected __isWebAuthnError = true + + constructor({ + message, + code, + cause, + name, + }: { + message: string + code: WebAuthnErrorCode + cause?: Error | unknown + name?: string + }) { + // @ts-ignore: help Rollup understand that `cause` is okay to set + super(message, { cause }) + this.name = name ?? (cause instanceof Error ? cause.name : undefined) ?? 'Unknown Error' + this.code = code + } +} + +/** + * Error class for unknown WebAuthn errors. + * Wraps unexpected errors that don't match known WebAuthn error conditions. + */ +export class WebAuthnUnknownError extends WebAuthnError { + originalError: unknown + + constructor(message: string, originalError: unknown) { + super({ + code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY', + cause: originalError, + message, + }) + this.name = 'WebAuthnUnknownError' + this.originalError = originalError + } +} + +/** + * Type guard to check if an error is a WebAuthnError. + * @param {unknown} error - The error to check + * @returns {boolean} True if the error is a WebAuthnError + */ +export function isWebAuthnError(error: unknown): error is WebAuthnError { + return typeof error === 'object' && error !== null && '__isWebAuthnError' in error +} + +/** + * Error codes for WebAuthn operations. + * These codes provide specific information about why a WebAuthn ceremony failed. + * @see {@link https://w3c.github.io/webauthn/#sctn-defined-errors W3C WebAuthn Spec - Defined Errors} + */ +export type WebAuthnErrorCode = + | 'ERROR_CEREMONY_ABORTED' + | 'ERROR_INVALID_DOMAIN' + | 'ERROR_INVALID_RP_ID' + | 'ERROR_INVALID_USER_ID_LENGTH' + | 'ERROR_MALFORMED_PUBKEYCREDPARAMS' + | 'ERROR_AUTHENTICATOR_GENERAL_ERROR' + | 'ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT' + | 'ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT' + | 'ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED' + | 'ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG' + | 'ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE' + | 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY' + +/** + * Attempt to intuit _why_ an error was raised after calling `navigator.credentials.create()`. + * Maps browser errors to specific WebAuthn error codes for better debugging. + * @param {Object} params - Error identification parameters + * @param {Error} params.error - The error thrown by the browser + * @param {CredentialCreationOptions} params.options - The options passed to credentials.create() + * @returns {WebAuthnError} A WebAuthnError with a specific error code + * @see {@link https://w3c.github.io/webauthn/#sctn-createCredential W3C WebAuthn Spec - Create Credential} + */ +export function identifyRegistrationError({ + error, + options, +}: { + error: Error + options: StrictOmit & { + publicKey: PublicKeyCredentialCreationOptionsFuture + } +}): WebAuthnError { + const { publicKey } = options + + if (!publicKey) { + throw Error('options was missing required publicKey property') + } + + if (error.name === 'AbortError') { + if (options.signal instanceof AbortSignal) { + // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 16) + return new WebAuthnError({ + message: 'Registration ceremony was sent an abort signal', + code: 'ERROR_CEREMONY_ABORTED', + cause: error, + }) + } + } else if (error.name === 'ConstraintError') { + if (publicKey.authenticatorSelection?.requireResidentKey === true) { + // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 4) + return new WebAuthnError({ + message: + 'Discoverable credentials were required but no available authenticator supported it', + code: 'ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT', + cause: error, + }) + } else if ( + // @ts-ignore: `mediation` doesn't yet exist on CredentialCreationOptions but it's possible as of Sept 2024 + options.mediation === 'conditional' && + publicKey.authenticatorSelection?.userVerification === 'required' + ) { + // https://w3c.github.io/webauthn/#sctn-createCredential (Step 22.4) + return new WebAuthnError({ + message: + 'User verification was required during automatic registration but it could not be performed', + code: 'ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE', + cause: error, + }) + } else if (publicKey.authenticatorSelection?.userVerification === 'required') { + // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 5) + return new WebAuthnError({ + message: 'User verification was required but no available authenticator supported it', + code: 'ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT', + cause: error, + }) + } + } else if (error.name === 'InvalidStateError') { + // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 20) + // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 3) + return new WebAuthnError({ + message: 'The authenticator was previously registered', + code: 'ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED', + cause: error, + }) + } else if (error.name === 'NotAllowedError') { + /** + * Pass the error directly through. Platforms are overloading this error beyond what the spec + * defines and we don't want to overwrite potentially useful error messages. + */ + return new WebAuthnError({ + message: error.message, + code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY', + cause: error, + }) + } else if (error.name === 'NotSupportedError') { + const validPubKeyCredParams = publicKey.pubKeyCredParams.filter( + (param) => param.type === 'public-key' + ) + + if (validPubKeyCredParams.length === 0) { + // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 10) + return new WebAuthnError({ + message: 'No entry in pubKeyCredParams was of type "public-key"', + code: 'ERROR_MALFORMED_PUBKEYCREDPARAMS', + cause: error, + }) + } + + // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 2) + return new WebAuthnError({ + message: + 'No available authenticator supported any of the specified pubKeyCredParams algorithms', + code: 'ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG', + cause: error, + }) + } else if (error.name === 'SecurityError') { + const effectiveDomain = window.location.hostname + if (!isValidDomain(effectiveDomain)) { + // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 7) + return new WebAuthnError({ + message: `${window.location.hostname} is an invalid domain`, + code: 'ERROR_INVALID_DOMAIN', + cause: error, + }) + } else if (publicKey.rp.id !== effectiveDomain) { + // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 8) + return new WebAuthnError({ + message: `The RP ID "${publicKey.rp.id}" is invalid for this domain`, + code: 'ERROR_INVALID_RP_ID', + cause: error, + }) + } + } else if (error.name === 'TypeError') { + if (publicKey.user.id.byteLength < 1 || publicKey.user.id.byteLength > 64) { + // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 5) + return new WebAuthnError({ + message: 'User ID was not between 1 and 64 characters', + code: 'ERROR_INVALID_USER_ID_LENGTH', + cause: error, + }) + } + } else if (error.name === 'UnknownError') { + // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 1) + // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 8) + return new WebAuthnError({ + message: + 'The authenticator was unable to process the specified options, or could not create a new credential', + code: 'ERROR_AUTHENTICATOR_GENERAL_ERROR', + cause: error, + }) + } + + return new WebAuthnError({ + message: 'a Non-Webauthn related error has occurred', + code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY', + cause: error, + }) +} + +/** + * Attempt to intuit _why_ an error was raised after calling `navigator.credentials.get()`. + * Maps browser errors to specific WebAuthn error codes for better debugging. + * @param {Object} params - Error identification parameters + * @param {Error} params.error - The error thrown by the browser + * @param {CredentialRequestOptions} params.options - The options passed to credentials.get() + * @returns {WebAuthnError} A WebAuthnError with a specific error code + * @see {@link https://w3c.github.io/webauthn/#sctn-getAssertion W3C WebAuthn Spec - Get Assertion} + */ +export function identifyAuthenticationError({ + error, + options, +}: { + error: Error + options: StrictOmit & { + publicKey: PublicKeyCredentialRequestOptionsFuture + } +}): WebAuthnError { + const { publicKey } = options + + if (!publicKey) { + throw Error('options was missing required publicKey property') + } + + if (error.name === 'AbortError') { + if (options.signal instanceof AbortSignal) { + // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 16) + return new WebAuthnError({ + message: 'Authentication ceremony was sent an abort signal', + code: 'ERROR_CEREMONY_ABORTED', + cause: error, + }) + } + } else if (error.name === 'NotAllowedError') { + /** + * Pass the error directly through. Platforms are overloading this error beyond what the spec + * defines and we don't want to overwrite potentially useful error messages. + */ + return new WebAuthnError({ + message: error.message, + code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY', + cause: error, + }) + } else if (error.name === 'SecurityError') { + const effectiveDomain = window.location.hostname + if (!isValidDomain(effectiveDomain)) { + // https://www.w3.org/TR/webauthn-2/#sctn-discover-from-external-source (Step 5) + return new WebAuthnError({ + message: `${window.location.hostname} is an invalid domain`, + code: 'ERROR_INVALID_DOMAIN', + cause: error, + }) + } else if (publicKey.rpId !== effectiveDomain) { + // https://www.w3.org/TR/webauthn-2/#sctn-discover-from-external-source (Step 6) + return new WebAuthnError({ + message: `The RP ID "${publicKey.rpId}" is invalid for this domain`, + code: 'ERROR_INVALID_RP_ID', + cause: error, + }) + } + } else if (error.name === 'UnknownError') { + // https://www.w3.org/TR/webauthn-2/#sctn-op-get-assertion (Step 1) + // https://www.w3.org/TR/webauthn-2/#sctn-op-get-assertion (Step 12) + return new WebAuthnError({ + message: + 'The authenticator was unable to process the specified options, or could not create a new assertion signature', + code: 'ERROR_AUTHENTICATOR_GENERAL_ERROR', + cause: error, + }) + } + + return new WebAuthnError({ + message: 'a Non-Webauthn related error has occurred', + code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY', + cause: error, + }) +} diff --git a/backend/node_modules/@supabase/auth-js/src/lib/webauthn.ts b/backend/node_modules/@supabase/auth-js/src/lib/webauthn.ts new file mode 100644 index 0000000..957b0f7 --- /dev/null +++ b/backend/node_modules/@supabase/auth-js/src/lib/webauthn.ts @@ -0,0 +1,934 @@ +import GoTrueClient from '../GoTrueClient' +import { base64UrlToUint8Array, bytesToBase64URL } from './base64url' +import { AuthError, AuthUnknownError, isAuthError } from './errors' +import { + AuthMFAEnrollWebauthnResponse, + AuthMFAVerifyResponse, + AuthMFAVerifyResponseData, + MFAChallengeWebauthnParams, + MFAEnrollWebauthnParams, + MFAVerifyWebauthnParamFields, + MFAVerifyWebauthnParams, + RequestResult, + StrictOmit, +} from './types' +import { isBrowser } from './helpers' +import type { + AuthenticationCredential, + AuthenticationResponseJSON, + AuthenticatorAttachment, + PublicKeyCredentialCreationOptionsFuture, + PublicKeyCredentialCreationOptionsJSON, + PublicKeyCredentialFuture, + PublicKeyCredentialRequestOptionsFuture, + PublicKeyCredentialRequestOptionsJSON, + RegistrationCredential, + RegistrationResponseJSON, +} from './webauthn.dom' + +import { + identifyAuthenticationError, + identifyRegistrationError, + isWebAuthnError, + WebAuthnError, + WebAuthnUnknownError, +} from './webauthn.errors' + +export { WebAuthnError, isWebAuthnError, identifyRegistrationError, identifyAuthenticationError } +// Re-export the JSON types for use in other files +export type { RegistrationResponseJSON, AuthenticationResponseJSON } + +/** + * WebAuthn abort service to manage ceremony cancellation. + * Ensures only one WebAuthn ceremony is active at a time to prevent "operation already in progress" errors. + * + * @experimental This class is experimental and may change in future releases + * @see {@link https://w3c.github.io/webauthn/#sctn-automation-webdriver-capability W3C WebAuthn Spec - Aborting Ceremonies} + */ +export class WebAuthnAbortService { + private controller: AbortController | undefined + + /** + * Create an abort signal for a new WebAuthn operation. + * Automatically cancels any existing operation. + * + * @returns {AbortSignal} Signal to pass to navigator.credentials.create() or .get() + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal MDN - AbortSignal} + */ + createNewAbortSignal(): AbortSignal { + // Abort any existing calls to navigator.credentials.create() or navigator.credentials.get() + if (this.controller) { + const abortError = new Error('Cancelling existing WebAuthn API call for new one') + abortError.name = 'AbortError' + this.controller.abort(abortError) + } + + const newController = new AbortController() + this.controller = newController + return newController.signal + } + + /** + * Manually cancel the current WebAuthn operation. + * Useful for cleaning up when user cancels or navigates away. + * + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort MDN - AbortController.abort} + */ + cancelCeremony(): void { + if (this.controller) { + const abortError = new Error('Manually cancelling existing WebAuthn API call') + abortError.name = 'AbortError' + this.controller.abort(abortError) + this.controller = undefined + } + } +} + +/** + * Singleton instance to ensure only one WebAuthn ceremony is active at a time. + * This prevents "operation already in progress" errors when retrying WebAuthn operations. + * + * @experimental This instance is experimental and may change in future releases + */ +export const webAuthnAbortService = new WebAuthnAbortService() + +/** + * Server response format for WebAuthn credential creation options. + * Uses W3C standard JSON format with base64url-encoded binary fields. + */ +export type ServerCredentialCreationOptions = PublicKeyCredentialCreationOptionsJSON + +/** + * Server response format for WebAuthn credential request options. + * Uses W3C standard JSON format with base64url-encoded binary fields. + */ +export type ServerCredentialRequestOptions = PublicKeyCredentialRequestOptionsJSON + +/** + * Convert base64url encoded strings in WebAuthn credential creation options to ArrayBuffers + * as required by the WebAuthn browser API. + * Supports both native WebAuthn Level 3 parseCreationOptionsFromJSON and manual fallback. + * + * @param {ServerCredentialCreationOptions} options - JSON options from server with base64url encoded fields + * @returns {PublicKeyCredentialCreationOptionsFuture} Options ready for navigator.credentials.create() + * @see {@link https://w3c.github.io/webauthn/#sctn-parseCreationOptionsFromJSON W3C WebAuthn Spec - parseCreationOptionsFromJSON} + */ +export function deserializeCredentialCreationOptions( + options: ServerCredentialCreationOptions +): PublicKeyCredentialCreationOptionsFuture { + if (!options) { + throw new Error('Credential creation options are required') + } + + // Check if the native parseCreationOptionsFromJSON method is available + if ( + typeof PublicKeyCredential !== 'undefined' && + 'parseCreationOptionsFromJSON' in PublicKeyCredential && + typeof (PublicKeyCredential as unknown as PublicKeyCredentialFuture) + .parseCreationOptionsFromJSON === 'function' + ) { + // Use the native WebAuthn Level 3 method + return ( + PublicKeyCredential as unknown as PublicKeyCredentialFuture + ).parseCreationOptionsFromJSON( + /** we assert the options here as typescript still doesn't know about future webauthn types */ + options as any + ) as PublicKeyCredentialCreationOptionsFuture + } + + // Fallback to manual parsing for browsers that don't support the native method + // Destructure to separate fields that need transformation + const { challenge: challengeStr, user: userOpts, excludeCredentials, ...restOptions } = options + + // Convert challenge from base64url to ArrayBuffer + const challenge = base64UrlToUint8Array(challengeStr).buffer as ArrayBuffer + + // Convert user.id from base64url to ArrayBuffer + const user: PublicKeyCredentialUserEntity = { + ...userOpts, + id: base64UrlToUint8Array(userOpts.id).buffer as ArrayBuffer, + } + + // Build the result object + const result: PublicKeyCredentialCreationOptionsFuture = { + ...restOptions, + challenge, + user, + } + + // Only add excludeCredentials if it exists + if (excludeCredentials && excludeCredentials.length > 0) { + result.excludeCredentials = new Array(excludeCredentials.length) + + for (let i = 0; i < excludeCredentials.length; i++) { + const cred = excludeCredentials[i] + result.excludeCredentials[i] = { + ...cred, + id: base64UrlToUint8Array(cred.id).buffer, + type: cred.type || 'public-key', + // Cast transports to handle future transport types like "cable" + transports: cred.transports, + } + } + } + + return result +} + +/** + * Convert base64url encoded strings in WebAuthn credential request options to ArrayBuffers + * as required by the WebAuthn browser API. + * Supports both native WebAuthn Level 3 parseRequestOptionsFromJSON and manual fallback. + * + * @param {ServerCredentialRequestOptions} options - JSON options from server with base64url encoded fields + * @returns {PublicKeyCredentialRequestOptionsFuture} Options ready for navigator.credentials.get() + * @see {@link https://w3c.github.io/webauthn/#sctn-parseRequestOptionsFromJSON W3C WebAuthn Spec - parseRequestOptionsFromJSON} + */ +export function deserializeCredentialRequestOptions( + options: ServerCredentialRequestOptions +): PublicKeyCredentialRequestOptionsFuture { + if (!options) { + throw new Error('Credential request options are required') + } + + // Check if the native parseRequestOptionsFromJSON method is available + if ( + typeof PublicKeyCredential !== 'undefined' && + 'parseRequestOptionsFromJSON' in PublicKeyCredential && + typeof (PublicKeyCredential as unknown as PublicKeyCredentialFuture) + .parseRequestOptionsFromJSON === 'function' + ) { + // Use the native WebAuthn Level 3 method + return ( + PublicKeyCredential as unknown as PublicKeyCredentialFuture + ).parseRequestOptionsFromJSON(options) as PublicKeyCredentialRequestOptionsFuture + } + + // Fallback to manual parsing for browsers that don't support the native method + // Destructure to separate fields that need transformation + const { challenge: challengeStr, allowCredentials, ...restOptions } = options + + // Convert challenge from base64url to ArrayBuffer + const challenge = base64UrlToUint8Array(challengeStr).buffer as ArrayBuffer + + // Build the result object + const result: PublicKeyCredentialRequestOptionsFuture = { + ...restOptions, + challenge, + } + + // Only add allowCredentials if it exists + if (allowCredentials && allowCredentials.length > 0) { + result.allowCredentials = new Array(allowCredentials.length) + + for (let i = 0; i < allowCredentials.length; i++) { + const cred = allowCredentials[i] + result.allowCredentials[i] = { + ...cred, + id: base64UrlToUint8Array(cred.id).buffer, + type: cred.type || 'public-key', + // Cast transports to handle future transport types like "cable" + transports: cred.transports, + } + } + } + + return result +} + +/** + * Server format for credential response with base64url-encoded binary fields + * Can be either a registration or authentication response + */ +export type ServerCredentialResponse = RegistrationResponseJSON | AuthenticationResponseJSON + +/** + * Convert a registration/enrollment credential response to server format. + * Serializes binary fields to base64url for JSON transmission. + * Supports both native WebAuthn Level 3 toJSON and manual fallback. + * + * @param {RegistrationCredential} credential - Credential from navigator.credentials.create() + * @returns {RegistrationResponseJSON} JSON-serializable credential for server + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-tojson W3C WebAuthn Spec - toJSON} + */ +export function serializeCredentialCreationResponse( + credential: RegistrationCredential +): RegistrationResponseJSON { + // Check if the credential instance has the toJSON method + if ('toJSON' in credential && typeof credential.toJSON === 'function') { + // Use the native WebAuthn Level 3 method + return (credential as RegistrationCredential).toJSON() + } + const credentialWithAttachment = credential as PublicKeyCredential & { + response: AuthenticatorAttestationResponse + authenticatorAttachment?: string | null + } + + return { + id: credential.id, + rawId: credential.id, + response: { + attestationObject: bytesToBase64URL(new Uint8Array(credential.response.attestationObject)), + clientDataJSON: bytesToBase64URL(new Uint8Array(credential.response.clientDataJSON)), + }, + type: 'public-key', + clientExtensionResults: credential.getClientExtensionResults(), + // Convert null to undefined and cast to AuthenticatorAttachment type + authenticatorAttachment: (credentialWithAttachment.authenticatorAttachment ?? undefined) as + | AuthenticatorAttachment + | undefined, + } +} + +/** + * Convert an authentication/verification credential response to server format. + * Serializes binary fields to base64url for JSON transmission. + * Supports both native WebAuthn Level 3 toJSON and manual fallback. + * + * @param {AuthenticationCredential} credential - Credential from navigator.credentials.get() + * @returns {AuthenticationResponseJSON} JSON-serializable credential for server + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-tojson W3C WebAuthn Spec - toJSON} + */ +export function serializeCredentialRequestResponse( + credential: AuthenticationCredential +): AuthenticationResponseJSON { + // Check if the credential instance has the toJSON method + if ('toJSON' in credential && typeof credential.toJSON === 'function') { + // Use the native WebAuthn Level 3 method + return (credential as AuthenticationCredential).toJSON() + } + + // Fallback to manual conversion for browsers that don't support toJSON + // Access authenticatorAttachment via type assertion to handle TypeScript version differences + // @simplewebauthn/types includes this property but base TypeScript 4.7.4 doesn't + const credentialWithAttachment = credential as PublicKeyCredential & { + response: AuthenticatorAssertionResponse + authenticatorAttachment?: string | null + } + + const clientExtensionResults = credential.getClientExtensionResults() + const assertionResponse = credential.response + + return { + id: credential.id, + rawId: credential.id, // W3C spec expects rawId to match id for JSON format + response: { + authenticatorData: bytesToBase64URL(new Uint8Array(assertionResponse.authenticatorData)), + clientDataJSON: bytesToBase64URL(new Uint8Array(assertionResponse.clientDataJSON)), + signature: bytesToBase64URL(new Uint8Array(assertionResponse.signature)), + userHandle: assertionResponse.userHandle + ? bytesToBase64URL(new Uint8Array(assertionResponse.userHandle)) + : undefined, + }, + type: 'public-key', + clientExtensionResults, + // Convert null to undefined and cast to AuthenticatorAttachment type + authenticatorAttachment: (credentialWithAttachment.authenticatorAttachment ?? undefined) as + | AuthenticatorAttachment + | undefined, + } +} + +/** + * A simple test to determine if a hostname is a properly-formatted domain name. + * Considers localhost valid for development environments. + * + * A "valid domain" is defined here: https://url.spec.whatwg.org/#valid-domain + * + * Regex sourced from here: + * https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch08s15.html + * + * @param {string} hostname - The hostname to validate + * @returns {boolean} True if valid domain or localhost + * @see {@link https://url.spec.whatwg.org/#valid-domain WHATWG URL Spec - Valid Domain} + */ +export function isValidDomain(hostname: string): boolean { + return ( + // Consider localhost valid as well since it's okay wrt Secure Contexts + hostname === 'localhost' || /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(hostname) + ) +} + +/** + * Determine if the browser is capable of WebAuthn. + * Checks for necessary Web APIs: PublicKeyCredential and Credential Management. + * + * @returns {boolean} True if browser supports WebAuthn + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredential#browser_compatibility MDN - PublicKeyCredential Browser Compatibility} + */ +function browserSupportsWebAuthn(): boolean { + return !!( + isBrowser() && + 'PublicKeyCredential' in window && + window.PublicKeyCredential && + 'credentials' in navigator && + typeof navigator?.credentials?.create === 'function' && + typeof navigator?.credentials?.get === 'function' + ) +} + +/** + * Create a WebAuthn credential using the browser's credentials API. + * Wraps navigator.credentials.create() with error handling. + * + * @param {CredentialCreationOptions} options - Options including publicKey parameters + * @returns {Promise>} Created credential or error + * @see {@link https://w3c.github.io/webauthn/#sctn-createCredential W3C WebAuthn Spec - Create Credential} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/create MDN - credentials.create} + */ +export async function createCredential( + options: StrictOmit & { + publicKey: PublicKeyCredentialCreationOptionsFuture + } +): Promise> { + try { + const response = await navigator.credentials.create( + /** we assert the type here until typescript types are updated */ + options as Parameters[0] + ) + if (!response) { + return { + data: null, + error: new WebAuthnUnknownError('Empty credential response', response), + } + } + if (!(response instanceof PublicKeyCredential)) { + return { + data: null, + error: new WebAuthnUnknownError('Browser returned unexpected credential type', response), + } + } + return { data: response as RegistrationCredential, error: null } + } catch (err) { + return { + data: null, + error: identifyRegistrationError({ + error: err as Error, + options, + }), + } + } +} + +/** + * Get a WebAuthn credential using the browser's credentials API. + * Wraps navigator.credentials.get() with error handling. + * + * @param {CredentialRequestOptions} options - Options including publicKey parameters + * @returns {Promise>} Retrieved credential or error + * @see {@link https://w3c.github.io/webauthn/#sctn-getAssertion W3C WebAuthn Spec - Get Assertion} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/get MDN - credentials.get} + */ +export async function getCredential( + options: StrictOmit & { + publicKey: PublicKeyCredentialRequestOptionsFuture + } +): Promise> { + try { + const response = await navigator.credentials.get( + /** we assert the type here until typescript types are updated */ + options as Parameters[0] + ) + if (!response) { + return { + data: null, + error: new WebAuthnUnknownError('Empty credential response', response), + } + } + if (!(response instanceof PublicKeyCredential)) { + return { + data: null, + error: new WebAuthnUnknownError('Browser returned unexpected credential type', response), + } + } + return { data: response as AuthenticationCredential, error: null } + } catch (err) { + return { + data: null, + error: identifyAuthenticationError({ + error: err as Error, + options, + }), + } + } +} + +export const DEFAULT_CREATION_OPTIONS: Partial = { + hints: ['security-key'], + authenticatorSelection: { + authenticatorAttachment: 'cross-platform', + requireResidentKey: false, + /** set to preferred because older yubikeys don't have PIN/Biometric */ + userVerification: 'preferred', + residentKey: 'discouraged', + }, + attestation: 'direct', +} + +export const DEFAULT_REQUEST_OPTIONS: Partial = { + /** set to preferred because older yubikeys don't have PIN/Biometric */ + userVerification: 'preferred', + hints: ['security-key'], + attestation: 'direct', +} + +function deepMerge(...sources: Partial[]): T { + const isObject = (val: unknown): val is Record => + val !== null && typeof val === 'object' && !Array.isArray(val) + + const isArrayBufferLike = (val: unknown): val is ArrayBuffer | ArrayBufferView => + val instanceof ArrayBuffer || ArrayBuffer.isView(val) + + const result: Partial = {} + + for (const source of sources) { + if (!source) continue + + for (const key in source) { + const value = source[key] + if (value === undefined) continue + + if (Array.isArray(value)) { + // preserve array reference, including unions like AuthenticatorTransport[] + result[key] = value as T[typeof key] + } else if (isArrayBufferLike(value)) { + result[key] = value as T[typeof key] + } else if (isObject(value)) { + const existing = result[key] + if (isObject(existing)) { + result[key] = deepMerge(existing, value) as unknown as T[typeof key] + } else { + result[key] = deepMerge(value) as unknown as T[typeof key] + } + } else { + result[key] = value as T[typeof key] + } + } + } + + return result as T +} + +/** + * Merges WebAuthn credential creation options with overrides. + * Sets sensible defaults for authenticator selection and extensions. + * + * @param {PublicKeyCredentialCreationOptionsFuture} baseOptions - The base options from the server + * @param {PublicKeyCredentialCreationOptionsFuture} overrides - Optional overrides to apply + * @param {string} friendlyName - Optional friendly name for the credential + * @returns {PublicKeyCredentialCreationOptionsFuture} Merged credential creation options + * @see {@link https://w3c.github.io/webauthn/#dictdef-authenticatorselectioncriteria W3C WebAuthn Spec - AuthenticatorSelectionCriteria} + */ +export function mergeCredentialCreationOptions( + baseOptions: PublicKeyCredentialCreationOptionsFuture, + overrides?: Partial +): PublicKeyCredentialCreationOptionsFuture { + return deepMerge(DEFAULT_CREATION_OPTIONS, baseOptions, overrides || {}) +} + +/** + * Merges WebAuthn credential request options with overrides. + * Sets sensible defaults for user verification and hints. + * + * @param {PublicKeyCredentialRequestOptionsFuture} baseOptions - The base options from the server + * @param {PublicKeyCredentialRequestOptionsFuture} overrides - Optional overrides to apply + * @returns {PublicKeyCredentialRequestOptionsFuture} Merged credential request options + * @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialrequestoptions W3C WebAuthn Spec - PublicKeyCredentialRequestOptions} + */ +export function mergeCredentialRequestOptions( + baseOptions: PublicKeyCredentialRequestOptionsFuture, + overrides?: Partial +): PublicKeyCredentialRequestOptionsFuture { + return deepMerge(DEFAULT_REQUEST_OPTIONS, baseOptions, overrides || {}) +} + +/** + * WebAuthn API wrapper for Supabase Auth. + * Provides methods for enrolling, challenging, verifying, authenticating, and registering WebAuthn credentials. + * + * @experimental This API is experimental and may change in future releases + * @see {@link https://w3c.github.io/webauthn/ W3C WebAuthn Specification} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API MDN - Web Authentication API} + */ +export class WebAuthnApi { + public enroll: typeof WebAuthnApi.prototype._enroll + public challenge: typeof WebAuthnApi.prototype._challenge + public verify: typeof WebAuthnApi.prototype._verify + public authenticate: typeof WebAuthnApi.prototype._authenticate + public register: typeof WebAuthnApi.prototype._register + + constructor(private client: GoTrueClient) { + // Bind all methods so they can be destructured + this.enroll = this._enroll.bind(this) + this.challenge = this._challenge.bind(this) + this.verify = this._verify.bind(this) + this.authenticate = this._authenticate.bind(this) + this.register = this._register.bind(this) + } + + /** + * Enroll a new WebAuthn factor. + * Creates an unverified WebAuthn factor that must be verified with a credential. + * + * @experimental This method is experimental and may change in future releases + * @param {Omit} params - Enrollment parameters (friendlyName required) + * @returns {Promise} Enrolled factor details or error + * @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registering a New Credential} + */ + public async _enroll( + params: Omit + ): Promise { + return this.client.mfa.enroll({ ...params, factorType: 'webauthn' }) + } + + /** + * Challenge for WebAuthn credential creation or authentication. + * Combines server challenge with browser credential operations. + * Handles both registration (create) and authentication (request) flows. + * + * @experimental This method is experimental and may change in future releases + * @param {MFAChallengeWebauthnParams & { friendlyName?: string; signal?: AbortSignal }} params - Challenge parameters including factorId + * @param {Object} overrides - Allows you to override the parameters passed to navigator.credentials + * @param {PublicKeyCredentialCreationOptionsFuture} overrides.create - Override options for credential creation + * @param {PublicKeyCredentialRequestOptionsFuture} overrides.request - Override options for credential request + * @returns {Promise} Challenge response with credential or error + * @see {@link https://w3c.github.io/webauthn/#sctn-credential-creation W3C WebAuthn Spec - Credential Creation} + * @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying Assertion} + */ + public async _challenge( + { + factorId, + webauthn, + friendlyName, + signal, + }: MFAChallengeWebauthnParams & { friendlyName?: string; signal?: AbortSignal }, + overrides?: + | { + create?: Partial + request?: never + } + | { + create?: never + request?: Partial + } + ): Promise< + RequestResult< + { factorId: string; challengeId: string } & { + webauthn: StrictOmit< + MFAVerifyWebauthnParamFields<'create' | 'request'>['webauthn'], + 'rpId' | 'rpOrigins' + > + }, + WebAuthnError | AuthError + > + > { + try { + // Get challenge from server using the client's MFA methods + const { data: challengeResponse, error: challengeError } = await this.client.mfa.challenge({ + factorId, + webauthn, + }) + + if (!challengeResponse) { + return { data: null, error: challengeError } + } + + const abortSignal = signal ?? webAuthnAbortService.createNewAbortSignal() + + /** webauthn will fail if either of the name/displayname are blank */ + if (challengeResponse.webauthn.type === 'create') { + const { user } = challengeResponse.webauthn.credential_options.publicKey + if (!user.name) { + user.name = `${user.id}:${friendlyName}` + } + if (!user.displayName) { + user.displayName = user.name + } + } + + switch (challengeResponse.webauthn.type) { + case 'create': { + const options = mergeCredentialCreationOptions( + challengeResponse.webauthn.credential_options.publicKey, + overrides?.create + ) + + const { data, error } = await createCredential({ + publicKey: options, + signal: abortSignal, + }) + + if (data) { + return { + data: { + factorId, + challengeId: challengeResponse.id, + webauthn: { + type: challengeResponse.webauthn.type, + credential_response: data, + }, + }, + error: null, + } + } + return { data: null, error } + } + + case 'request': { + const options = mergeCredentialRequestOptions( + challengeResponse.webauthn.credential_options.publicKey, + overrides?.request + ) + + const { data, error } = await getCredential({ + ...challengeResponse.webauthn.credential_options, + publicKey: options, + signal: abortSignal, + }) + + if (data) { + return { + data: { + factorId, + challengeId: challengeResponse.id, + webauthn: { + type: challengeResponse.webauthn.type, + credential_response: data, + }, + }, + error: null, + } + } + return { data: null, error } + } + } + } catch (error) { + if (isAuthError(error)) { + return { data: null, error } + } + return { + data: null, + error: new AuthUnknownError('Unexpected error in challenge', error), + } + } + } + + /** + * Verify a WebAuthn credential with the server. + * Completes the WebAuthn ceremony by sending the credential to the server for verification. + * + * @experimental This method is experimental and may change in future releases + * @param {Object} params - Verification parameters + * @param {string} params.challengeId - ID of the challenge being verified + * @param {string} params.factorId - ID of the WebAuthn factor + * @param {MFAVerifyWebauthnParams['webauthn']} params.webauthn - WebAuthn credential response + * @returns {Promise} Verification result with session or error + * @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying an Authentication Assertion} + * */ + public async _verify({ + challengeId, + factorId, + webauthn, + }: { + challengeId: string + factorId: string + webauthn: MFAVerifyWebauthnParams['webauthn'] + }): Promise { + return this.client.mfa.verify({ + factorId, + challengeId, + webauthn: webauthn, + }) + } + + /** + * Complete WebAuthn authentication flow. + * Performs challenge and verification in a single operation for existing credentials. + * + * @experimental This method is experimental and may change in future releases + * @param {Object} params - Authentication parameters + * @param {string} params.factorId - ID of the WebAuthn factor to authenticate with + * @param {Object} params.webauthn - WebAuthn configuration + * @param {string} params.webauthn.rpId - Relying Party ID (defaults to current hostname) + * @param {string[]} params.webauthn.rpOrigins - Allowed origins (defaults to current origin) + * @param {AbortSignal} params.webauthn.signal - Optional abort signal + * @param {PublicKeyCredentialRequestOptionsFuture} overrides - Override options for navigator.credentials.get + * @returns {Promise>} Authentication result + * @see {@link https://w3c.github.io/webauthn/#sctn-authentication W3C WebAuthn Spec - Authentication Ceremony} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialRequestOptions MDN - PublicKeyCredentialRequestOptions} + */ + public async _authenticate( + { + factorId, + webauthn: { + rpId = typeof window !== 'undefined' ? window.location.hostname : undefined, + rpOrigins = typeof window !== 'undefined' ? [window.location.origin] : undefined, + signal, + } = {}, + }: { + factorId: string + webauthn?: { + rpId?: string + rpOrigins?: string[] + signal?: AbortSignal + } + }, + overrides?: PublicKeyCredentialRequestOptionsFuture + ): Promise> { + if (!rpId) { + return { + data: null, + error: new AuthError('rpId is required for WebAuthn authentication'), + } + } + try { + if (!browserSupportsWebAuthn()) { + return { + data: null, + error: new AuthUnknownError('Browser does not support WebAuthn', null), + } + } + + // Get challenge and credential + const { data: challengeResponse, error: challengeError } = await this.challenge( + { + factorId, + webauthn: { rpId, rpOrigins }, + signal, + }, + { request: overrides } + ) + + if (!challengeResponse) { + return { data: null, error: challengeError } + } + + const { webauthn } = challengeResponse + + // Verify credential + return this._verify({ + factorId, + challengeId: challengeResponse.challengeId, + webauthn: { + type: webauthn.type, + rpId, + rpOrigins, + credential_response: webauthn.credential_response, + }, + }) + } catch (error) { + if (isAuthError(error)) { + return { data: null, error } + } + return { + data: null, + error: new AuthUnknownError('Unexpected error in authenticate', error), + } + } + } + + /** + * Complete WebAuthn registration flow. + * Performs enrollment, challenge, and verification in a single operation for new credentials. + * + * @experimental This method is experimental and may change in future releases + * @param {Object} params - Registration parameters + * @param {string} params.friendlyName - User-friendly name for the credential + * @param {string} params.rpId - Relying Party ID (defaults to current hostname) + * @param {string[]} params.rpOrigins - Allowed origins (defaults to current origin) + * @param {AbortSignal} params.signal - Optional abort signal + * @param {PublicKeyCredentialCreationOptionsFuture} overrides - Override options for navigator.credentials.create + * @returns {Promise>} Registration result + * @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registration Ceremony} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions MDN - PublicKeyCredentialCreationOptions} + */ + public async _register( + { + friendlyName, + webauthn: { + rpId = typeof window !== 'undefined' ? window.location.hostname : undefined, + rpOrigins = typeof window !== 'undefined' ? [window.location.origin] : undefined, + signal, + } = {}, + }: { + friendlyName: string + webauthn?: { + rpId?: string + rpOrigins?: string[] + signal?: AbortSignal + } + }, + overrides?: Partial + ): Promise> { + if (!rpId) { + return { + data: null, + error: new AuthError('rpId is required for WebAuthn registration'), + } + } + try { + if (!browserSupportsWebAuthn()) { + return { + data: null, + error: new AuthUnknownError('Browser does not support WebAuthn', null), + } + } + + // Enroll factor + const { data: factor, error: enrollError } = await this._enroll({ + friendlyName, + }) + + if (!factor) { + await this.client.mfa + .listFactors() + .then((factors) => + factors.data?.all.find( + (v) => + v.factor_type === 'webauthn' && + v.friendly_name === friendlyName && + v.status !== 'unverified' + ) + ) + .then((factor) => (factor ? this.client.mfa.unenroll({ factorId: factor?.id }) : void 0)) + return { data: null, error: enrollError } + } + + // Get challenge and create credential + const { data: challengeResponse, error: challengeError } = await this._challenge( + { + factorId: factor.id, + friendlyName: factor.friendly_name, + webauthn: { rpId, rpOrigins }, + signal, + }, + { + create: overrides, + } + ) + + if (!challengeResponse) { + return { data: null, error: challengeError } + } + + return this._verify({ + factorId: factor.id, + challengeId: challengeResponse.challengeId, + webauthn: { + rpId, + rpOrigins, + type: challengeResponse.webauthn.type, + credential_response: challengeResponse.webauthn.credential_response, + }, + }) + } catch (error) { + if (isAuthError(error)) { + return { data: null, error } + } + return { + data: null, + error: new AuthUnknownError('Unexpected error in register', error), + } + } + } +} diff --git a/backend/node_modules/@supabase/functions-js/README.md b/backend/node_modules/@supabase/functions-js/README.md new file mode 100644 index 0000000..5ccb1eb --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/README.md @@ -0,0 +1,134 @@ +
+

+ + + + + Supabase Logo + + + +

Supabase Functions JS SDK

+ +

JavaScript SDK to interact with Supabase Edge Functions.

+ +

+ Guides + · + Reference Docs + · + TypeDoc +

+

+ +
+ +[![Build](https://github.com/supabase/supabase-js/workflows/CI/badge.svg)](https://github.com/supabase/supabase-js/actions?query=branch%3Amaster) +[![Package](https://img.shields.io/npm/v/@supabase/functions-js)](https://www.npmjs.com/package/@supabase/functions-js) +[![License: MIT](https://img.shields.io/npm/l/@supabase/supabase-js)](#license) +[![pkg.pr.new](https://pkg.pr.new/badge/supabase/functions-js)](https://pkg.pr.new/~/supabase/functions-js) + +
+ +## Requirements + +- **Node.js 20 or later** (Node.js 18 support dropped as of October 31, 2025) +- For browser support, all modern browsers are supported + +> ⚠️ **Node.js 18 Deprecation Notice** +> +> Node.js 18 reached end-of-life on April 30, 2025. As announced in [our deprecation notice](https://github.com/orgs/supabase/discussions/37217), support for Node.js 18 was dropped on October 31, 2025. + +## Quick Start + +### Installation + +```bash +npm install @supabase/functions-js +``` + +### Usage + +```js +import { FunctionsClient } from '@supabase/functions-js' + +const functionsUrl = 'https://.supabase.co/functions/v1' +const anonKey = '' + +const functions = new FunctionsClient(functionsUrl, { + headers: { + Authorization: `Bearer ${anonKey}`, + }, +}) + +// Invoke a function +const { data, error } = await functions.invoke('hello-world', { + body: { name: 'Functions' }, +}) +``` + +## Development + +This package is part of the [Supabase JavaScript monorepo](https://github.com/supabase/supabase-js). To work on this package: + +### Building + +```bash +# Complete build (from monorepo root) +npx nx build functions-js + +# Build with watch mode for development +npx nx build functions-js --watch + +# Individual build targets +npx nx build:main functions-js # CommonJS build (dist/main/) +npx nx build:module functions-js # ES Modules build (dist/module/) + +# Other useful commands +npx nx clean functions-js # Clean build artifacts +npx nx typecheck functions-js # TypeScript type checking +npx nx docs functions-js # Generate documentation +``` + +#### Build Outputs + +- **CommonJS (`dist/main/`)** - For Node.js environments +- **ES Modules (`dist/module/`)** - For modern bundlers (Webpack, Vite, Rollup) +- **TypeScript definitions (`dist/module/index.d.ts`)** - Type definitions for TypeScript projects + +### Testing + +**Docker Required** for relay tests. The functions-js tests use testcontainers to spin up a Deno relay server for testing Edge Function invocations. + +```bash +# Run all tests (from monorepo root) +npx nx test functions-js + +# Run tests with coverage report +npx nx test functions-js --coverage + +# Run tests in watch mode during development +npx nx test functions-js --watch + +# CI test command (runs with coverage) +npx nx test:ci functions-js +``` + +#### Test Requirements + +- **Node.js 20+** - Required for testcontainers +- **Docker** - Must be installed and running for relay tests +- No Supabase instance needed - Tests use mocked services and testcontainers + +#### What Gets Tested + +- **Function invocation** - Testing the `invoke()` method with various options +- **Relay functionality** - Using a containerized Deno relay to test real Edge Function scenarios +- **Error handling** - Ensuring proper error responses and retries +- **Request/response models** - Validating headers, body, and response formats + +### Contributing + +We welcome contributions! Please see our [Contributing Guide](../../../CONTRIBUTING.md) for details on how to get started. + +For major changes or if you're unsure about something, please open an issue first to discuss your proposed changes. diff --git a/backend/node_modules/@supabase/functions-js/dist/main/FunctionsClient.d.ts b/backend/node_modules/@supabase/functions-js/dist/main/FunctionsClient.d.ts new file mode 100644 index 0000000..ff81f03 --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/main/FunctionsClient.d.ts @@ -0,0 +1,50 @@ +import { Fetch, FunctionInvokeOptions, FunctionRegion, FunctionsResponse } from './types'; +/** + * Client for invoking Supabase Edge Functions. + */ +export declare class FunctionsClient { + protected url: string; + protected headers: Record; + protected region: FunctionRegion; + protected fetch: Fetch; + /** + * Creates a new Functions client bound to an Edge Functions URL. + * + * @example + * ```ts + * import { FunctionsClient, FunctionRegion } from '@supabase/functions-js' + * + * const functions = new FunctionsClient('https://xyzcompany.supabase.co/functions/v1', { + * headers: { apikey: 'public-anon-key' }, + * region: FunctionRegion.UsEast1, + * }) + * ``` + */ + constructor(url: string, { headers, customFetch, region, }?: { + headers?: Record; + customFetch?: Fetch; + region?: FunctionRegion; + }); + /** + * Updates the authorization header + * @param token - the new jwt token sent in the authorisation header + * @example + * ```ts + * functions.setAuth(session.access_token) + * ``` + */ + setAuth(token: string): void; + /** + * Invokes a function + * @param functionName - The name of the Function to invoke. + * @param options - Options for invoking the Function. + * @example + * ```ts + * const { data, error } = await functions.invoke('hello-world', { + * body: { name: 'Ada' }, + * }) + * ``` + */ + invoke(functionName: string, options?: FunctionInvokeOptions): Promise>; +} +//# sourceMappingURL=FunctionsClient.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/main/FunctionsClient.d.ts.map b/backend/node_modules/@supabase/functions-js/dist/main/FunctionsClient.d.ts.map new file mode 100644 index 0000000..ac8158f --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/main/FunctionsClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"FunctionsClient.d.ts","sourceRoot":"","sources":["../../src/FunctionsClient.ts"],"names":[],"mappings":"AACA,OAAO,EACL,KAAK,EACL,qBAAqB,EACrB,cAAc,EAId,iBAAiB,EAClB,MAAM,SAAS,CAAA;AAEhB;;GAEG;AACH,qBAAa,eAAe;IAC1B,SAAS,CAAC,GAAG,EAAE,MAAM,CAAA;IACrB,SAAS,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IACzC,SAAS,CAAC,MAAM,EAAE,cAAc,CAAA;IAChC,SAAS,CAAC,KAAK,EAAE,KAAK,CAAA;IAEtB;;;;;;;;;;;;OAYG;gBAED,GAAG,EAAE,MAAM,EACX,EACE,OAAY,EACZ,WAAW,EACX,MAA2B,GAC5B,GAAE;QACD,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;QAChC,WAAW,CAAC,EAAE,KAAK,CAAA;QACnB,MAAM,CAAC,EAAE,cAAc,CAAA;KACnB;IAQR;;;;;;;OAOG;IACH,OAAO,CAAC,KAAK,EAAE,MAAM;IAIrB;;;;;;;;;;OAUG;IACG,MAAM,CAAC,CAAC,GAAG,GAAG,EAClB,YAAY,EAAE,MAAM,EACpB,OAAO,GAAE,qBAA0B,GAClC,OAAO,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC;CAyHjC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/main/FunctionsClient.js b/backend/node_modules/@supabase/functions-js/dist/main/FunctionsClient.js new file mode 100644 index 0000000..ac607ee --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/main/FunctionsClient.js @@ -0,0 +1,174 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FunctionsClient = void 0; +const tslib_1 = require("tslib"); +const helper_1 = require("./helper"); +const types_1 = require("./types"); +/** + * Client for invoking Supabase Edge Functions. + */ +class FunctionsClient { + /** + * Creates a new Functions client bound to an Edge Functions URL. + * + * @example + * ```ts + * import { FunctionsClient, FunctionRegion } from '@supabase/functions-js' + * + * const functions = new FunctionsClient('https://xyzcompany.supabase.co/functions/v1', { + * headers: { apikey: 'public-anon-key' }, + * region: FunctionRegion.UsEast1, + * }) + * ``` + */ + constructor(url, { headers = {}, customFetch, region = types_1.FunctionRegion.Any, } = {}) { + this.url = url; + this.headers = headers; + this.region = region; + this.fetch = (0, helper_1.resolveFetch)(customFetch); + } + /** + * Updates the authorization header + * @param token - the new jwt token sent in the authorisation header + * @example + * ```ts + * functions.setAuth(session.access_token) + * ``` + */ + setAuth(token) { + this.headers.Authorization = `Bearer ${token}`; + } + /** + * Invokes a function + * @param functionName - The name of the Function to invoke. + * @param options - Options for invoking the Function. + * @example + * ```ts + * const { data, error } = await functions.invoke('hello-world', { + * body: { name: 'Ada' }, + * }) + * ``` + */ + invoke(functionName_1) { + return tslib_1.__awaiter(this, arguments, void 0, function* (functionName, options = {}) { + var _a; + let timeoutId; + let timeoutController; + try { + const { headers, method, body: functionArgs, signal, timeout } = options; + let _headers = {}; + let { region } = options; + if (!region) { + region = this.region; + } + // Add region as query parameter using URL API + const url = new URL(`${this.url}/${functionName}`); + if (region && region !== 'any') { + _headers['x-region'] = region; + url.searchParams.set('forceFunctionRegion', region); + } + let body; + if (functionArgs && + ((headers && !Object.prototype.hasOwnProperty.call(headers, 'Content-Type')) || !headers)) { + if ((typeof Blob !== 'undefined' && functionArgs instanceof Blob) || + functionArgs instanceof ArrayBuffer) { + // will work for File as File inherits Blob + // also works for ArrayBuffer as it is the same underlying structure as a Blob + _headers['Content-Type'] = 'application/octet-stream'; + body = functionArgs; + } + else if (typeof functionArgs === 'string') { + // plain string + _headers['Content-Type'] = 'text/plain'; + body = functionArgs; + } + else if (typeof FormData !== 'undefined' && functionArgs instanceof FormData) { + // don't set content-type headers + // Request will automatically add the right boundary value + body = functionArgs; + } + else { + // default, assume this is JSON + _headers['Content-Type'] = 'application/json'; + body = JSON.stringify(functionArgs); + } + } + else { + // if the Content-Type was supplied, simply set the body + body = functionArgs; + } + // Handle timeout by creating an AbortController + let effectiveSignal = signal; + if (timeout) { + timeoutController = new AbortController(); + timeoutId = setTimeout(() => timeoutController.abort(), timeout); + // If user provided their own signal, we need to respect both + if (signal) { + effectiveSignal = timeoutController.signal; + // If the user's signal is aborted, abort our timeout controller too + signal.addEventListener('abort', () => timeoutController.abort()); + } + else { + effectiveSignal = timeoutController.signal; + } + } + const response = yield this.fetch(url.toString(), { + method: method || 'POST', + // headers priority is (high to low): + // 1. invoke-level headers + // 2. client-level headers + // 3. default Content-Type header + headers: Object.assign(Object.assign(Object.assign({}, _headers), this.headers), headers), + body, + signal: effectiveSignal, + }).catch((fetchError) => { + throw new types_1.FunctionsFetchError(fetchError); + }); + const isRelayError = response.headers.get('x-relay-error'); + if (isRelayError && isRelayError === 'true') { + throw new types_1.FunctionsRelayError(response); + } + if (!response.ok) { + throw new types_1.FunctionsHttpError(response); + } + let responseType = ((_a = response.headers.get('Content-Type')) !== null && _a !== void 0 ? _a : 'text/plain').split(';')[0].trim(); + let data; + if (responseType === 'application/json') { + data = yield response.json(); + } + else if (responseType === 'application/octet-stream' || + responseType === 'application/pdf') { + data = yield response.blob(); + } + else if (responseType === 'text/event-stream') { + data = response; + } + else if (responseType === 'multipart/form-data') { + data = yield response.formData(); + } + else { + // default to text + data = yield response.text(); + } + return { data, error: null, response }; + } + catch (error) { + return { + data: null, + error, + response: error instanceof types_1.FunctionsHttpError || error instanceof types_1.FunctionsRelayError + ? error.context + : undefined, + }; + } + finally { + // Clear the timeout if it was set + if (timeoutId) { + clearTimeout(timeoutId); + } + } + }); + } +} +exports.FunctionsClient = FunctionsClient; +//# sourceMappingURL=FunctionsClient.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/main/FunctionsClient.js.map b/backend/node_modules/@supabase/functions-js/dist/main/FunctionsClient.js.map new file mode 100644 index 0000000..4ecb6e0 --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/main/FunctionsClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"FunctionsClient.js","sourceRoot":"","sources":["../../src/FunctionsClient.ts"],"names":[],"mappings":";;;;AAAA,qCAAuC;AACvC,mCAQgB;AAEhB;;GAEG;AACH,MAAa,eAAe;IAM1B;;;;;;;;;;;;OAYG;IACH,YACE,GAAW,EACX,EACE,OAAO,GAAG,EAAE,EACZ,WAAW,EACX,MAAM,GAAG,sBAAc,CAAC,GAAG,MAKzB,EAAE;QAEN,IAAI,CAAC,GAAG,GAAG,GAAG,CAAA;QACd,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;QACtB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,KAAK,GAAG,IAAA,qBAAY,EAAC,WAAW,CAAC,CAAA;IACxC,CAAC;IAED;;;;;;;OAOG;IACH,OAAO,CAAC,KAAa;QACnB,IAAI,CAAC,OAAO,CAAC,aAAa,GAAG,UAAU,KAAK,EAAE,CAAA;IAChD,CAAC;IAED;;;;;;;;;;OAUG;IACG,MAAM;qEACV,YAAoB,EACpB,UAAiC,EAAE;;YAEnC,IAAI,SAAoD,CAAA;YACxD,IAAI,iBAA8C,CAAA;YAElD,IAAI,CAAC;gBACH,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,YAAY,EAAE,MAAM,EAAE,OAAO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L,IAAI,EAAE,IAAI;oBACV,KAAK;oBACL,QAAQ,EACN,KAAK,YAAY,0BAAkB,IAAI,KAAK,YAAY,2BAAmB;wBACzE,CAAC,CAAC,KAAK,CAAC,OAAO;wBACf,CAAC,CAAC,SAAS;iBAChB,CAAA;YACH,CAAC;oBAAS,CAAC;gBACT,kCAAkC;gBAClC,IAAI,SAAS,EAAE,CAAC;oBACd,YAAY,CAAC,SAAS,CAAC,CAAA;gBACzB,CAAC;YACH,CAAC;QACH,CAAC;KAAA;CACF;AAxLD,0CAwLC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/main/helper.d.ts b/backend/node_modules/@supabase/functions-js/dist/main/helper.d.ts new file mode 100644 index 0000000..b697a98 --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/main/helper.d.ts @@ -0,0 +1,3 @@ +import { Fetch } from './types'; +export declare const resolveFetch: (customFetch?: Fetch) => Fetch; +//# sourceMappingURL=helper.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/main/helper.d.ts.map b/backend/node_modules/@supabase/functions-js/dist/main/helper.d.ts.map new file mode 100644 index 0000000..635907e --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/main/helper.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"helper.d.ts","sourceRoot":"","sources":["../../src/helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAE/B,eAAO,MAAM,YAAY,GAAI,cAAc,KAAK,KAAG,KAKlD,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/main/helper.js b/backend/node_modules/@supabase/functions-js/dist/main/helper.js new file mode 100644 index 0000000..24e1b58 --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/main/helper.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.resolveFetch = void 0; +const resolveFetch = (customFetch) => { + if (customFetch) { + return (...args) => customFetch(...args); + } + return (...args) => fetch(...args); +}; +exports.resolveFetch = resolveFetch; +//# sourceMappingURL=helper.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/main/helper.js.map b/backend/node_modules/@supabase/functions-js/dist/main/helper.js.map new file mode 100644 index 0000000..5ced9a6 --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/main/helper.js.map @@ -0,0 +1 @@ +{"version":3,"file":"helper.js","sourceRoot":"","sources":["../../src/helper.ts"],"names":[],"mappings":";;;AAEO,MAAM,YAAY,GAAG,CAAC,WAAmB,EAAS,EAAE;IACzD,IAAI,WAAW,EAAE,CAAC;QAChB,OAAO,CAAC,GAAG,IAAI,EAAE,EAAE,CAAC,WAAW,CAAC,GAAG,IAAI,CAAC,CAAA;IAC1C,CAAC;IACD,OAAO,CAAC,GAAG,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,CAAA;AACpC,CAAC,CAAA;AALY,QAAA,YAAY,gBAKxB"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/main/index.d.ts b/backend/node_modules/@supabase/functions-js/dist/main/index.d.ts new file mode 100644 index 0000000..9c301ef --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/main/index.d.ts @@ -0,0 +1,3 @@ +export { FunctionsClient } from './FunctionsClient'; +export { type FunctionInvokeOptions, FunctionsError, FunctionsFetchError, FunctionsHttpError, FunctionsRelayError, FunctionRegion, type FunctionsResponse, } from './types'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/main/index.d.ts.map b/backend/node_modules/@supabase/functions-js/dist/main/index.d.ts.map new file mode 100644 index 0000000..ecd7486 --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/main/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AACnD,OAAO,EACL,KAAK,qBAAqB,EAC1B,cAAc,EACd,mBAAmB,EACnB,kBAAkB,EAClB,mBAAmB,EACnB,cAAc,EACd,KAAK,iBAAiB,GACvB,MAAM,SAAS,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/main/index.js b/backend/node_modules/@supabase/functions-js/dist/main/index.js new file mode 100644 index 0000000..2cdb2fa --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/main/index.js @@ -0,0 +1,12 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FunctionRegion = exports.FunctionsRelayError = exports.FunctionsHttpError = exports.FunctionsFetchError = exports.FunctionsError = exports.FunctionsClient = void 0; +var FunctionsClient_1 = require("./FunctionsClient"); +Object.defineProperty(exports, "FunctionsClient", { enumerable: true, get: function () { return FunctionsClient_1.FunctionsClient; } }); +var types_1 = require("./types"); +Object.defineProperty(exports, "FunctionsError", { enumerable: true, get: function () { return types_1.FunctionsError; } }); +Object.defineProperty(exports, "FunctionsFetchError", { enumerable: true, get: function () { return types_1.FunctionsFetchError; } }); +Object.defineProperty(exports, "FunctionsHttpError", { enumerable: true, get: function () { return types_1.FunctionsHttpError; } }); +Object.defineProperty(exports, "FunctionsRelayError", { enumerable: true, get: function () { return types_1.FunctionsRelayError; } }); +Object.defineProperty(exports, "FunctionRegion", { enumerable: true, get: function () { return types_1.FunctionRegion; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/main/index.js.map b/backend/node_modules/@supabase/functions-js/dist/main/index.js.map new file mode 100644 index 0000000..bf37337 --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/main/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAAA,qDAAmD;AAA1C,kHAAA,eAAe,OAAA;AACxB,iCAQgB;AANd,uGAAA,cAAc,OAAA;AACd,4GAAA,mBAAmB,OAAA;AACnB,2GAAA,kBAAkB,OAAA;AAClB,4GAAA,mBAAmB,OAAA;AACnB,uGAAA,cAAc,OAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/main/types.d.ts b/backend/node_modules/@supabase/functions-js/dist/main/types.d.ts new file mode 100644 index 0000000..c5423f5 --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/main/types.d.ts @@ -0,0 +1,117 @@ +export type Fetch = typeof fetch; +/** + * Response format + */ +export interface FunctionsResponseSuccess { + data: T; + error: null; + response?: Response; +} +export interface FunctionsResponseFailure { + data: null; + error: any; + response?: Response; +} +export type FunctionsResponse = FunctionsResponseSuccess | FunctionsResponseFailure; +/** + * Base error for Supabase Edge Function invocations. + * + * @example + * ```ts + * import { FunctionsError } from '@supabase/functions-js' + * + * throw new FunctionsError('Unexpected error invoking function', 'FunctionsError', { + * requestId: 'abc123', + * }) + * ``` + */ +export declare class FunctionsError extends Error { + context: any; + constructor(message: string, name?: string, context?: any); +} +/** + * Error thrown when the network request to an Edge Function fails. + * + * @example + * ```ts + * import { FunctionsFetchError } from '@supabase/functions-js' + * + * throw new FunctionsFetchError({ requestId: 'abc123' }) + * ``` + */ +export declare class FunctionsFetchError extends FunctionsError { + constructor(context: any); +} +/** + * Error thrown when the Supabase relay cannot reach the Edge Function. + * + * @example + * ```ts + * import { FunctionsRelayError } from '@supabase/functions-js' + * + * throw new FunctionsRelayError({ region: 'us-east-1' }) + * ``` + */ +export declare class FunctionsRelayError extends FunctionsError { + constructor(context: any); +} +/** + * Error thrown when the Edge Function returns a non-2xx status code. + * + * @example + * ```ts + * import { FunctionsHttpError } from '@supabase/functions-js' + * + * throw new FunctionsHttpError({ status: 500 }) + * ``` + */ +export declare class FunctionsHttpError extends FunctionsError { + constructor(context: any); +} +export declare enum FunctionRegion { + Any = "any", + ApNortheast1 = "ap-northeast-1", + ApNortheast2 = "ap-northeast-2", + ApSouth1 = "ap-south-1", + ApSoutheast1 = "ap-southeast-1", + ApSoutheast2 = "ap-southeast-2", + CaCentral1 = "ca-central-1", + EuCentral1 = "eu-central-1", + EuWest1 = "eu-west-1", + EuWest2 = "eu-west-2", + EuWest3 = "eu-west-3", + SaEast1 = "sa-east-1", + UsEast1 = "us-east-1", + UsWest1 = "us-west-1", + UsWest2 = "us-west-2" +} +export type FunctionInvokeOptions = { + /** + * Object representing the headers to send with the request. + */ + headers?: { + [key: string]: string; + }; + /** + * The HTTP verb of the request + */ + method?: 'POST' | 'GET' | 'PUT' | 'PATCH' | 'DELETE'; + /** + * The Region to invoke the function in. + */ + region?: FunctionRegion; + /** + * The body of the request. + */ + body?: File | Blob | ArrayBuffer | FormData | ReadableStream | Record | string; + /** + * The AbortSignal to use for the request. + * */ + signal?: AbortSignal; + /** + * The timeout for the request in milliseconds. + * If the function takes longer than this, the request will be aborted. + * */ + timeout?: number; +}; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/main/types.d.ts.map b/backend/node_modules/@supabase/functions-js/dist/main/types.d.ts.map new file mode 100644 index 0000000..9409578 --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/main/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,KAAK,GAAG,OAAO,KAAK,CAAA;AAEhC;;GAEG;AACH,MAAM,WAAW,wBAAwB,CAAC,CAAC;IACzC,IAAI,EAAE,CAAC,CAAA;IACP,KAAK,EAAE,IAAI,CAAA;IACX,QAAQ,CAAC,EAAE,QAAQ,CAAA;CACpB;AACD,MAAM,WAAW,wBAAwB;IACvC,IAAI,EAAE,IAAI,CAAA;IACV,KAAK,EAAE,GAAG,CAAA;IACV,QAAQ,CAAC,EAAE,QAAQ,CAAA;CACpB;AACD,MAAM,MAAM,iBAAiB,CAAC,CAAC,IAAI,wBAAwB,CAAC,CAAC,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AAC,EAAE,WAAW,CAAA;IACpB;;;SAGK;IACL,OAAO,CAAC,EAAE,MAAM,CAAA;CACjB,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/main/types.js b/backend/node_modules/@supabase/functions-js/dist/main/types.js new file mode 100644 index 0000000..73a4866 --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/main/types.js @@ -0,0 +1,91 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FunctionRegion = exports.FunctionsHttpError = exports.FunctionsRelayError = exports.FunctionsFetchError = exports.FunctionsError = void 0; +/** + * Base error for Supabase Edge Function invocations. + * + * @example + * ```ts + * import { FunctionsError } from '@supabase/functions-js' + * + * throw new FunctionsError('Unexpected error invoking function', 'FunctionsError', { + * requestId: 'abc123', + * }) + * ``` + */ +class FunctionsError extends Error { + constructor(message, name = 'FunctionsError', context) { + super(message); + this.name = name; + this.context = context; + } +} +exports.FunctionsError = FunctionsError; +/** + * Error thrown when the network request to an Edge Function fails. + * + * @example + * ```ts + * import { FunctionsFetchError } from '@supabase/functions-js' + * + * throw new FunctionsFetchError({ requestId: 'abc123' }) + * ``` + */ +class FunctionsFetchError extends FunctionsError { + constructor(context) { + super('Failed to send a request to the Edge Function', 'FunctionsFetchError', context); + } +} +exports.FunctionsFetchError = FunctionsFetchError; +/** + * Error thrown when the Supabase relay cannot reach the Edge Function. + * + * @example + * ```ts + * import { FunctionsRelayError } from '@supabase/functions-js' + * + * throw new FunctionsRelayError({ region: 'us-east-1' }) + * ``` + */ +class FunctionsRelayError extends FunctionsError { + constructor(context) { + super('Relay Error invoking the Edge Function', 'FunctionsRelayError', context); + } +} +exports.FunctionsRelayError = FunctionsRelayError; +/** + * Error thrown when the Edge Function returns a non-2xx status code. + * + * @example + * ```ts + * import { FunctionsHttpError } from '@supabase/functions-js' + * + * throw new FunctionsHttpError({ status: 500 }) + * ``` + */ +class FunctionsHttpError extends FunctionsError { + constructor(context) { + super('Edge Function returned a non-2xx status code', 'FunctionsHttpError', context); + } +} +exports.FunctionsHttpError = FunctionsHttpError; +// Define the enum for the 'region' property +var FunctionRegion; +(function (FunctionRegion) { + FunctionRegion["Any"] = "any"; + FunctionRegion["ApNortheast1"] = "ap-northeast-1"; + FunctionRegion["ApNortheast2"] = "ap-northeast-2"; + FunctionRegion["ApSouth1"] = "ap-south-1"; + FunctionRegion["ApSoutheast1"] = "ap-southeast-1"; + FunctionRegion["ApSoutheast2"] = "ap-southeast-2"; + FunctionRegion["CaCentral1"] = "ca-central-1"; + FunctionRegion["EuCentral1"] = "eu-central-1"; + FunctionRegion["EuWest1"] = "eu-west-1"; + FunctionRegion["EuWest2"] = "eu-west-2"; + FunctionRegion["EuWest3"] = "eu-west-3"; + FunctionRegion["SaEast1"] = "sa-east-1"; + FunctionRegion["UsEast1"] = "us-east-1"; + FunctionRegion["UsWest1"] = "us-west-1"; + FunctionRegion["UsWest2"] = "us-west-2"; +})(FunctionRegion || (exports.FunctionRegion = FunctionRegion = {})); +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/main/types.js.map b/backend/node_modules/@supabase/functions-js/dist/main/types.js.map new file mode 100644 index 0000000..519fa2e --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/main/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":";;;AAiBA;;;;;;;;;;;GAWG;AACH,MAAa,cAAe,SAAQ,KAAK;IAEvC,YAAY,OAAe,EAAE,IAAI,GAAG,gBAAgB,EAAE,OAAa;QACjE,KAAK,CAAC,OAAO,CAAC,CAAA;QACd,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;QAChB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;IACxB,CAAC;CACF;AAPD,wCAOC;AAED;;;;;;;;;GASG;AACH,MAAa,mBAAoB,SAAQ,cAAc;IACrD,YAAY,OAAY;QACtB,KAAK,CAAC,+CAA+C,EAAE,qBAAqB,EAAE,OAAO,CAAC,CAAA;IACxF,CAAC;CACF;AAJD,kDAIC;AAED;;;;;;;;;GASG;AACH,MAAa,mBAAoB,SAAQ,cAAc;IACrD,YAAY,OAAY;QACtB,KAAK,CAAC,wCAAwC,EAAE,qBAAqB,EAAE,OAAO,CAAC,CAAA;IACjF,CAAC;CACF;AAJD,kDAIC;AAED;;;;;;;;;GASG;AACH,MAAa,kBAAmB,SAAQ,cAAc;IACpD,YAAY,OAAY;QACtB,KAAK,CAAC,8CAA8C,EAAE,oBAAoB,EAAE,OAAO,CAAC,CAAA;IACtF,CAAC;CACF;AAJD,gDAIC;AACD,4CAA4C;AAC5C,IAAY,cAgBX;AAhBD,WAAY,cAAc;IACxB,6BAAW,CAAA;IACX,iDAA+B,CAAA;IAC/B,iDAA+B,CAAA;IAC/B,yCAAuB,CAAA;IACvB,iDAA+B,CAAA;IAC/B,iDAA+B,CAAA;IAC/B,6CAA2B,CAAA;IAC3B,6CAA2B,CAAA;IAC3B,uCAAqB,CAAA;IACrB,uCAAqB,CAAA;IACrB,uCAAqB,CAAA;IACrB,uCAAqB,CAAA;IACrB,uCAAqB,CAAA;IACrB,uCAAqB,CAAA;IACrB,uCAAqB,CAAA;AACvB,CAAC,EAhBW,cAAc,8BAAd,cAAc,QAgBzB"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/main/version.d.ts b/backend/node_modules/@supabase/functions-js/dist/main/version.d.ts new file mode 100644 index 0000000..da11aac --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/main/version.d.ts @@ -0,0 +1,2 @@ +export declare const version = "2.87.1"; +//# sourceMappingURL=version.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/main/version.d.ts.map b/backend/node_modules/@supabase/functions-js/dist/main/version.d.ts.map new file mode 100644 index 0000000..0f6a672 --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/main/version.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,OAAO,WAAW,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/main/version.js b/backend/node_modules/@supabase/functions-js/dist/main/version.js new file mode 100644 index 0000000..31bcb0a --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/main/version.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.version = void 0; +// Generated automatically during releases by scripts/update-version-files.ts +// This file provides runtime access to the package version for: +// - HTTP request headers (e.g., X-Client-Info header for API requests) +// - Debugging and support (identifying which version is running) +// - Telemetry and logging (version reporting in errors/analytics) +// - Ensuring build artifacts match the published package version +exports.version = '2.87.1'; +//# sourceMappingURL=version.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/main/version.js.map b/backend/node_modules/@supabase/functions-js/dist/main/version.js.map new file mode 100644 index 0000000..de7f383 --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/main/version.js.map @@ -0,0 +1 @@ +{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":";;;AAAA,6EAA6E;AAC7E,gEAAgE;AAChE,uEAAuE;AACvE,iEAAiE;AACjE,kEAAkE;AAClE,iEAAiE;AACpD,QAAA,OAAO,GAAG,QAAQ,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/module/FunctionsClient.d.ts b/backend/node_modules/@supabase/functions-js/dist/module/FunctionsClient.d.ts new file mode 100644 index 0000000..ff81f03 --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/module/FunctionsClient.d.ts @@ -0,0 +1,50 @@ +import { Fetch, FunctionInvokeOptions, FunctionRegion, FunctionsResponse } from './types'; +/** + * Client for invoking Supabase Edge Functions. + */ +export declare class FunctionsClient { + protected url: string; + protected headers: Record; + protected region: FunctionRegion; + protected fetch: Fetch; + /** + * Creates a new Functions client bound to an Edge Functions URL. + * + * @example + * ```ts + * import { FunctionsClient, FunctionRegion } from '@supabase/functions-js' + * + * const functions = new FunctionsClient('https://xyzcompany.supabase.co/functions/v1', { + * headers: { apikey: 'public-anon-key' }, + * region: FunctionRegion.UsEast1, + * }) + * ``` + */ + constructor(url: string, { headers, customFetch, region, }?: { + headers?: Record; + customFetch?: Fetch; + region?: FunctionRegion; + }); + /** + * Updates the authorization header + * @param token - the new jwt token sent in the authorisation header + * @example + * ```ts + * functions.setAuth(session.access_token) + * ``` + */ + setAuth(token: string): void; + /** + * Invokes a function + * @param functionName - The name of the Function to invoke. + * @param options - Options for invoking the Function. + * @example + * ```ts + * const { data, error } = await functions.invoke('hello-world', { + * body: { name: 'Ada' }, + * }) + * ``` + */ + invoke(functionName: string, options?: FunctionInvokeOptions): Promise>; +} +//# sourceMappingURL=FunctionsClient.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/module/FunctionsClient.d.ts.map b/backend/node_modules/@supabase/functions-js/dist/module/FunctionsClient.d.ts.map new file mode 100644 index 0000000..ac8158f --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/module/FunctionsClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"FunctionsClient.d.ts","sourceRoot":"","sources":["../../src/FunctionsClient.ts"],"names":[],"mappings":"AACA,OAAO,EACL,KAAK,EACL,qBAAqB,EACrB,cAAc,EAId,iBAAiB,EAClB,MAAM,SAAS,CAAA;AAEhB;;GAEG;AACH,qBAAa,eAAe;IAC1B,SAAS,CAAC,GAAG,EAAE,MAAM,CAAA;IACrB,SAAS,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IACzC,SAAS,CAAC,MAAM,EAAE,cAAc,CAAA;IAChC,SAAS,CAAC,KAAK,EAAE,KAAK,CAAA;IAEtB;;;;;;;;;;;;OAYG;gBAED,GAAG,EAAE,MAAM,EACX,EACE,OAAY,EACZ,WAAW,EACX,MAA2B,GAC5B,GAAE;QACD,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;QAChC,WAAW,CAAC,EAAE,KAAK,CAAA;QACnB,MAAM,CAAC,EAAE,cAAc,CAAA;KACnB;IAQR;;;;;;;OAOG;IACH,OAAO,CAAC,KAAK,EAAE,MAAM;IAIrB;;;;;;;;;;OAUG;IACG,MAAM,CAAC,CAAC,GAAG,GAAG,EAClB,YAAY,EAAE,MAAM,EACpB,OAAO,GAAE,qBAA0B,GAClC,OAAO,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC;CAyHjC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/module/FunctionsClient.js b/backend/node_modules/@supabase/functions-js/dist/module/FunctionsClient.js new file mode 100644 index 0000000..88758cf --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/module/FunctionsClient.js @@ -0,0 +1,170 @@ +import { __awaiter } from "tslib"; +import { resolveFetch } from './helper'; +import { FunctionRegion, FunctionsFetchError, FunctionsHttpError, FunctionsRelayError, } from './types'; +/** + * Client for invoking Supabase Edge Functions. + */ +export class FunctionsClient { + /** + * Creates a new Functions client bound to an Edge Functions URL. + * + * @example + * ```ts + * import { FunctionsClient, FunctionRegion } from '@supabase/functions-js' + * + * const functions = new FunctionsClient('https://xyzcompany.supabase.co/functions/v1', { + * headers: { apikey: 'public-anon-key' }, + * region: FunctionRegion.UsEast1, + * }) + * ``` + */ + constructor(url, { headers = {}, customFetch, region = FunctionRegion.Any, } = {}) { + this.url = url; + this.headers = headers; + this.region = region; + this.fetch = resolveFetch(customFetch); + } + /** + * Updates the authorization header + * @param token - the new jwt token sent in the authorisation header + * @example + * ```ts + * functions.setAuth(session.access_token) + * ``` + */ + setAuth(token) { + this.headers.Authorization = `Bearer ${token}`; + } + /** + * Invokes a function + * @param functionName - The name of the Function to invoke. + * @param options - Options for invoking the Function. + * @example + * ```ts + * const { data, error } = await functions.invoke('hello-world', { + * body: { name: 'Ada' }, + * }) + * ``` + */ + invoke(functionName_1) { + return __awaiter(this, arguments, void 0, function* (functionName, options = {}) { + var _a; + let timeoutId; + let timeoutController; + try { + const { headers, method, body: functionArgs, signal, timeout } = options; + let _headers = {}; + let { region } = options; + if (!region) { + region = this.region; + } + // Add region as query parameter using URL API + const url = new URL(`${this.url}/${functionName}`); + if (region && region !== 'any') { + _headers['x-region'] = region; + url.searchParams.set('forceFunctionRegion', region); + } + let body; + if (functionArgs && + ((headers && !Object.prototype.hasOwnProperty.call(headers, 'Content-Type')) || !headers)) { + if ((typeof Blob !== 'undefined' && functionArgs instanceof Blob) || + functionArgs instanceof ArrayBuffer) { + // will work for File as File inherits Blob + // also works for ArrayBuffer as it is the same underlying structure as a Blob + _headers['Content-Type'] = 'application/octet-stream'; + body = functionArgs; + } + else if (typeof functionArgs === 'string') { + // plain string + _headers['Content-Type'] = 'text/plain'; + body = functionArgs; + } + else if (typeof FormData !== 'undefined' && functionArgs instanceof FormData) { + // don't set content-type headers + // Request will automatically add the right boundary value + body = functionArgs; + } + else { + // default, assume this is JSON + _headers['Content-Type'] = 'application/json'; + body = JSON.stringify(functionArgs); + } + } + else { + // if the Content-Type was supplied, simply set the body + body = functionArgs; + } + // Handle timeout by creating an AbortController + let effectiveSignal = signal; + if (timeout) { + timeoutController = new AbortController(); + timeoutId = setTimeout(() => timeoutController.abort(), timeout); + // If user provided their own signal, we need to respect both + if (signal) { + effectiveSignal = timeoutController.signal; + // If the user's signal is aborted, abort our timeout controller too + signal.addEventListener('abort', () => timeoutController.abort()); + } + else { + effectiveSignal = timeoutController.signal; + } + } + const response = yield this.fetch(url.toString(), { + method: method || 'POST', + // headers priority is (high to low): + // 1. invoke-level headers + // 2. client-level headers + // 3. default Content-Type header + headers: Object.assign(Object.assign(Object.assign({}, _headers), this.headers), headers), + body, + signal: effectiveSignal, + }).catch((fetchError) => { + throw new FunctionsFetchError(fetchError); + }); + const isRelayError = response.headers.get('x-relay-error'); + if (isRelayError && isRelayError === 'true') { + throw new FunctionsRelayError(response); + } + if (!response.ok) { + throw new FunctionsHttpError(response); + } + let responseType = ((_a = response.headers.get('Content-Type')) !== null && _a !== void 0 ? _a : 'text/plain').split(';')[0].trim(); + let data; + if (responseType === 'application/json') { + data = yield response.json(); + } + else if (responseType === 'application/octet-stream' || + responseType === 'application/pdf') { + data = yield response.blob(); + } + else if (responseType === 'text/event-stream') { + data = response; + } + else if (responseType === 'multipart/form-data') { + data = yield response.formData(); + } + else { + // default to text + data = yield response.text(); + } + return { data, error: null, response }; + } + catch (error) { + return { + data: null, + error, + response: error instanceof FunctionsHttpError || error instanceof FunctionsRelayError + ? error.context + : undefined, + }; + } + finally { + // Clear the timeout if it was set + if (timeoutId) { + clearTimeout(timeoutId); + } + } + }); + } +} +//# sourceMappingURL=FunctionsClient.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/module/FunctionsClient.js.map b/backend/node_modules/@supabase/functions-js/dist/module/FunctionsClient.js.map new file mode 100644 index 0000000..144a371 --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/module/FunctionsClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"FunctionsClient.js","sourceRoot":"","sources":["../../src/FunctionsClient.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAA;AACvC,OAAO,EAGL,cAAc,EACd,mBAAmB,EACnB,kBAAkB,EAClB,mBAAmB,GAEpB,MAAM,SAAS,CAAA;AAEhB;;GAEG;AACH,MAAM,OAAO,eAAe;IAM1B;;;;;;;;;;;;OAYG;IACH,YACE,GAAW,EACX,EACE,OAAO,GAAG,EAAE,EACZ,WAAW,EACX,MAAM,GAAG,cAAc,CAAC,GAAG,MAKzB,EAAE;QAEN,IAAI,CAAC,GAAG,GAAG,GAAG,CAAA;QACd,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;QACtB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC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C;oBAChD,IAAI,GAAG,QAAQ,CAAA;gBACjB,CAAC;qBAAM,IAAI,YAAY,KAAK,qBAAqB,EAAE,CAAC;oBAClD,IAAI,GAAG,MAAM,QAAQ,CAAC,QAAQ,EAAE,CAAA;gBAClC,CAAC;qBAAM,CAAC;oBACN,kBAAkB;oBAClB,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAA;gBAC9B,CAAC;gBAED,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAA;YACxC,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,OAAO;oBACL,IAAI,EAAE,IAAI;oBACV,KAAK;oBACL,QAAQ,EACN,KAAK,YAAY,kBAAkB,IAAI,KAAK,YAAY,mBAAmB;wBACzE,CAAC,CAAC,KAAK,CAAC,OAAO;wBACf,CAAC,CAAC,SAAS;iBAChB,CAAA;YACH,CAAC;oBAAS,CAAC;gBACT,kCAAkC;gBAClC,IAAI,SAAS,EAAE,CAAC;oBACd,YAAY,CAAC,SAAS,CAAC,CAAA;gBACzB,CAAC;YACH,CAAC;QACH,CAAC;KAAA;CACF"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/module/helper.d.ts b/backend/node_modules/@supabase/functions-js/dist/module/helper.d.ts new file mode 100644 index 0000000..b697a98 --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/module/helper.d.ts @@ -0,0 +1,3 @@ +import { Fetch } from './types'; +export declare const resolveFetch: (customFetch?: Fetch) => Fetch; +//# sourceMappingURL=helper.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/module/helper.d.ts.map b/backend/node_modules/@supabase/functions-js/dist/module/helper.d.ts.map new file mode 100644 index 0000000..635907e --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/module/helper.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"helper.d.ts","sourceRoot":"","sources":["../../src/helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAE/B,eAAO,MAAM,YAAY,GAAI,cAAc,KAAK,KAAG,KAKlD,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/module/helper.js b/backend/node_modules/@supabase/functions-js/dist/module/helper.js new file mode 100644 index 0000000..927759a --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/module/helper.js @@ -0,0 +1,7 @@ +export const resolveFetch = (customFetch) => { + if (customFetch) { + return (...args) => customFetch(...args); + } + return (...args) => fetch(...args); +}; +//# sourceMappingURL=helper.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/module/helper.js.map b/backend/node_modules/@supabase/functions-js/dist/module/helper.js.map new file mode 100644 index 0000000..560a93c --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/module/helper.js.map @@ -0,0 +1 @@ +{"version":3,"file":"helper.js","sourceRoot":"","sources":["../../src/helper.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,WAAmB,EAAS,EAAE;IACzD,IAAI,WAAW,EAAE,CAAC;QAChB,OAAO,CAAC,GAAG,IAAI,EAAE,EAAE,CAAC,WAAW,CAAC,GAAG,IAAI,CAAC,CAAA;IAC1C,CAAC;IACD,OAAO,CAAC,GAAG,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,CAAA;AACpC,CAAC,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/module/index.d.ts b/backend/node_modules/@supabase/functions-js/dist/module/index.d.ts new file mode 100644 index 0000000..9c301ef --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/module/index.d.ts @@ -0,0 +1,3 @@ +export { FunctionsClient } from './FunctionsClient'; +export { type FunctionInvokeOptions, FunctionsError, FunctionsFetchError, FunctionsHttpError, FunctionsRelayError, FunctionRegion, type FunctionsResponse, } from './types'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/module/index.d.ts.map b/backend/node_modules/@supabase/functions-js/dist/module/index.d.ts.map new file mode 100644 index 0000000..ecd7486 --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/module/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AACnD,OAAO,EACL,KAAK,qBAAqB,EAC1B,cAAc,EACd,mBAAmB,EACnB,kBAAkB,EAClB,mBAAmB,EACnB,cAAc,EACd,KAAK,iBAAiB,GACvB,MAAM,SAAS,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/module/index.js b/backend/node_modules/@supabase/functions-js/dist/module/index.js new file mode 100644 index 0000000..3a815c5 --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/module/index.js @@ -0,0 +1,3 @@ +export { FunctionsClient } from './FunctionsClient'; +export { FunctionsError, FunctionsFetchError, FunctionsHttpError, FunctionsRelayError, FunctionRegion, } from './types'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/module/index.js.map b/backend/node_modules/@supabase/functions-js/dist/module/index.js.map new file mode 100644 index 0000000..9af8c6e --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/module/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AACnD,OAAO,EAEL,cAAc,EACd,mBAAmB,EACnB,kBAAkB,EAClB,mBAAmB,EACnB,cAAc,GAEf,MAAM,SAAS,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/module/types.d.ts b/backend/node_modules/@supabase/functions-js/dist/module/types.d.ts new file mode 100644 index 0000000..c5423f5 --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/module/types.d.ts @@ -0,0 +1,117 @@ +export type Fetch = typeof fetch; +/** + * Response format + */ +export interface FunctionsResponseSuccess { + data: T; + error: null; + response?: Response; +} +export interface FunctionsResponseFailure { + data: null; + error: any; + response?: Response; +} +export type FunctionsResponse = FunctionsResponseSuccess | FunctionsResponseFailure; +/** + * Base error for Supabase Edge Function invocations. + * + * @example + * ```ts + * import { FunctionsError } from '@supabase/functions-js' + * + * throw new FunctionsError('Unexpected error invoking function', 'FunctionsError', { + * requestId: 'abc123', + * }) + * ``` + */ +export declare class FunctionsError extends Error { + context: any; + constructor(message: string, name?: string, context?: any); +} +/** + * Error thrown when the network request to an Edge Function fails. + * + * @example + * ```ts + * import { FunctionsFetchError } from '@supabase/functions-js' + * + * throw new FunctionsFetchError({ requestId: 'abc123' }) + * ``` + */ +export declare class FunctionsFetchError extends FunctionsError { + constructor(context: any); +} +/** + * Error thrown when the Supabase relay cannot reach the Edge Function. + * + * @example + * ```ts + * import { FunctionsRelayError } from '@supabase/functions-js' + * + * throw new FunctionsRelayError({ region: 'us-east-1' }) + * ``` + */ +export declare class FunctionsRelayError extends FunctionsError { + constructor(context: any); +} +/** + * Error thrown when the Edge Function returns a non-2xx status code. + * + * @example + * ```ts + * import { FunctionsHttpError } from '@supabase/functions-js' + * + * throw new FunctionsHttpError({ status: 500 }) + * ``` + */ +export declare class FunctionsHttpError extends FunctionsError { + constructor(context: any); +} +export declare enum FunctionRegion { + Any = "any", + ApNortheast1 = "ap-northeast-1", + ApNortheast2 = "ap-northeast-2", + ApSouth1 = "ap-south-1", + ApSoutheast1 = "ap-southeast-1", + ApSoutheast2 = "ap-southeast-2", + CaCentral1 = "ca-central-1", + EuCentral1 = "eu-central-1", + EuWest1 = "eu-west-1", + EuWest2 = "eu-west-2", + EuWest3 = "eu-west-3", + SaEast1 = "sa-east-1", + UsEast1 = "us-east-1", + UsWest1 = "us-west-1", + UsWest2 = "us-west-2" +} +export type FunctionInvokeOptions = { + /** + * Object representing the headers to send with the request. + */ + headers?: { + [key: string]: string; + }; + /** + * The HTTP verb of the request + */ + method?: 'POST' | 'GET' | 'PUT' | 'PATCH' | 'DELETE'; + /** + * The Region to invoke the function in. + */ + region?: FunctionRegion; + /** + * The body of the request. + */ + body?: File | Blob | ArrayBuffer | FormData | ReadableStream | Record | string; + /** + * The AbortSignal to use for the request. + * */ + signal?: AbortSignal; + /** + * The timeout for the request in milliseconds. + * If the function takes longer than this, the request will be aborted. + * */ + timeout?: number; +}; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/module/types.d.ts.map b/backend/node_modules/@supabase/functions-js/dist/module/types.d.ts.map new file mode 100644 index 0000000..9409578 --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/module/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,KAAK,GAAG,OAAO,KAAK,CAAA;AAEhC;;GAEG;AACH,MAAM,WAAW,wBAAwB,CAAC,CAAC;IACzC,IAAI,EAAE,CAAC,CAAA;IACP,KAAK,EAAE,IAAI,CAAA;IACX,QAAQ,CAAC,EAAE,QAAQ,CAAA;CACpB;AACD,MAAM,WAAW,wBAAwB;IACvC,IAAI,EAAE,IAAI,CAAA;IACV,KAAK,EAAE,GAAG,CAAA;IACV,QAAQ,CAAC,EAAE,QAAQ,CAAA;CACpB;AACD,MAAM,MAAM,iBAAiB,CAAC,CAAC,IAAI,wBAAwB,CAAC,CAAC,CAAC,GAAG,wBAAwB,CAAA;AAEzF;;;;;;;;;;;GAWG;AACH,qBAAa,cAAe,SAAQ,KAAK;IACvC,OAAO,EAAE,GAAG,CAAA;gBACA,OAAO,EAAE,MAAM,EAAE,IAAI,SAAmB,EAAE,OAAO,CAAC,EAAE,GAAG;CAKpE;AAED;;;;;;;;;GASG;AACH,qBAAa,mBAAoB,SAAQ,cAAc;gBACzC,OAAO,EAAE,GAAG;CAGzB;AAED;;;;;;;;;GASG;AACH,qBAAa,mBAAoB,SAAQ,cAAc;gBACzC,OAAO,EAAE,GAAG;CAGzB;AAED;;;;;;;;;GASG;AACH,qBAAa,kBAAmB,SAAQ,cAAc;gBACxC,OAAO,EAAE,GAAG;CAGzB;AAED,oBAAY,cAAc;IACxB,GAAG,QAAQ;IACX,YAAY,mBAAmB;IAC/B,YAAY,mBAAmB;IAC/B,QAAQ,eAAe;IACvB,YAAY,mBAAmB;IAC/B,YAAY,mBAAmB;IAC/B,UAAU,iBAAiB;IAC3B,UAAU,iBAAiB;IAC3B,OAAO,cAAc;IACrB,OAAO,cAAc;IACrB,OAAO,cAAc;IACrB,OAAO,cAAc;IACrB,OAAO,cAAc;IACrB,OAAO,cAAc;IACrB,OAAO,cAAc;CACtB;AAED,MAAM,MAAM,qBAAqB,GAAG;IAClC;;OAEG;IACH,OAAO,CAAC,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE,CAAA;IACnC;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,GAAG,KAAK,GAAG,KAAK,GAAG,OAAO,GAAG,QAAQ,CAAA;IACpD;;OAEG;IACH,MAAM,CAAC,EAAE,cAAc,CAAA;IACvB;;OAEG;IACH,IAAI,CAAC,EACD,IAAI,GACJ,IAAI,GACJ,WAAW,GACX,QAAQ,GACR,cAAc,CAAC,UAAU,CAAC,GAC1B,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GACnB,MAAM,CAAA;IACV;;SAEK;IACL,MAAM,CAAC,EAAE,WAAW,CAAA;IACpB;;;SAGK;IACL,OAAO,CAAC,EAAE,MAAM,CAAA;CACjB,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/module/types.js b/backend/node_modules/@supabase/functions-js/dist/module/types.js new file mode 100644 index 0000000..7c132a8 --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/module/types.js @@ -0,0 +1,84 @@ +/** + * Base error for Supabase Edge Function invocations. + * + * @example + * ```ts + * import { FunctionsError } from '@supabase/functions-js' + * + * throw new FunctionsError('Unexpected error invoking function', 'FunctionsError', { + * requestId: 'abc123', + * }) + * ``` + */ +export class FunctionsError extends Error { + constructor(message, name = 'FunctionsError', context) { + super(message); + this.name = name; + this.context = context; + } +} +/** + * Error thrown when the network request to an Edge Function fails. + * + * @example + * ```ts + * import { FunctionsFetchError } from '@supabase/functions-js' + * + * throw new FunctionsFetchError({ requestId: 'abc123' }) + * ``` + */ +export class FunctionsFetchError extends FunctionsError { + constructor(context) { + super('Failed to send a request to the Edge Function', 'FunctionsFetchError', context); + } +} +/** + * Error thrown when the Supabase relay cannot reach the Edge Function. + * + * @example + * ```ts + * import { FunctionsRelayError } from '@supabase/functions-js' + * + * throw new FunctionsRelayError({ region: 'us-east-1' }) + * ``` + */ +export class FunctionsRelayError extends FunctionsError { + constructor(context) { + super('Relay Error invoking the Edge Function', 'FunctionsRelayError', context); + } +} +/** + * Error thrown when the Edge Function returns a non-2xx status code. + * + * @example + * ```ts + * import { FunctionsHttpError } from '@supabase/functions-js' + * + * throw new FunctionsHttpError({ status: 500 }) + * ``` + */ +export class FunctionsHttpError extends FunctionsError { + constructor(context) { + super('Edge Function returned a non-2xx status code', 'FunctionsHttpError', context); + } +} +// Define the enum for the 'region' property +export var FunctionRegion; +(function (FunctionRegion) { + FunctionRegion["Any"] = "any"; + FunctionRegion["ApNortheast1"] = "ap-northeast-1"; + FunctionRegion["ApNortheast2"] = "ap-northeast-2"; + FunctionRegion["ApSouth1"] = "ap-south-1"; + FunctionRegion["ApSoutheast1"] = "ap-southeast-1"; + FunctionRegion["ApSoutheast2"] = "ap-southeast-2"; + FunctionRegion["CaCentral1"] = "ca-central-1"; + FunctionRegion["EuCentral1"] = "eu-central-1"; + FunctionRegion["EuWest1"] = "eu-west-1"; + FunctionRegion["EuWest2"] = "eu-west-2"; + FunctionRegion["EuWest3"] = "eu-west-3"; + FunctionRegion["SaEast1"] = "sa-east-1"; + FunctionRegion["UsEast1"] = "us-east-1"; + FunctionRegion["UsWest1"] = "us-west-1"; + FunctionRegion["UsWest2"] = "us-west-2"; +})(FunctionRegion || (FunctionRegion = {})); +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/module/types.js.map b/backend/node_modules/@supabase/functions-js/dist/module/types.js.map new file mode 100644 index 0000000..998210b --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/module/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAiBA;;;;;;;;;;;GAWG;AACH,MAAM,OAAO,cAAe,SAAQ,KAAK;IAEvC,YAAY,OAAe,EAAE,IAAI,GAAG,gBAAgB,EAAE,OAAa;QACjE,KAAK,CAAC,OAAO,CAAC,CAAA;QACd,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;QAChB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;IACxB,CAAC;CACF;AAED;;;;;;;;;GASG;AACH,MAAM,OAAO,mBAAoB,SAAQ,cAAc;IACrD,YAAY,OAAY;QACtB,KAAK,CAAC,+CAA+C,EAAE,qBAAqB,EAAE,OAAO,CAAC,CAAA;IACxF,CAAC;CACF;AAED;;;;;;;;;GASG;AACH,MAAM,OAAO,mBAAoB,SAAQ,cAAc;IACrD,YAAY,OAAY;QACtB,KAAK,CAAC,wCAAwC,EAAE,qBAAqB,EAAE,OAAO,CAAC,CAAA;IACjF,CAAC;CACF;AAED;;;;;;;;;GASG;AACH,MAAM,OAAO,kBAAmB,SAAQ,cAAc;IACpD,YAAY,OAAY;QACtB,KAAK,CAAC,8CAA8C,EAAE,oBAAoB,EAAE,OAAO,CAAC,CAAA;IACtF,CAAC;CACF;AACD,4CAA4C;AAC5C,MAAM,CAAN,IAAY,cAgBX;AAhBD,WAAY,cAAc;IACxB,6BAAW,CAAA;IACX,iDAA+B,CAAA;IAC/B,iDAA+B,CAAA;IAC/B,yCAAuB,CAAA;IACvB,iDAA+B,CAAA;IAC/B,iDAA+B,CAAA;IAC/B,6CAA2B,CAAA;IAC3B,6CAA2B,CAAA;IAC3B,uCAAqB,CAAA;IACrB,uCAAqB,CAAA;IACrB,uCAAqB,CAAA;IACrB,uCAAqB,CAAA;IACrB,uCAAqB,CAAA;IACrB,uCAAqB,CAAA;IACrB,uCAAqB,CAAA;AACvB,CAAC,EAhBW,cAAc,KAAd,cAAc,QAgBzB"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/module/version.d.ts b/backend/node_modules/@supabase/functions-js/dist/module/version.d.ts new file mode 100644 index 0000000..da11aac --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/module/version.d.ts @@ -0,0 +1,2 @@ +export declare const version = "2.87.1"; +//# sourceMappingURL=version.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/module/version.d.ts.map b/backend/node_modules/@supabase/functions-js/dist/module/version.d.ts.map new file mode 100644 index 0000000..0f6a672 --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/module/version.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,OAAO,WAAW,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/module/version.js b/backend/node_modules/@supabase/functions-js/dist/module/version.js new file mode 100644 index 0000000..8a1c0bd --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/module/version.js @@ -0,0 +1,8 @@ +// Generated automatically during releases by scripts/update-version-files.ts +// This file provides runtime access to the package version for: +// - HTTP request headers (e.g., X-Client-Info header for API requests) +// - Debugging and support (identifying which version is running) +// - Telemetry and logging (version reporting in errors/analytics) +// - Ensuring build artifacts match the published package version +export const version = '2.87.1'; +//# sourceMappingURL=version.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/dist/module/version.js.map b/backend/node_modules/@supabase/functions-js/dist/module/version.js.map new file mode 100644 index 0000000..205161f --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/dist/module/version.js.map @@ -0,0 +1 @@ +{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,gEAAgE;AAChE,uEAAuE;AACvE,iEAAiE;AACjE,kEAAkE;AAClE,iEAAiE;AACjE,MAAM,CAAC,MAAM,OAAO,GAAG,QAAQ,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/functions-js/package.json b/backend/node_modules/@supabase/functions-js/package.json new file mode 100644 index 0000000..be26f92 --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/package.json @@ -0,0 +1,52 @@ +{ + "name": "@supabase/functions-js", + "version": "2.87.1", + "description": "JS SDK to interact with Supabase Functions.", + "main": "dist/main/index.js", + "module": "dist/module/index.js", + "types": "dist/module/index.d.ts", + "sideEffects": false, + "scripts": { + "build": "npm run build:main && npm run build:module", + "build:main": "tsc -p tsconfig.json", + "build:module": "tsc -p tsconfig.module.json", + "docs": "typedoc src/index.ts --out docs/v2", + "docs:json": "typedoc --json docs/v2/spec.json --excludeExternals src/index.ts", + "test": "jest", + "test:ci": "jest --coverage" + }, + "repository": { + "type": "git", + "url": "https://github.com/supabase/supabase-js.git", + "directory": "packages/core/functions-js" + }, + "keywords": [ + "functions", + "supabase" + ], + "author": "Supabase", + "files": [ + "dist", + "src" + ], + "license": "MIT", + "bugs": { + "url": "https://github.com/supabase/supabase-js/issues" + }, + "homepage": "https://github.com/supabase/supabase-js/tree/master/packages/core/functions-js", + "dependencies": { + "tslib": "2.8.1" + }, + "devDependencies": { + "bs-logger": "^0.2.6", + "nanoid": "^3.3.1", + "openai": "^4.52.5", + "testcontainers": "^8.5.1" + }, + "publishConfig": { + "access": "public" + }, + "engines": { + "node": ">=20.0.0" + } +} diff --git a/backend/node_modules/@supabase/functions-js/src/FunctionsClient.ts b/backend/node_modules/@supabase/functions-js/src/FunctionsClient.ts new file mode 100644 index 0000000..8e1387c --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/src/FunctionsClient.ts @@ -0,0 +1,199 @@ +import { resolveFetch } from './helper' +import { + Fetch, + FunctionInvokeOptions, + FunctionRegion, + FunctionsFetchError, + FunctionsHttpError, + FunctionsRelayError, + FunctionsResponse, +} from './types' + +/** + * Client for invoking Supabase Edge Functions. + */ +export class FunctionsClient { + protected url: string + protected headers: Record + protected region: FunctionRegion + protected fetch: Fetch + + /** + * Creates a new Functions client bound to an Edge Functions URL. + * + * @example + * ```ts + * import { FunctionsClient, FunctionRegion } from '@supabase/functions-js' + * + * const functions = new FunctionsClient('https://xyzcompany.supabase.co/functions/v1', { + * headers: { apikey: 'public-anon-key' }, + * region: FunctionRegion.UsEast1, + * }) + * ``` + */ + constructor( + url: string, + { + headers = {}, + customFetch, + region = FunctionRegion.Any, + }: { + headers?: Record + customFetch?: Fetch + region?: FunctionRegion + } = {} + ) { + this.url = url + this.headers = headers + this.region = region + this.fetch = resolveFetch(customFetch) + } + + /** + * Updates the authorization header + * @param token - the new jwt token sent in the authorisation header + * @example + * ```ts + * functions.setAuth(session.access_token) + * ``` + */ + setAuth(token: string) { + this.headers.Authorization = `Bearer ${token}` + } + + /** + * Invokes a function + * @param functionName - The name of the Function to invoke. + * @param options - Options for invoking the Function. + * @example + * ```ts + * const { data, error } = await functions.invoke('hello-world', { + * body: { name: 'Ada' }, + * }) + * ``` + */ + async invoke( + functionName: string, + options: FunctionInvokeOptions = {} + ): Promise> { + let timeoutId: ReturnType | undefined + let timeoutController: AbortController | undefined + + try { + const { headers, method, body: functionArgs, signal, timeout } = options + let _headers: Record = {} + let { region } = options + if (!region) { + region = this.region + } + // Add region as query parameter using URL API + const url = new URL(`${this.url}/${functionName}`) + if (region && region !== 'any') { + _headers['x-region'] = region + url.searchParams.set('forceFunctionRegion', region) + } + let body: any + if ( + functionArgs && + ((headers && !Object.prototype.hasOwnProperty.call(headers, 'Content-Type')) || !headers) + ) { + if ( + (typeof Blob !== 'undefined' && functionArgs instanceof Blob) || + functionArgs instanceof ArrayBuffer + ) { + // will work for File as File inherits Blob + // also works for ArrayBuffer as it is the same underlying structure as a Blob + _headers['Content-Type'] = 'application/octet-stream' + body = functionArgs + } else if (typeof functionArgs === 'string') { + // plain string + _headers['Content-Type'] = 'text/plain' + body = functionArgs + } else if (typeof FormData !== 'undefined' && functionArgs instanceof FormData) { + // don't set content-type headers + // Request will automatically add the right boundary value + body = functionArgs + } else { + // default, assume this is JSON + _headers['Content-Type'] = 'application/json' + body = JSON.stringify(functionArgs) + } + } else { + // if the Content-Type was supplied, simply set the body + body = functionArgs + } + + // Handle timeout by creating an AbortController + let effectiveSignal = signal + if (timeout) { + timeoutController = new AbortController() + timeoutId = setTimeout(() => timeoutController!.abort(), timeout) + + // If user provided their own signal, we need to respect both + if (signal) { + effectiveSignal = timeoutController.signal + // If the user's signal is aborted, abort our timeout controller too + signal.addEventListener('abort', () => timeoutController!.abort()) + } else { + effectiveSignal = timeoutController.signal + } + } + + const response = await this.fetch(url.toString(), { + method: method || 'POST', + // headers priority is (high to low): + // 1. invoke-level headers + // 2. client-level headers + // 3. default Content-Type header + headers: { ..._headers, ...this.headers, ...headers }, + body, + signal: effectiveSignal, + }).catch((fetchError) => { + throw new FunctionsFetchError(fetchError) + }) + + const isRelayError = response.headers.get('x-relay-error') + if (isRelayError && isRelayError === 'true') { + throw new FunctionsRelayError(response) + } + + if (!response.ok) { + throw new FunctionsHttpError(response) + } + + let responseType = (response.headers.get('Content-Type') ?? 'text/plain').split(';')[0].trim() + let data: any + if (responseType === 'application/json') { + data = await response.json() + } else if ( + responseType === 'application/octet-stream' || + responseType === 'application/pdf' + ) { + data = await response.blob() + } else if (responseType === 'text/event-stream') { + data = response + } else if (responseType === 'multipart/form-data') { + data = await response.formData() + } else { + // default to text + data = await response.text() + } + + return { data, error: null, response } + } catch (error) { + return { + data: null, + error, + response: + error instanceof FunctionsHttpError || error instanceof FunctionsRelayError + ? error.context + : undefined, + } + } finally { + // Clear the timeout if it was set + if (timeoutId) { + clearTimeout(timeoutId) + } + } + } +} diff --git a/backend/node_modules/@supabase/functions-js/src/edge-runtime.d.ts b/backend/node_modules/@supabase/functions-js/src/edge-runtime.d.ts new file mode 100644 index 0000000..1fefacf --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/src/edge-runtime.d.ts @@ -0,0 +1,198 @@ +declare type BeforeunloadReason = 'cpu' | 'memory' | 'wall_clock' | 'early_drop' | 'termination' + +declare interface WindowEventMap { + load: Event + unload: Event + beforeunload: CustomEvent + drain: Event +} + +// TODO(Nyannyacha): These two type defs will be provided later. + +// deno-lint-ignore no-explicit-any +type S3FsConfig = any + +// deno-lint-ignore no-explicit-any +type TmpFsConfig = any + +type OtelPropagators = 'TraceContext' | 'Baggage' +type OtelConsoleConfig = 'Ignore' | 'Capture' | 'Replace' +type OtelConfig = { + tracing_enabled?: boolean + metrics_enabled?: boolean + console?: OtelConsoleConfig + propagators?: OtelPropagators[] +} + +interface UserWorkerFetchOptions { + signal?: AbortSignal +} + +interface PermissionsOptions { + allow_all?: boolean | null + allow_env?: string[] | null + deny_env?: string[] | null + allow_net?: string[] | null + deny_net?: string[] | null + allow_ffi?: string[] | null + deny_ffi?: string[] | null + allow_read?: string[] | null + deny_read?: string[] | null + allow_run?: string[] | null + deny_run?: string[] | null + allow_sys?: string[] | null + deny_sys?: string[] | null + allow_write?: string[] | null + deny_write?: string[] | null + allow_import?: string[] | null +} + +interface UserWorkerCreateContext { + sourceMap?: boolean | null + importMapPath?: string | null + shouldBootstrapMockFnThrowError?: boolean | null + suppressEszipMigrationWarning?: boolean | null + useReadSyncFileAPI?: boolean | null + supervisor?: { + requestAbsentTimeoutMs?: number | null + } + otel?: { + [attribute: string]: string + } +} + +interface UserWorkerCreateOptions { + servicePath?: string | null + envVars?: string[][] | [string, string][] | null + noModuleCache?: boolean | null + + forceCreate?: boolean | null + allowRemoteModules?: boolean | null + customModuleRoot?: string | null + permissions?: PermissionsOptions | null + + maybeEszip?: Uint8Array | null + maybeEntrypoint?: string | null + maybeModuleCode?: string | null + + memoryLimitMb?: number | null + lowMemoryMultiplier?: number | null + workerTimeoutMs?: number | null + cpuTimeSoftLimitMs?: number | null + cpuTimeHardLimitMs?: number | null + staticPatterns?: string[] | null + + s3FsConfig?: S3FsConfig | null + tmpFsConfig?: TmpFsConfig | null + otelConfig?: OtelConfig | null + + context?: UserWorkerCreateContext | null +} + +interface HeapStatistics { + totalHeapSize: number + totalHeapSizeExecutable: number + totalPhysicalSize: number + totalAvailableSize: number + totalGlobalHandlesSize: number + usedGlobalHandlesSize: number + usedHeapSize: number + mallocedMemory: number + externalMemory: number + peakMallocedMemory: number +} + +interface RuntimeMetrics { + mainWorkerHeapStats: HeapStatistics + eventWorkerHeapStats?: HeapStatistics +} + +interface MemInfo { + total: number + free: number + available: number + buffers: number + cached: number + swapTotal: number + swapFree: number +} + +declare namespace EdgeRuntime { + export namespace ai { + function tryCleanupUnusedSession(): Promise + } + + class UserWorker { + constructor(key: string) + + fetch(request: Request, options?: UserWorkerFetchOptions): Promise + + static create(opts: UserWorkerCreateOptions): Promise + static tryCleanupIdleWorkers(timeoutMs: number): Promise + } + + export function scheduleTermination(): void + export function waitUntil(promise: Promise): Promise + export function getRuntimeMetrics(): Promise + export function applySupabaseTag(src: Request, dest: Request): void + export function systemMemoryInfo(): MemInfo + export function raiseSegfault(): void + + export { UserWorker as userWorkers } +} + +declare namespace Supabase { + export namespace ai { + interface ModelOptions { + /** + * Pool embeddings by taking their mean. Applies only for `gte-small` model + */ + mean_pool?: boolean + + /** + * Normalize the embeddings result. Applies only for `gte-small` model + */ + normalize?: boolean + + /** + * Stream response from model. Applies only for LLMs like `mistral` (default: false) + */ + stream?: boolean + + /** + * Automatically abort the request to the model after specified time (in seconds). Applies only for LLMs like `mistral` (default: 60) + */ + timeout?: number + + /** + * Mode for the inference API host. (default: 'ollama') + */ + mode?: 'ollama' | 'openaicompatible' + signal?: AbortSignal + } + + export class Session { + /** + * Create a new model session using given model + */ + constructor(model: string) + + /** + * Execute the given prompt in model session + */ + run( + prompt: + | string + | Omit, + modelOptions?: ModelOptions + ): unknown + } + } +} + +declare namespace Deno { + export namespace errors { + class WorkerRequestCancelled extends Error {} + class WorkerAlreadyRetired extends Error {} + } +} diff --git a/backend/node_modules/@supabase/functions-js/src/helper.ts b/backend/node_modules/@supabase/functions-js/src/helper.ts new file mode 100644 index 0000000..7a72ec2 --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/src/helper.ts @@ -0,0 +1,8 @@ +import { Fetch } from './types' + +export const resolveFetch = (customFetch?: Fetch): Fetch => { + if (customFetch) { + return (...args) => customFetch(...args) + } + return (...args) => fetch(...args) +} diff --git a/backend/node_modules/@supabase/functions-js/src/index.ts b/backend/node_modules/@supabase/functions-js/src/index.ts new file mode 100644 index 0000000..dfb4b78 --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/src/index.ts @@ -0,0 +1,10 @@ +export { FunctionsClient } from './FunctionsClient' +export { + type FunctionInvokeOptions, + FunctionsError, + FunctionsFetchError, + FunctionsHttpError, + FunctionsRelayError, + FunctionRegion, + type FunctionsResponse, +} from './types' diff --git a/backend/node_modules/@supabase/functions-js/src/types.ts b/backend/node_modules/@supabase/functions-js/src/types.ts new file mode 100644 index 0000000..494c3d9 --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/src/types.ts @@ -0,0 +1,138 @@ +export type Fetch = typeof fetch + +/** + * Response format + */ +export interface FunctionsResponseSuccess { + data: T + error: null + response?: Response +} +export interface FunctionsResponseFailure { + data: null + error: any + response?: Response +} +export type FunctionsResponse = FunctionsResponseSuccess | FunctionsResponseFailure + +/** + * Base error for Supabase Edge Function invocations. + * + * @example + * ```ts + * import { FunctionsError } from '@supabase/functions-js' + * + * throw new FunctionsError('Unexpected error invoking function', 'FunctionsError', { + * requestId: 'abc123', + * }) + * ``` + */ +export class FunctionsError extends Error { + context: any + constructor(message: string, name = 'FunctionsError', context?: any) { + super(message) + this.name = name + this.context = context + } +} + +/** + * Error thrown when the network request to an Edge Function fails. + * + * @example + * ```ts + * import { FunctionsFetchError } from '@supabase/functions-js' + * + * throw new FunctionsFetchError({ requestId: 'abc123' }) + * ``` + */ +export class FunctionsFetchError extends FunctionsError { + constructor(context: any) { + super('Failed to send a request to the Edge Function', 'FunctionsFetchError', context) + } +} + +/** + * Error thrown when the Supabase relay cannot reach the Edge Function. + * + * @example + * ```ts + * import { FunctionsRelayError } from '@supabase/functions-js' + * + * throw new FunctionsRelayError({ region: 'us-east-1' }) + * ``` + */ +export class FunctionsRelayError extends FunctionsError { + constructor(context: any) { + super('Relay Error invoking the Edge Function', 'FunctionsRelayError', context) + } +} + +/** + * Error thrown when the Edge Function returns a non-2xx status code. + * + * @example + * ```ts + * import { FunctionsHttpError } from '@supabase/functions-js' + * + * throw new FunctionsHttpError({ status: 500 }) + * ``` + */ +export class FunctionsHttpError extends FunctionsError { + constructor(context: any) { + super('Edge Function returned a non-2xx status code', 'FunctionsHttpError', context) + } +} +// Define the enum for the 'region' property +export enum FunctionRegion { + Any = 'any', + ApNortheast1 = 'ap-northeast-1', + ApNortheast2 = 'ap-northeast-2', + ApSouth1 = 'ap-south-1', + ApSoutheast1 = 'ap-southeast-1', + ApSoutheast2 = 'ap-southeast-2', + CaCentral1 = 'ca-central-1', + EuCentral1 = 'eu-central-1', + EuWest1 = 'eu-west-1', + EuWest2 = 'eu-west-2', + EuWest3 = 'eu-west-3', + SaEast1 = 'sa-east-1', + UsEast1 = 'us-east-1', + UsWest1 = 'us-west-1', + UsWest2 = 'us-west-2', +} + +export type FunctionInvokeOptions = { + /** + * Object representing the headers to send with the request. + */ + headers?: { [key: string]: string } + /** + * The HTTP verb of the request + */ + method?: 'POST' | 'GET' | 'PUT' | 'PATCH' | 'DELETE' + /** + * The Region to invoke the function in. + */ + region?: FunctionRegion + /** + * The body of the request. + */ + body?: + | File + | Blob + | ArrayBuffer + | FormData + | ReadableStream + | Record + | string + /** + * The AbortSignal to use for the request. + * */ + signal?: AbortSignal + /** + * The timeout for the request in milliseconds. + * If the function takes longer than this, the request will be aborted. + * */ + timeout?: number +} diff --git a/backend/node_modules/@supabase/functions-js/src/version.ts b/backend/node_modules/@supabase/functions-js/src/version.ts new file mode 100644 index 0000000..57a6913 --- /dev/null +++ b/backend/node_modules/@supabase/functions-js/src/version.ts @@ -0,0 +1,7 @@ +// Generated automatically during releases by scripts/update-version-files.ts +// This file provides runtime access to the package version for: +// - HTTP request headers (e.g., X-Client-Info header for API requests) +// - Debugging and support (identifying which version is running) +// - Telemetry and logging (version reporting in errors/analytics) +// - Ensuring build artifacts match the published package version +export const version = '2.87.1' diff --git a/backend/node_modules/@supabase/postgrest-js/README.md b/backend/node_modules/@supabase/postgrest-js/README.md new file mode 100644 index 0000000..01b676c --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/README.md @@ -0,0 +1,199 @@ +
+

+ + + + + Supabase Logo + + + +

Supabase PostgREST JS SDK

+ +

Isomorphic JavaScript SDK for PostgREST with an ORM-like interface.

+ +

+ Guides + · + Reference Docs + · + TypeDoc +

+

+ +
+ +[![Build](https://github.com/supabase/supabase-js/workflows/CI/badge.svg)](https://github.com/supabase/supabase-js/actions?query=branch%3Amaster) +[![Package](https://img.shields.io/npm/v/@supabase/postgrest-js)](https://www.npmjs.com/package/@supabase/postgrest-js) +[![License: MIT](https://img.shields.io/npm/l/@supabase/supabase-js)](#license) +[![pkg.pr.new](https://pkg.pr.new/badge/supabase/postgrest-js)](https://pkg.pr.new/~/supabase/postgrest-js) + +
+ +### Quick start + +Install + +```bash +npm install @supabase/postgrest-js +``` + +Usage + +```js +import { PostgrestClient } from '@supabase/postgrest-js' + +const REST_URL = 'http://localhost:3000' +const postgrest = new PostgrestClient(REST_URL) +``` + +- select(): https://supabase.com/docs/reference/javascript/select +- insert(): https://supabase.com/docs/reference/javascript/insert +- update(): https://supabase.com/docs/reference/javascript/update +- delete(): https://supabase.com/docs/reference/javascript/delete + +#### Custom `fetch` implementation + +`postgrest-js` uses the [`cross-fetch`](https://www.npmjs.com/package/cross-fetch) library to make HTTP requests, but an alternative `fetch` implementation can be provided as an option. This is most useful in environments where `cross-fetch` is not compatible, for instance Cloudflare Workers: + +```js +import { PostgrestClient } from '@supabase/postgrest-js' + +const REST_URL = 'http://localhost:3000' +const postgrest = new PostgrestClient(REST_URL, { + fetch: (...args) => fetch(...args), +}) +``` + +## Development + +This package is part of the [Supabase JavaScript monorepo](https://github.com/supabase/supabase-js). To work on this package: + +### Building + +```bash +# Complete build (from monorepo root) +npx nx build postgrest-js + +# Build with watch mode for development +npx nx build postgrest-js --watch + +# Individual build targets +npx nx build:cjs postgrest-js # CommonJS build +npx nx build:esm postgrest-js # ES Modules wrapper + +# Other useful commands +npx nx clean postgrest-js # Clean build artifacts +npx nx format postgrest-js # Format code with Prettier +npx nx lint postgrest-js # Run ESLint +npx nx type-check postgrest-js # TypeScript type checking +npx nx docs postgrest-js # Generate documentation +``` + +#### Build Outputs + +- **CommonJS (`dist/cjs/`)** - For Node.js environments + - `index.js` - Main entry point + - `index.d.ts` - TypeScript definitions +- **ES Modules (`dist/esm/`)** - For modern bundlers + - `wrapper.mjs` - ESM wrapper that imports CommonJS + +#### Special Build Setup + +Unlike other packages, postgrest-js uses a hybrid approach: + +- The main code is compiled to CommonJS +- An ESM wrapper (`wrapper.mjs`) is provided for ES Module environments +- This ensures maximum compatibility across different JavaScript environments + +The `wrapper.mjs` file simply re-exports the CommonJS build, allowing the package to work seamlessly in both CommonJS and ESM contexts. + +### Testing + +**Docker Required!** The postgrest-js tests need a local PostgreSQL database and PostgREST server running in Docker containers. + +#### Quick Start + +```bash +# Run all tests (from monorepo root) +npx nx test:ci:postgrest postgrest-js +``` + +This single command automatically: + +1. Cleans any existing test containers +2. Starts PostgreSQL database and PostgREST server in Docker +3. Waits for services to be ready +4. Runs format checking +5. Runs TypeScript type tests +6. Generates and validates TypeScript types from the database schema +7. Runs all Jest unit tests with coverage +8. Runs CommonJS and ESM smoke tests +9. Cleans up Docker containers + +#### Individual Test Commands + +```bash +# Run tests with coverage +npx nx test:run postgrest-js + +# Update test snapshots and regenerate types +npx nx test:update postgrest-js + +# Type checking only +npx nx test:types postgrest-js + +``` + +#### Test Infrastructure + +The tests use Docker Compose to spin up: + +- **PostgreSQL** - Database with test schema and dummy data +- **PostgREST** - REST API server that the client connects to + +```bash +# Manually manage test infrastructure +npx nx db:run postgrest-js # Start containers +npx nx db:clean postgrest-js # Stop and remove containers +``` + +#### What `test:update` Does + +The `test:update` command is useful when: + +- Database schema changes require updating TypeScript types +- Test snapshots need to be updated after intentional changes + +It performs these steps: + +1. Starts fresh database containers +2. **Regenerates TypeScript types** from the actual database schema +3. **Updates Jest snapshots** for all tests +4. Cleans up containers + +#### Test Types Explained + +- **Format Check** - Ensures code formatting with Prettier +- **Type Tests** - Validates TypeScript types using `tstyche` +- **Generated Types Test** - Ensures generated types match database schema +- **Unit Tests** - Jest tests covering all client functionality +- **Smoke Tests** - Basic import/require tests for CommonJS and ESM + +#### Prerequisites + +- **Docker** must be installed and running +- **Port 3000** - PostgREST server (API) +- **Port 8080** - Database schema endpoint (for type generation) + +**Note:** Unlike a full Supabase instance, this uses a minimal PostgREST setup specifically for testing the SDK. + +### Contributing + +We welcome contributions! Please see our [Contributing Guide](../../../CONTRIBUTING.md) for details on how to get started. + +For major changes or if you're unsure about something, please open an issue first to discuss your proposed changes. + +## License + +This repo is licensed under MIT License. diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestBuilder.d.ts b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestBuilder.d.ts new file mode 100644 index 0000000..b812bb9 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestBuilder.d.ts @@ -0,0 +1,85 @@ +import type { PostgrestSingleResponse, PostgrestResponseSuccess, CheckMatchingArrayTypes, MergePartialResult, IsValidResultOverride } from './types/types'; +import { ClientServerOptions, Fetch } from './types/common/common'; +import { ContainsNull } from './select-query-parser/types'; +export default abstract class PostgrestBuilder implements PromiseLike : PostgrestSingleResponse> { + protected method: 'GET' | 'HEAD' | 'POST' | 'PATCH' | 'DELETE'; + protected url: URL; + protected headers: Headers; + protected schema?: string; + protected body?: unknown; + protected shouldThrowOnError: boolean; + protected signal?: AbortSignal; + protected fetch: Fetch; + protected isMaybeSingle: boolean; + /** + * Creates a builder configured for a specific PostgREST request. + * + * @example + * ```ts + * import PostgrestQueryBuilder from '@supabase/postgrest-js' + * + * const builder = new PostgrestQueryBuilder( + * new URL('https://xyzcompany.supabase.co/rest/v1/users'), + * { headers: new Headers({ apikey: 'public-anon-key' }) } + * ) + * ``` + */ + constructor(builder: { + method: 'GET' | 'HEAD' | 'POST' | 'PATCH' | 'DELETE'; + url: URL; + headers: HeadersInit; + schema?: string; + body?: unknown; + shouldThrowOnError?: boolean; + signal?: AbortSignal; + fetch?: Fetch; + isMaybeSingle?: boolean; + }); + /** + * If there's an error with the query, throwOnError will reject the promise by + * throwing the error instead of returning it as part of a successful response. + * + * {@link https://github.com/supabase/supabase-js/issues/92} + */ + throwOnError(): this & PostgrestBuilder; + /** + * Set an HTTP header for the request. + */ + setHeader(name: string, value: string): this; + then : PostgrestSingleResponse, TResult2 = never>(onfulfilled?: ((value: ThrowOnError extends true ? PostgrestResponseSuccess : PostgrestSingleResponse) => TResult1 | PromiseLike) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null): PromiseLike; + /** + * Override the type of the returned `data`. + * + * @typeParam NewResult - The new result type to override with + * @deprecated Use overrideTypes() method at the end of your call chain instead + */ + returns(): PostgrestBuilder, ThrowOnError>; + /** + * Override the type of the returned `data` field in the response. + * + * @typeParam NewResult - The new type to cast the response data to + * @typeParam Options - Optional type configuration (defaults to { merge: true }) + * @typeParam Options.merge - When true, merges the new type with existing return type. When false, replaces the existing types entirely (defaults to true) + * @example + * ```typescript + * // Merge with existing types (default behavior) + * const query = supabase + * .from('users') + * .select() + * .overrideTypes<{ custom_field: string }>() + * + * // Replace existing types completely + * const replaceQuery = supabase + * .from('users') + * .select() + * .overrideTypes<{ id: number; name: string }, { merge: false }>() + * ``` + * @returns A PostgrestBuilder instance with the new type + */ + overrideTypes(): PostgrestBuilder extends true ? ContainsNull extends true ? MergePartialResult, Options> | null : MergePartialResult : CheckMatchingArrayTypes, ThrowOnError>; +} +//# sourceMappingURL=PostgrestBuilder.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestBuilder.d.ts.map b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestBuilder.d.ts.map new file mode 100644 index 0000000..e517453 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestBuilder.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"PostgrestBuilder.d.ts","sourceRoot":"","sources":["../../src/PostgrestBuilder.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,uBAAuB,EACvB,wBAAwB,EACxB,uBAAuB,EACvB,kBAAkB,EAClB,qBAAqB,EACtB,MAAM,eAAe,CAAA;AACtB,OAAO,EAAE,mBAAmB,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAA;AAElE,OAAO,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAA;AAE1D,MAAM,CAAC,OAAO,CAAC,QAAQ,OAAO,gBAAgB,CAC5C,aAAa,SAAS,mBAAmB,EACzC,MAAM,EACN,YAAY,SAAS,OAAO,GAAG,KAAK,CACpC,YACE,WAAW,CACT,YAAY,SAAS,IAAI,GAAG,wBAAwB,CAAC,MAAM,CAAC,GAAG,uBAAuB,CAAC,MAAM,CAAC,CAC/F;IAEH,SAAS,CAAC,MAAM,EAAE,KAAK,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,QAAQ,CAAA;IAC9D,SAAS,CAAC,GAAG,EAAE,GAAG,CAAA;IAClB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I,EACR,UAAU,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,GAAG,KAAK,QAAQ,GAAG,WAAW,CAAC,QAAQ,CAAC,CAAC,GAAG,SAAS,GAAG,IAAI,GAClF,WAAW,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAkKnC;;;;;OAKG;IACH,OAAO,CAAC,SAAS,KAAK,gBAAgB,CACpC,aAAa,EACb,uBAAuB,CAAC,MAAM,EAAE,SAAS,CAAC,EAC1C,YAAY,CACb;IASD;;;;;;;;;;;;;;;;;;;;;OAqBG;IACH,aAAa,CACX,SAAS,EACT,OAAO,SAAS;QAAE,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG;QAAE,KAAK,EAAE,IAAI,CAAA;KAAE,KAClD,gBAAgB,CACnB,aAAa,EACb,qBAAqB,CAAC,MAAM,EAAE,SAAS,EAAE,KAAK,EAAE,KAAK,CAAC,SAAS,IAAI,GAE/D,YAAY,CAAC,MAAM,CAAC,SAAS,IAAI,GAC/B,kBAAkB,CAAC,SAAS,EAAE,WAAW,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC,GAAG,IAAI,GAClE,kBAAkB,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC,GAChD,uBAAuB,CAAC,MAAM,EAAE,SAAS,CAAC,EAC9C,YAAY,CACb;CAYF"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestBuilder.js b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestBuilder.js new file mode 100644 index 0000000..d124196 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestBuilder.js @@ -0,0 +1,250 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = require("tslib"); +const PostgrestError_1 = tslib_1.__importDefault(require("./PostgrestError")); +class PostgrestBuilder { + /** + * Creates a builder configured for a specific PostgREST request. + * + * @example + * ```ts + * import PostgrestQueryBuilder from '@supabase/postgrest-js' + * + * const builder = new PostgrestQueryBuilder( + * new URL('https://xyzcompany.supabase.co/rest/v1/users'), + * { headers: new Headers({ apikey: 'public-anon-key' }) } + * ) + * ``` + */ + constructor(builder) { + var _a, _b; + this.shouldThrowOnError = false; + this.method = builder.method; + this.url = builder.url; + this.headers = new Headers(builder.headers); + this.schema = builder.schema; + this.body = builder.body; + this.shouldThrowOnError = (_a = builder.shouldThrowOnError) !== null && _a !== void 0 ? _a : false; + this.signal = builder.signal; + this.isMaybeSingle = (_b = builder.isMaybeSingle) !== null && _b !== void 0 ? _b : false; + if (builder.fetch) { + this.fetch = builder.fetch; + } + else { + this.fetch = fetch; + } + } + /** + * If there's an error with the query, throwOnError will reject the promise by + * throwing the error instead of returning it as part of a successful response. + * + * {@link https://github.com/supabase/supabase-js/issues/92} + */ + throwOnError() { + this.shouldThrowOnError = true; + return this; + } + /** + * Set an HTTP header for the request. + */ + setHeader(name, value) { + this.headers = new Headers(this.headers); + this.headers.set(name, value); + return this; + } + then(onfulfilled, onrejected) { + // https://postgrest.org/en/stable/api.html#switching-schemas + if (this.schema === undefined) { + // skip + } + else if (['GET', 'HEAD'].includes(this.method)) { + this.headers.set('Accept-Profile', this.schema); + } + else { + this.headers.set('Content-Profile', this.schema); + } + if (this.method !== 'GET' && this.method !== 'HEAD') { + this.headers.set('Content-Type', 'application/json'); + } + // NOTE: Invoke w/o `this` to avoid illegal invocation error. + // https://github.com/supabase/postgrest-js/pull/247 + const _fetch = this.fetch; + let res = _fetch(this.url.toString(), { + method: this.method, + headers: this.headers, + body: JSON.stringify(this.body), + signal: this.signal, + }).then(async (res) => { + var _a, _b, _c, _d; + let error = null; + let data = null; + let count = null; + let status = res.status; + let statusText = res.statusText; + if (res.ok) { + if (this.method !== 'HEAD') { + const body = await res.text(); + if (body === '') { + // Prefer: return=minimal + } + else if (this.headers.get('Accept') === 'text/csv') { + data = body; + } + else if (this.headers.get('Accept') && + ((_a = this.headers.get('Accept')) === null || _a === void 0 ? void 0 : _a.includes('application/vnd.pgrst.plan+text'))) { + data = body; + } + else { + data = JSON.parse(body); + } + } + const countHeader = (_b = this.headers.get('Prefer')) === null || _b === void 0 ? void 0 : _b.match(/count=(exact|planned|estimated)/); + const contentRange = (_c = res.headers.get('content-range')) === null || _c === void 0 ? void 0 : _c.split('/'); + if (countHeader && contentRange && contentRange.length > 1) { + count = parseInt(contentRange[1]); + } + // Temporary partial fix for https://github.com/supabase/postgrest-js/issues/361 + // Issue persists e.g. for `.insert([...]).select().maybeSingle()` + if (this.isMaybeSingle && this.method === 'GET' && Array.isArray(data)) { + if (data.length > 1) { + error = { + // https://github.com/PostgREST/postgrest/blob/a867d79c42419af16c18c3fb019eba8df992626f/src/PostgREST/Error.hs#L553 + code: 'PGRST116', + details: `Results contain ${data.length} rows, application/vnd.pgrst.object+json requires 1 row`, + hint: null, + message: 'JSON object requested, multiple (or no) rows returned', + }; + data = null; + count = null; + status = 406; + statusText = 'Not Acceptable'; + } + else if (data.length === 1) { + data = data[0]; + } + else { + data = null; + } + } + } + else { + const body = await res.text(); + try { + error = JSON.parse(body); + // Workaround for https://github.com/supabase/postgrest-js/issues/295 + if (Array.isArray(error) && res.status === 404) { + data = []; + error = null; + status = 200; + statusText = 'OK'; + } + } + catch (_e) { + // Workaround for https://github.com/supabase/postgrest-js/issues/295 + if (res.status === 404 && body === '') { + status = 204; + statusText = 'No Content'; + } + else { + error = { + message: body, + }; + } + } + if (error && this.isMaybeSingle && ((_d = error === null || error === void 0 ? void 0 : error.details) === null || _d === void 0 ? void 0 : _d.includes('0 rows'))) { + error = null; + status = 200; + statusText = 'OK'; + } + if (error && this.shouldThrowOnError) { + throw new PostgrestError_1.default(error); + } + } + const postgrestResponse = { + error, + data, + count, + status, + statusText, + }; + return postgrestResponse; + }); + if (!this.shouldThrowOnError) { + res = res.catch((fetchError) => { + var _a, _b, _c, _d, _e, _f; + // Build detailed error information including cause if available + // Note: We don't populate code/hint for client-side network errors since those + // fields are meant for upstream service errors (PostgREST/PostgreSQL) + let errorDetails = ''; + // Add cause information if available (e.g., DNS errors, network failures) + const cause = fetchError === null || fetchError === void 0 ? void 0 : fetchError.cause; + if (cause) { + const causeMessage = (_a = cause === null || cause === void 0 ? void 0 : cause.message) !== null && _a !== void 0 ? _a : ''; + const causeCode = (_b = cause === null || cause === void 0 ? void 0 : cause.code) !== null && _b !== void 0 ? _b : ''; + errorDetails = `${(_c = fetchError === null || fetchError === void 0 ? void 0 : fetchError.name) !== null && _c !== void 0 ? _c : 'FetchError'}: ${fetchError === null || fetchError === void 0 ? void 0 : fetchError.message}`; + errorDetails += `\n\nCaused by: ${(_d = cause === null || cause === void 0 ? void 0 : cause.name) !== null && _d !== void 0 ? _d : 'Error'}: ${causeMessage}`; + if (causeCode) { + errorDetails += ` (${causeCode})`; + } + if (cause === null || cause === void 0 ? void 0 : cause.stack) { + errorDetails += `\n${cause.stack}`; + } + } + else { + // No cause available, just include the error stack + errorDetails = (_e = fetchError === null || fetchError === void 0 ? void 0 : fetchError.stack) !== null && _e !== void 0 ? _e : ''; + } + return { + error: { + message: `${(_f = fetchError === null || fetchError === void 0 ? void 0 : fetchError.name) !== null && _f !== void 0 ? _f : 'FetchError'}: ${fetchError === null || fetchError === void 0 ? void 0 : fetchError.message}`, + details: errorDetails, + hint: '', + code: '', + }, + data: null, + count: null, + status: 0, + statusText: '', + }; + }); + } + return res.then(onfulfilled, onrejected); + } + /** + * Override the type of the returned `data`. + * + * @typeParam NewResult - The new result type to override with + * @deprecated Use overrideTypes() method at the end of your call chain instead + */ + returns() { + /* istanbul ignore next */ + return this; + } + /** + * Override the type of the returned `data` field in the response. + * + * @typeParam NewResult - The new type to cast the response data to + * @typeParam Options - Optional type configuration (defaults to { merge: true }) + * @typeParam Options.merge - When true, merges the new type with existing return type. When false, replaces the existing types entirely (defaults to true) + * @example + * ```typescript + * // Merge with existing types (default behavior) + * const query = supabase + * .from('users') + * .select() + * .overrideTypes<{ custom_field: string }>() + * + * // Replace existing types completely + * const replaceQuery = supabase + * .from('users') + * .select() + * .overrideTypes<{ id: number; name: string }, { merge: false }>() + * ``` + * @returns A PostgrestBuilder instance with the new type + */ + overrideTypes() { + return this; + } +} +exports.default = PostgrestBuilder; +//# sourceMappingURL=PostgrestBuilder.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestBuilder.js.map b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestBuilder.js.map new file mode 100644 index 0000000..d6bc7a3 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestBuilder.js.map @@ -0,0 +1 @@ +{"version":3,"file":"PostgrestBuilder.js","sourceRoot":"","sources":["../../src/PostgrestBuilder.ts"],"names":[],"mappings":";;;AAQA,8EAA6C;AAG7C,MAA8B,gBAAgB;IAmB5C;;;;;;;;;;;;OAYG;IACH,YAAY,OAUX;;QA5BS,uBAAkB,GAAG,KAAK,CAAA;QA6BlC,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAA;QAC5B,IAAI,CAAC,GAAG,GAAG,OAAO,CAAC,GAAG,CAAA;QACtB,IAAI,CAAC,OAAO,GAAG,IAAI,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,CAAA;QAC3C,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAA;QAC5B,IAAI,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAA;QACxB,IAAI,CAAC,kBAAkB,GAAG,MAAA,OAAO,CAAC,kBAAkB,mCAAI,KAAK,CAAA;QAC7D,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAA;QAC5B,IAAI,CAAC,aAAa,GAAG,MAAA,OAAO,CAAC,aAAa,mCAAI,KAAK,CAAA;QAEnD,IAAI,OAAO,CAAC,KAAK,EAAE,CAAC;YAClB,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAA;QAC5B,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,KAAK,GAAG,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,CAAC;QAED,OAAO,GAAG,CAAC,IAAI,CAAC,WAAW,EAAE,UAAU,CAAC,CAAA;IAC1C,CAAC;IAED;;;;;OAKG;IACH,OAAO;QAKL,0BAA0B;QAC1B,OAAO,IAIN,CAAA;IACH,CAAC;IAED;;;;;;;;;;;;;;;;;;;;;OAqBG;IACH,aAAa;QAaX,OAAO,IASN,CAAA;IACH,CAAC;CACF;AAjUD,mCAiUC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestClient.d.ts b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestClient.d.ts new file mode 100644 index 0000000..2de7dbc --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestClient.d.ts @@ -0,0 +1,93 @@ +import PostgrestQueryBuilder from './PostgrestQueryBuilder'; +import PostgrestFilterBuilder from './PostgrestFilterBuilder'; +import { Fetch, GenericSchema, ClientServerOptions } from './types/common/common'; +import { GetRpcFunctionFilterBuilderByArgs } from './types/common/rpc'; +/** + * PostgREST client. + * + * @typeParam Database - Types for the schema from the [type + * generator](https://supabase.com/docs/reference/javascript/next/typescript-support) + * + * @typeParam SchemaName - Postgres schema to switch to. Must be a string + * literal, the same one passed to the constructor. If the schema is not + * `"public"`, this must be supplied manually. + */ +export default class PostgrestClient = 'public' extends keyof Omit ? 'public' : string & keyof Omit, Schema extends GenericSchema = Omit[SchemaName] extends GenericSchema ? Omit[SchemaName] : any> { + url: string; + headers: Headers; + schemaName?: SchemaName; + fetch?: Fetch; + /** + * Creates a PostgREST client. + * + * @param url - URL of the PostgREST endpoint + * @param options - Named parameters + * @param options.headers - Custom headers + * @param options.schema - Postgres schema to switch to + * @param options.fetch - Custom fetch + * @example + * ```ts + * import PostgrestClient from '@supabase/postgrest-js' + * + * const postgrest = new PostgrestClient('https://xyzcompany.supabase.co/rest/v1', { + * headers: { apikey: 'public-anon-key' }, + * schema: 'public', + * }) + * ``` + */ + constructor(url: string, { headers, schema, fetch, }?: { + headers?: HeadersInit; + schema?: SchemaName; + fetch?: Fetch; + }); + from(relation: TableName): PostgrestQueryBuilder; + from(relation: ViewName): PostgrestQueryBuilder; + /** + * Select a schema to query or perform an function (rpc) call. + * + * The schema needs to be on the list of exposed schemas inside Supabase. + * + * @param schema - The schema to query + */ + schema>(schema: DynamicSchema): PostgrestClient; + /** + * Perform a function call. + * + * @param fn - The function name to call + * @param args - The arguments to pass to the function call + * @param options - Named parameters + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * @param options.get - When set to `true`, the function will be called with + * read-only access mode. + * @param options.count - Count algorithm to use to count rows returned by the + * function. Only applicable for [set-returning + * functions](https://www.postgresql.org/docs/current/functions-srf.html). + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + * + * @example + * ```ts + * // For cross-schema functions where type inference fails, use overrideTypes: + * const { data } = await supabase + * .schema('schema_b') + * .rpc('function_a', {}) + * .overrideTypes<{ id: string; user_id: string }[]>() + * ``` + */ + rpc = GetRpcFunctionFilterBuilderByArgs>(fn: FnName, args?: Args, { head, get, count, }?: { + head?: boolean; + get?: boolean; + count?: 'exact' | 'planned' | 'estimated'; + }): PostgrestFilterBuilder; +} +//# sourceMappingURL=PostgrestClient.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestClient.d.ts.map b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestClient.d.ts.map new file mode 100644 index 0000000..739773d --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"PostgrestClient.d.ts","sourceRoot":"","sources":["../../src/PostgrestClient.ts"],"names":[],"mappings":"AAAA,OAAO,qBAAqB,MAAM,yBAAyB,CAAA;AAC3D,OAAO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AAC,EACpB,aAAa,CAAC,QAAQ,CAAC,EACvB,aAAa,CAAC,cAAc,CAAC,EAC7B,aAAa,CAAC,eAAe,CAAC,EAC9B,KAAK,CACN;CAkCF"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestClient.js b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestClient.js new file mode 100644 index 0000000..c07f614 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestClient.js @@ -0,0 +1,140 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = require("tslib"); +const PostgrestQueryBuilder_1 = tslib_1.__importDefault(require("./PostgrestQueryBuilder")); +const PostgrestFilterBuilder_1 = tslib_1.__importDefault(require("./PostgrestFilterBuilder")); +/** + * PostgREST client. + * + * @typeParam Database - Types for the schema from the [type + * generator](https://supabase.com/docs/reference/javascript/next/typescript-support) + * + * @typeParam SchemaName - Postgres schema to switch to. Must be a string + * literal, the same one passed to the constructor. If the schema is not + * `"public"`, this must be supplied manually. + */ +class PostgrestClient { + // TODO: Add back shouldThrowOnError once we figure out the typings + /** + * Creates a PostgREST client. + * + * @param url - URL of the PostgREST endpoint + * @param options - Named parameters + * @param options.headers - Custom headers + * @param options.schema - Postgres schema to switch to + * @param options.fetch - Custom fetch + * @example + * ```ts + * import PostgrestClient from '@supabase/postgrest-js' + * + * const postgrest = new PostgrestClient('https://xyzcompany.supabase.co/rest/v1', { + * headers: { apikey: 'public-anon-key' }, + * schema: 'public', + * }) + * ``` + */ + constructor(url, { headers = {}, schema, fetch, } = {}) { + this.url = url; + this.headers = new Headers(headers); + this.schemaName = schema; + this.fetch = fetch; + } + /** + * Perform a query on a table or a view. + * + * @param relation - The table or view name to query + */ + from(relation) { + if (!relation || typeof relation !== 'string' || relation.trim() === '') { + throw new Error('Invalid relation name: relation must be a non-empty string.'); + } + const url = new URL(`${this.url}/${relation}`); + return new PostgrestQueryBuilder_1.default(url, { + headers: new Headers(this.headers), + schema: this.schemaName, + fetch: this.fetch, + }); + } + /** + * Select a schema to query or perform an function (rpc) call. + * + * The schema needs to be on the list of exposed schemas inside Supabase. + * + * @param schema - The schema to query + */ + schema(schema) { + return new PostgrestClient(this.url, { + headers: this.headers, + schema, + fetch: this.fetch, + }); + } + /** + * Perform a function call. + * + * @param fn - The function name to call + * @param args - The arguments to pass to the function call + * @param options - Named parameters + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * @param options.get - When set to `true`, the function will be called with + * read-only access mode. + * @param options.count - Count algorithm to use to count rows returned by the + * function. Only applicable for [set-returning + * functions](https://www.postgresql.org/docs/current/functions-srf.html). + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + * + * @example + * ```ts + * // For cross-schema functions where type inference fails, use overrideTypes: + * const { data } = await supabase + * .schema('schema_b') + * .rpc('function_a', {}) + * .overrideTypes<{ id: string; user_id: string }[]>() + * ``` + */ + rpc(fn, args = {}, { head = false, get = false, count, } = {}) { + var _a; + let method; + const url = new URL(`${this.url}/rpc/${fn}`); + let body; + if (head || get) { + method = head ? 'HEAD' : 'GET'; + Object.entries(args) + // params with undefined value needs to be filtered out, otherwise it'll + // show up as `?param=undefined` + .filter(([_, value]) => value !== undefined) + // array values need special syntax + .map(([name, value]) => [name, Array.isArray(value) ? `{${value.join(',')}}` : `${value}`]) + .forEach(([name, value]) => { + url.searchParams.append(name, value); + }); + } + else { + method = 'POST'; + body = args; + } + const headers = new Headers(this.headers); + if (count) { + headers.set('Prefer', `count=${count}`); + } + return new PostgrestFilterBuilder_1.default({ + method, + url, + headers, + schema: this.schemaName, + body, + fetch: (_a = this.fetch) !== null && _a !== void 0 ? _a : fetch, + }); + } +} +exports.default = PostgrestClient; +//# sourceMappingURL=PostgrestClient.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestClient.js.map b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestClient.js.map new file mode 100644 index 0000000..638b68b --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"PostgrestClient.js","sourceRoot":"","sources":["../../src/PostgrestClient.ts"],"names":[],"mappings":";;;AAAA,4FAA2D;AAC3D,8FAA6D;AAI7D;;;;;;;;;GASG;AACH,MAAqB,eAAe;IA0BlC,mEAAmE;IACnE;;;;;;;;;;;;;;;;;OAiBG;IACH,YACE,GAAW,EACX,EACE,OAAO,GAAG,EAAE,EACZ,MAAM,EACN,KAAK,MAKH,EAAE;QAEN,IAAI,CAAC,GAAG,GAAG,GAAG,CAAA;QACd,IAAI,CAAC,OAAO,GAAG,IAAI,OAAO,CAAC,OAAO,CAAC,CAAA;QACnC,IAAI,CAAC,UAAU,GAAG,MAAM,CAAA;QACxB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAA;IACpB,CAAC;IAQD;;;;OAIG;IACH,IAAI,CAAC,QAAgB;QACnB,IAAI,CAAC,QAAQ,IAAI,OAAO,QAAQ,KAAK,QAAQ,IAAI,QAAQ,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC;YACxE,MAAM,IAAI,KAAK,CAAC,6DAA6D,CAAC,CAAA;QAChF,CAAC;QAED,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,GAAG,IAAI,CAAC,GAAG,IAAI,QAAQ,EAAE,CAAC,CAAA;QAC9C,OAAO,IAAI,+BAAqB,CAAC,GAAG,EAAE;YACpC,OAAO,EAAE,IAAI,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC;YAClC,MAAM,EAAE,IAAI,CAAC,UAAU;YACvB,KAAK,EAAE,IAAI,CAAC,KAAK;SAClB,CAAC,CAAA;IACJ,CAAC;IAED;;;;;;OAMG;IACH,MAAM,CACJ,MAAqB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AM,GAAG,MAAM,CAAA;YACf,IAAI,GAAG,IAAI,CAAA;QACb,CAAC;QAED,MAAM,OAAO,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;QACzC,IAAI,KAAK,EAAE,CAAC;YACV,OAAO,CAAC,GAAG,CAAC,QAAQ,EAAE,SAAS,KAAK,EAAE,CAAC,CAAA;QACzC,CAAC;QAED,OAAO,IAAI,gCAAsB,CAAC;YAChC,MAAM;YACN,GAAG;YACH,OAAO;YACP,MAAM,EAAE,IAAI,CAAC,UAAU;YACvB,IAAI;YACJ,KAAK,EAAE,MAAA,IAAI,CAAC,KAAK,mCAAI,KAAK;SAC3B,CAAC,CAAA;IACJ,CAAC;CACF;AA3MD,kCA2MC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestError.d.ts b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestError.d.ts new file mode 100644 index 0000000..1a1037f --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestError.d.ts @@ -0,0 +1,30 @@ +/** + * Error format + * + * {@link https://postgrest.org/en/stable/api.html?highlight=options#errors-and-http-status-codes} + */ +export default class PostgrestError extends Error { + details: string; + hint: string; + code: string; + /** + * @example + * ```ts + * import PostgrestError from '@supabase/postgrest-js' + * + * throw new PostgrestError({ + * message: 'Row level security prevented the request', + * details: 'RLS denied the insert', + * hint: 'Check your policies', + * code: 'PGRST301', + * }) + * ``` + */ + constructor(context: { + message: string; + details: string; + hint: string; + code: string; + }); +} +//# sourceMappingURL=PostgrestError.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestError.d.ts.map b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestError.d.ts.map new file mode 100644 index 0000000..96dd30f --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestError.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"PostgrestError.d.ts","sourceRoot":"","sources":["../../src/PostgrestError.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,CAAC,OAAO,OAAO,cAAe,SAAQ,KAAK;IAC/C,OAAO,EAAE,MAAM,CAAA;IACf,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,EAAE,MAAM,CAAA;IAEZ;;;;;;;;;;;;OAYG;gBACS,OAAO,EAAE;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE;CAOtF"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestError.js b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestError.js new file mode 100644 index 0000000..f4e7ea3 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestError.js @@ -0,0 +1,31 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * Error format + * + * {@link https://postgrest.org/en/stable/api.html?highlight=options#errors-and-http-status-codes} + */ +class PostgrestError extends Error { + /** + * @example + * ```ts + * import PostgrestError from '@supabase/postgrest-js' + * + * throw new PostgrestError({ + * message: 'Row level security prevented the request', + * details: 'RLS denied the insert', + * hint: 'Check your policies', + * code: 'PGRST301', + * }) + * ``` + */ + constructor(context) { + super(context.message); + this.name = 'PostgrestError'; + this.details = context.details; + this.hint = context.hint; + this.code = context.code; + } +} +exports.default = PostgrestError; +//# sourceMappingURL=PostgrestError.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestError.js.map b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestError.js.map new file mode 100644 index 0000000..6e310b3 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestError.js.map @@ -0,0 +1 @@ +{"version":3,"file":"PostgrestError.js","sourceRoot":"","sources":["../../src/PostgrestError.ts"],"names":[],"mappings":";;AAAA;;;;GAIG;AACH,MAAqB,cAAe,SAAQ,KAAK;IAK/C;;;;;;;;;;;;OAYG;IACH,YAAY,OAAyE;QACnF,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,CAAA;QACtB,IAAI,CAAC,IAAI,GAAG,gBAAgB,CAAA;QAC5B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,CAAA;QAC9B,IAAI,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAA;QACxB,IAAI,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAA;IAC1B,CAAC;CACF;AAzBD,iCAyBC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestFilterBuilder.d.ts b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestFilterBuilder.d.ts new file mode 100644 index 0000000..bcbe267 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestFilterBuilder.d.ts @@ -0,0 +1,123 @@ +import PostgrestTransformBuilder from './PostgrestTransformBuilder'; +import { JsonPathToAccessor, JsonPathToType } from './select-query-parser/utils'; +import { ClientServerOptions, GenericSchema } from './types/common/common'; +type FilterOperator = 'eq' | 'neq' | 'gt' | 'gte' | 'lt' | 'lte' | 'like' | 'ilike' | 'is' | 'isdistinct' | 'in' | 'cs' | 'cd' | 'sl' | 'sr' | 'nxl' | 'nxr' | 'adj' | 'ov' | 'fts' | 'plfts' | 'phfts' | 'wfts' | 'match' | 'imatch'; +export type IsStringOperator = Path extends `${string}->>${string}` ? true : false; +type ResolveFilterValue, ColumnName extends string> = ColumnName extends `${infer RelationshipTable}.${infer Remainder}` ? Remainder extends `${infer _}.${infer _}` ? ResolveFilterValue : ResolveFilterRelationshipValue : ColumnName extends keyof Row ? Row[ColumnName] : IsStringOperator extends true ? string : JsonPathToType> extends infer JsonPathValue ? JsonPathValue extends never ? never : JsonPathValue : never; +type ResolveFilterRelationshipValue = Schema['Tables'] & Schema['Views'] extends infer TablesAndViews ? RelationshipTable extends keyof TablesAndViews ? 'Row' extends keyof TablesAndViews[RelationshipTable] ? RelationshipColumn extends keyof TablesAndViews[RelationshipTable]['Row'] ? TablesAndViews[RelationshipTable]['Row'][RelationshipColumn] : unknown : unknown : unknown : never; +export type InvalidMethodError = { + Error: S; +}; +export default class PostgrestFilterBuilder, Result, RelationName = unknown, Relationships = unknown, Method = unknown> extends PostgrestTransformBuilder { + /** + * Match only rows where `column` is equal to `value`. + * + * To check if the value of `column` is NULL, you should use `.is()` instead. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + eq(column: ColumnName, value: ResolveFilterValue extends never ? NonNullable : ResolveFilterValue extends infer ResolvedFilterValue ? NonNullable : never): this; + /** + * Match only rows where `column` is not equal to `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + neq(column: ColumnName, value: ResolveFilterValue extends never ? unknown : ResolveFilterValue extends infer ResolvedFilterValue ? ResolvedFilterValue : never): this; + gt(column: ColumnName, value: Row[ColumnName]): this; + gt(column: string, value: unknown): this; + gte(column: ColumnName, value: Row[ColumnName]): this; + gte(column: string, value: unknown): this; + lt(column: ColumnName, value: Row[ColumnName]): this; + lt(column: string, value: unknown): this; + lte(column: ColumnName, value: Row[ColumnName]): this; + lte(column: string, value: unknown): this; + like(column: ColumnName, pattern: string): this; + like(column: string, pattern: string): this; + likeAllOf(column: ColumnName, patterns: readonly string[]): this; + likeAllOf(column: string, patterns: readonly string[]): this; + likeAnyOf(column: ColumnName, patterns: readonly string[]): this; + likeAnyOf(column: string, patterns: readonly string[]): this; + ilike(column: ColumnName, pattern: string): this; + ilike(column: string, pattern: string): this; + ilikeAllOf(column: ColumnName, patterns: readonly string[]): this; + ilikeAllOf(column: string, patterns: readonly string[]): this; + ilikeAnyOf(column: ColumnName, patterns: readonly string[]): this; + ilikeAnyOf(column: string, patterns: readonly string[]): this; + regexMatch(column: ColumnName, pattern: string): this; + regexMatch(column: string, pattern: string): this; + regexIMatch(column: ColumnName, pattern: string): this; + regexIMatch(column: string, pattern: string): this; + is(column: ColumnName, value: Row[ColumnName] & (boolean | null)): this; + is(column: string, value: boolean | null): this; + /** + * Match only rows where `column` IS DISTINCT FROM `value`. + * + * Unlike `.neq()`, this treats `NULL` as a comparable value. Two `NULL` values + * are considered equal (not distinct), and comparing `NULL` with any non-NULL + * value returns true (distinct). + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + isDistinct(column: ColumnName, value: ResolveFilterValue extends never ? unknown : ResolveFilterValue extends infer ResolvedFilterValue ? ResolvedFilterValue : never): this; + /** + * Match only rows where `column` is included in the `values` array. + * + * @param column - The column to filter on + * @param values - The values array to filter with + */ + in(column: ColumnName, values: ReadonlyArray extends never ? unknown : ResolveFilterValue extends infer ResolvedFilterValue ? ResolvedFilterValue : never>): this; + contains(column: ColumnName, value: string | ReadonlyArray | Record): this; + contains(column: string, value: string | readonly unknown[] | Record): this; + containedBy(column: ColumnName, value: string | ReadonlyArray | Record): this; + containedBy(column: string, value: string | readonly unknown[] | Record): this; + rangeGt(column: ColumnName, range: string): this; + rangeGt(column: string, range: string): this; + rangeGte(column: ColumnName, range: string): this; + rangeGte(column: string, range: string): this; + rangeLt(column: ColumnName, range: string): this; + rangeLt(column: string, range: string): this; + rangeLte(column: ColumnName, range: string): this; + rangeLte(column: string, range: string): this; + rangeAdjacent(column: ColumnName, range: string): this; + rangeAdjacent(column: string, range: string): this; + overlaps(column: ColumnName, value: string | ReadonlyArray): this; + overlaps(column: string, value: string | readonly unknown[]): this; + textSearch(column: ColumnName, query: string, options?: { + config?: string; + type?: 'plain' | 'phrase' | 'websearch'; + }): this; + textSearch(column: string, query: string, options?: { + config?: string; + type?: 'plain' | 'phrase' | 'websearch'; + }): this; + match(query: Record): this; + match(query: Record): this; + not(column: ColumnName, operator: FilterOperator, value: Row[ColumnName]): this; + not(column: string, operator: string, value: unknown): this; + /** + * Match only rows which satisfy at least one of the filters. + * + * Unlike most filters, `filters` is used as-is and needs to follow [PostgREST + * syntax](https://postgrest.org/en/stable/api.html#operators). You also need + * to make sure it's properly sanitized. + * + * It's currently not possible to do an `.or()` filter across multiple tables. + * + * @param filters - The filters to use, following PostgREST syntax + * @param options - Named parameters + * @param options.referencedTable - Set this to filter on referenced tables + * instead of the parent table + * @param options.foreignTable - Deprecated, use `referencedTable` instead + */ + or(filters: string, { foreignTable, referencedTable, }?: { + foreignTable?: string; + referencedTable?: string; + }): this; + filter(column: ColumnName, operator: `${'' | 'not.'}${FilterOperator}`, value: unknown): this; + filter(column: string, operator: string, value: unknown): this; +} +export {}; +//# sourceMappingURL=PostgrestFilterBuilder.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestFilterBuilder.d.ts.map b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestFilterBuilder.d.ts.map new file mode 100644 index 0000000..5b285bd --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestFilterBuilder.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"PostgrestFilterBuilder.d.ts","sourceRoot":"","sources":["../../src/PostgrestFilterBuilder.ts"],"names":[],"mappings":"AAAA,OAAO,yBAAyB,MAAM,6BAA6B,CAAA;AACnE,OAAO,EAAE,kBAAkB,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAA;AAChF,OAAO,EAAE,mBAAmB,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAA;AAE1E,KAAK,cAAc,GACf,IAAI,GACJ,KAAK,GACL,IAAI,GACJ,KAAK,GACL,IAAI,GACJ,KAAK,GACL,MAAM,GACN,OAAO,GACP,IAAI,GACJ,YAAY,GACZ,IAAI,GACJ,IAAI,GACJ,IAAI,GACJ,IAAI,GACJ,IAAI,GACJ,KAAK,GACL,KAAK,GACL,KAAK,GACL,IAAI,GACJ,KAAK,GACL,OAAO,GACP,OAAO,GACP,MAAM,GACN,OAAO,GACP,QAAQ,CAAA;AAEZ,M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B,QAAQ,EAAE,GAAG,EAAE,GAAG,MAAM,GAAG,cAAc,EAAE,EAC3C,KAAK,EAAE,OAAO,GACb,IAAI;IACP,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI;CAkB/D"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestFilterBuilder.js b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestFilterBuilder.js new file mode 100644 index 0000000..3b73365 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestFilterBuilder.js @@ -0,0 +1,416 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = require("tslib"); +const PostgrestTransformBuilder_1 = tslib_1.__importDefault(require("./PostgrestTransformBuilder")); +const PostgrestReservedCharsRegexp = new RegExp('[,()]'); +class PostgrestFilterBuilder extends PostgrestTransformBuilder_1.default { + /** + * Match only rows where `column` is equal to `value`. + * + * To check if the value of `column` is NULL, you should use `.is()` instead. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + eq(column, value) { + this.url.searchParams.append(column, `eq.${value}`); + return this; + } + /** + * Match only rows where `column` is not equal to `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + neq(column, value) { + this.url.searchParams.append(column, `neq.${value}`); + return this; + } + /** + * Match only rows where `column` is greater than `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + gt(column, value) { + this.url.searchParams.append(column, `gt.${value}`); + return this; + } + /** + * Match only rows where `column` is greater than or equal to `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + gte(column, value) { + this.url.searchParams.append(column, `gte.${value}`); + return this; + } + /** + * Match only rows where `column` is less than `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + lt(column, value) { + this.url.searchParams.append(column, `lt.${value}`); + return this; + } + /** + * Match only rows where `column` is less than or equal to `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + lte(column, value) { + this.url.searchParams.append(column, `lte.${value}`); + return this; + } + /** + * Match only rows where `column` matches `pattern` case-sensitively. + * + * @param column - The column to filter on + * @param pattern - The pattern to match with + */ + like(column, pattern) { + this.url.searchParams.append(column, `like.${pattern}`); + return this; + } + /** + * Match only rows where `column` matches all of `patterns` case-sensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + likeAllOf(column, patterns) { + this.url.searchParams.append(column, `like(all).{${patterns.join(',')}}`); + return this; + } + /** + * Match only rows where `column` matches any of `patterns` case-sensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + likeAnyOf(column, patterns) { + this.url.searchParams.append(column, `like(any).{${patterns.join(',')}}`); + return this; + } + /** + * Match only rows where `column` matches `pattern` case-insensitively. + * + * @param column - The column to filter on + * @param pattern - The pattern to match with + */ + ilike(column, pattern) { + this.url.searchParams.append(column, `ilike.${pattern}`); + return this; + } + /** + * Match only rows where `column` matches all of `patterns` case-insensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + ilikeAllOf(column, patterns) { + this.url.searchParams.append(column, `ilike(all).{${patterns.join(',')}}`); + return this; + } + /** + * Match only rows where `column` matches any of `patterns` case-insensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + ilikeAnyOf(column, patterns) { + this.url.searchParams.append(column, `ilike(any).{${patterns.join(',')}}`); + return this; + } + /** + * Match only rows where `column` matches the PostgreSQL regex `pattern` + * case-sensitively (using the `~` operator). + * + * @param column - The column to filter on + * @param pattern - The PostgreSQL regular expression pattern to match with + */ + regexMatch(column, pattern) { + this.url.searchParams.append(column, `match.${pattern}`); + return this; + } + /** + * Match only rows where `column` matches the PostgreSQL regex `pattern` + * case-insensitively (using the `~*` operator). + * + * @param column - The column to filter on + * @param pattern - The PostgreSQL regular expression pattern to match with + */ + regexIMatch(column, pattern) { + this.url.searchParams.append(column, `imatch.${pattern}`); + return this; + } + /** + * Match only rows where `column` IS `value`. + * + * For non-boolean columns, this is only relevant for checking if the value of + * `column` is NULL by setting `value` to `null`. + * + * For boolean columns, you can also set `value` to `true` or `false` and it + * will behave the same way as `.eq()`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + is(column, value) { + this.url.searchParams.append(column, `is.${value}`); + return this; + } + /** + * Match only rows where `column` IS DISTINCT FROM `value`. + * + * Unlike `.neq()`, this treats `NULL` as a comparable value. Two `NULL` values + * are considered equal (not distinct), and comparing `NULL` with any non-NULL + * value returns true (distinct). + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + isDistinct(column, value) { + this.url.searchParams.append(column, `isdistinct.${value}`); + return this; + } + /** + * Match only rows where `column` is included in the `values` array. + * + * @param column - The column to filter on + * @param values - The values array to filter with + */ + in(column, values) { + const cleanedValues = Array.from(new Set(values)) + .map((s) => { + // handle postgrest reserved characters + // https://postgrest.org/en/v7.0.0/api.html#reserved-characters + if (typeof s === 'string' && PostgrestReservedCharsRegexp.test(s)) + return `"${s}"`; + else + return `${s}`; + }) + .join(','); + this.url.searchParams.append(column, `in.(${cleanedValues})`); + return this; + } + /** + * Only relevant for jsonb, array, and range columns. Match only rows where + * `column` contains every element appearing in `value`. + * + * @param column - The jsonb, array, or range column to filter on + * @param value - The jsonb, array, or range value to filter with + */ + contains(column, value) { + if (typeof value === 'string') { + // range types can be inclusive '[', ']' or exclusive '(', ')' so just + // keep it simple and accept a string + this.url.searchParams.append(column, `cs.${value}`); + } + else if (Array.isArray(value)) { + // array + this.url.searchParams.append(column, `cs.{${value.join(',')}}`); + } + else { + // json + this.url.searchParams.append(column, `cs.${JSON.stringify(value)}`); + } + return this; + } + /** + * Only relevant for jsonb, array, and range columns. Match only rows where + * every element appearing in `column` is contained by `value`. + * + * @param column - The jsonb, array, or range column to filter on + * @param value - The jsonb, array, or range value to filter with + */ + containedBy(column, value) { + if (typeof value === 'string') { + // range + this.url.searchParams.append(column, `cd.${value}`); + } + else if (Array.isArray(value)) { + // array + this.url.searchParams.append(column, `cd.{${value.join(',')}}`); + } + else { + // json + this.url.searchParams.append(column, `cd.${JSON.stringify(value)}`); + } + return this; + } + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is greater than any element in `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeGt(column, range) { + this.url.searchParams.append(column, `sr.${range}`); + return this; + } + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is either contained in `range` or greater than any element in + * `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeGte(column, range) { + this.url.searchParams.append(column, `nxl.${range}`); + return this; + } + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is less than any element in `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeLt(column, range) { + this.url.searchParams.append(column, `sl.${range}`); + return this; + } + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is either contained in `range` or less than any element in + * `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeLte(column, range) { + this.url.searchParams.append(column, `nxr.${range}`); + return this; + } + /** + * Only relevant for range columns. Match only rows where `column` is + * mutually exclusive to `range` and there can be no element between the two + * ranges. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeAdjacent(column, range) { + this.url.searchParams.append(column, `adj.${range}`); + return this; + } + /** + * Only relevant for array and range columns. Match only rows where + * `column` and `value` have an element in common. + * + * @param column - The array or range column to filter on + * @param value - The array or range value to filter with + */ + overlaps(column, value) { + if (typeof value === 'string') { + // range + this.url.searchParams.append(column, `ov.${value}`); + } + else { + // array + this.url.searchParams.append(column, `ov.{${value.join(',')}}`); + } + return this; + } + /** + * Only relevant for text and tsvector columns. Match only rows where + * `column` matches the query string in `query`. + * + * @param column - The text or tsvector column to filter on + * @param query - The query text to match with + * @param options - Named parameters + * @param options.config - The text search configuration to use + * @param options.type - Change how the `query` text is interpreted + */ + textSearch(column, query, { config, type } = {}) { + let typePart = ''; + if (type === 'plain') { + typePart = 'pl'; + } + else if (type === 'phrase') { + typePart = 'ph'; + } + else if (type === 'websearch') { + typePart = 'w'; + } + const configPart = config === undefined ? '' : `(${config})`; + this.url.searchParams.append(column, `${typePart}fts${configPart}.${query}`); + return this; + } + /** + * Match only rows where each column in `query` keys is equal to its + * associated value. Shorthand for multiple `.eq()`s. + * + * @param query - The object to filter with, with column names as keys mapped + * to their filter values + */ + match(query) { + Object.entries(query).forEach(([column, value]) => { + this.url.searchParams.append(column, `eq.${value}`); + }); + return this; + } + /** + * Match only rows which doesn't satisfy the filter. + * + * Unlike most filters, `opearator` and `value` are used as-is and need to + * follow [PostgREST + * syntax](https://postgrest.org/en/stable/api.html#operators). You also need + * to make sure they are properly sanitized. + * + * @param column - The column to filter on + * @param operator - The operator to be negated to filter with, following + * PostgREST syntax + * @param value - The value to filter with, following PostgREST syntax + */ + not(column, operator, value) { + this.url.searchParams.append(column, `not.${operator}.${value}`); + return this; + } + /** + * Match only rows which satisfy at least one of the filters. + * + * Unlike most filters, `filters` is used as-is and needs to follow [PostgREST + * syntax](https://postgrest.org/en/stable/api.html#operators). You also need + * to make sure it's properly sanitized. + * + * It's currently not possible to do an `.or()` filter across multiple tables. + * + * @param filters - The filters to use, following PostgREST syntax + * @param options - Named parameters + * @param options.referencedTable - Set this to filter on referenced tables + * instead of the parent table + * @param options.foreignTable - Deprecated, use `referencedTable` instead + */ + or(filters, { foreignTable, referencedTable = foreignTable, } = {}) { + const key = referencedTable ? `${referencedTable}.or` : 'or'; + this.url.searchParams.append(key, `(${filters})`); + return this; + } + /** + * Match only rows which satisfy the filter. This is an escape hatch - you + * should use the specific filter methods wherever possible. + * + * Unlike most filters, `opearator` and `value` are used as-is and need to + * follow [PostgREST + * syntax](https://postgrest.org/en/stable/api.html#operators). You also need + * to make sure they are properly sanitized. + * + * @param column - The column to filter on + * @param operator - The operator to filter with, following PostgREST syntax + * @param value - The value to filter with, following PostgREST syntax + */ + filter(column, operator, value) { + this.url.searchParams.append(column, `${operator}.${value}`); + return this; + } +} +exports.default = PostgrestFilterBuilder; +//# sourceMappingURL=PostgrestFilterBuilder.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestFilterBuilder.js.map b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestFilterBuilder.js.map new file mode 100644 index 0000000..ad12202 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestFilterBuilder.js.map @@ -0,0 +1 @@ +{"version":3,"file":"PostgrestFilterBuilder.js","sourceRoot":"","sources":["../../src/PostgrestFilterBuilder.ts"],"names":[],"mappings":";;;AAAA,oGAAmE;AAmCnE,MAAM,4BAA4B,GAAG,IAAI,MAAM,CAAC,OAAO,CAAC,CAAA;AA2CxD,MAAqB,sBAQnB,SAAQ,mCAQT;IACC;;;;;;;OAOG;IACH,EAAE,CACA,MAAkB,EAClB,KAOW;QAEX,IAAI,CAAC,GAAG,CAAC,YAAY,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,KAAK,EAAE,CAAC,CAAA;QACnD,OAAO,IAAI,CAAA;IACb,CAAC;IAED;;;;;OAKG;IACH,GAAG,CACD,MAAkB,EAClB,KAIW;QAEX,IAAI,CAAC,GAAG,CAAC,YAAY,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,KAAK,EAAE,CAAC,CAAA;QACpD,OAAO,IAAI,CAAA;IACb,CAAC;IAID;;;;;OAKG;IACH,EAAE,CAAC,MAAc,EAAE,KAAc;QAC/B,IAAI,CAAC,GAAG,CAAC,YAAY,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,KAAK,EAAE,CAAC,CAAA;QACnD,OAAO,IAAI,CAAA;IACb,CAAC;IAID;;;;;OAKG;IACH,GAAG,CAAC,MAAc,EAAE,KAAc;QAChC,IAAI,CAAC,GAAG,CAAC,YAAY,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,KAAK,EAAE,CAAC,CAAA;QACpD,OAAO,IAAI,CAAA;IACb,CAAC;IAID;;;;;OAKG;IACH,EAAE,CAAC,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C,KAA8B;QAClC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE,EAAE;YAChD,IAAI,CAAC,GAAG,CAAC,YAAY,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,KAAK,EAAE,CAAC,CAAA;QACrD,CAAC,CAAC,CAAA;QACF,OAAO,IAAI,CAAA;IACb,CAAC;IAQD;;;;;;;;;;;;OAYG;IACH,GAAG,CAAC,MAAc,EAAE,QAAgB,EAAE,KAAc;QAClD,IAAI,CAAC,GAAG,CAAC,YAAY,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,QAAQ,IAAI,KAAK,EAAE,CAAC,CAAA;QAChE,OAAO,IAAI,CAAA;IACb,CAAC;IAED;;;;;;;;;;;;;;OAcG;IACH,EAAE,CACA,OAAe,EACf,EACE,YAAY,EACZ,eAAe,GAAG,YAAY,MACyB,EAAE;QAE3D,MAAM,GAAG,GAAG,eAAe,CAAC,CAAC,CAAC,GAAG,eAAe,KAAK,CAAC,CAAC,CAAC,IAAI,CAAA;QAC5D,IAAI,CAAC,GAAG,CAAC,YAAY,CAAC,MAAM,CAAC,GAAG,EAAE,IAAI,OAAO,GAAG,CAAC,CAAA;QACjD,OAAO,IAAI,CAAA;IACb,CAAC;IAQD;;;;;;;;;;;;OAYG;IACH,MAAM,CAAC,MAAc,EAAE,QAAgB,EAAE,KAAc;QACrD,IAAI,CAAC,GAAG,CAAC,YAAY,CAAC,MAAM,CAAC,MAAM,EAAE,GAAG,QAAQ,IAAI,KAAK,EAAE,CAAC,CAAA;QAC5D,OAAO,IAAI,CAAA;IACb,CAAC;CACF;AApkBD,yCAokBC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestQueryBuilder.d.ts b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestQueryBuilder.d.ts new file mode 100644 index 0000000..e061b58 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestQueryBuilder.d.ts @@ -0,0 +1,130 @@ +import PostgrestFilterBuilder from './PostgrestFilterBuilder'; +import { GetResult } from './select-query-parser/result'; +import { ClientServerOptions, Fetch, GenericSchema, GenericTable, GenericView } from './types/common/common'; +export default class PostgrestQueryBuilder { + url: URL; + headers: Headers; + schema?: string; + signal?: AbortSignal; + fetch?: Fetch; + /** + * Creates a query builder scoped to a Postgres table or view. + * + * @example + * ```ts + * import PostgrestQueryBuilder from '@supabase/postgrest-js' + * + * const query = new PostgrestQueryBuilder( + * new URL('https://xyzcompany.supabase.co/rest/v1/users'), + * { headers: { apikey: 'public-anon-key' } } + * ) + * ``` + */ + constructor(url: URL, { headers, schema, fetch, }: { + headers?: HeadersInit; + schema?: string; + fetch?: Fetch; + }); + /** + * Perform a SELECT query on the table or view. + * + * @param columns - The columns to retrieve, separated by commas. Columns can be renamed when returned with `customName:columnName` + * + * @param options - Named parameters + * + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * + * @param options.count - Count algorithm to use to count rows in the table or view. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + select>(columns?: Query, options?: { + head?: boolean; + count?: 'exact' | 'planned' | 'estimated'; + }): PostgrestFilterBuilder; + insert(values: Row, options?: { + count?: 'exact' | 'planned' | 'estimated'; + }): PostgrestFilterBuilder; + insert(values: Row[], options?: { + count?: 'exact' | 'planned' | 'estimated'; + defaultToNull?: boolean; + }): PostgrestFilterBuilder; + upsert(values: Row, options?: { + onConflict?: string; + ignoreDuplicates?: boolean; + count?: 'exact' | 'planned' | 'estimated'; + }): PostgrestFilterBuilder; + upsert(values: Row[], options?: { + onConflict?: string; + ignoreDuplicates?: boolean; + count?: 'exact' | 'planned' | 'estimated'; + defaultToNull?: boolean; + }): PostgrestFilterBuilder; + /** + * Perform an UPDATE on the table or view. + * + * By default, updated rows are not returned. To return it, chain the call + * with `.select()` after filters. + * + * @param values - The values to update with + * + * @param options - Named parameters + * + * @param options.count - Count algorithm to use to count updated rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + update(values: Row, { count, }?: { + count?: 'exact' | 'planned' | 'estimated'; + }): PostgrestFilterBuilder; + /** + * Perform a DELETE on the table or view. + * + * By default, deleted rows are not returned. To return it, chain the call + * with `.select()` after filters. + * + * @param options - Named parameters + * + * @param options.count - Count algorithm to use to count deleted rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + delete({ count, }?: { + count?: 'exact' | 'planned' | 'estimated'; + }): PostgrestFilterBuilder; +} +//# sourceMappingURL=PostgrestQueryBuilder.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestQueryBuilder.d.ts.map b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestQueryBuilder.d.ts.map new file mode 100644 index 0000000..46d65e0 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestQueryBuilder.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"PostgrestQueryBuilder.d.ts","sourceRoot":"","sources":["../../src/PostgrestQueryBuilder.ts"],"names":[],"mappings":"AAAA,OAAO,sBAAsB,MAAM,0BAA0B,CAAA;AAC7D,OAAO,EAAE,SAAS,EAAE,MAAM,8BAA8B,CAAA;AACxD,OAAO,EACL,mBAAmB,EACnB,KAAK,EACL,aAAa,EACb,YAAY,EACZ,WAAW,EACZ,MAAM,uBAAuB,CAA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AAU,CAAC,EAAE,MAAM,CAAA;QACnB,gBAAgB,CAAC,EAAE,OAAO,CAAA;QAC1B,KAAK,CAAC,EAAE,OAAO,GAAG,SAAS,GAAG,WAAW,CAAA;QACzC,aAAa,CAAC,EAAE,OAAO,CAAA;KACxB,GACA,sBAAsB,CACvB,aAAa,EACb,MAAM,EACN,QAAQ,CAAC,KAAK,CAAC,EACf,IAAI,EACJ,YAAY,EACZ,aAAa,EACb,MAAM,CACP;IA4ID;;;;;;;;;;;;;;;;;;;;OAoBG;IACH,MAAM,CAAC,GAAG,SAAS,QAAQ,SAAS;QAAE,MAAM,EAAE,OAAO,CAAA;KAAE,GAAG,QAAQ,CAAC,QAAQ,CAAC,GAAG,KAAK,EAClF,MAAM,EAAE,GAAG,EACX,EACE,KAAK,GACN,GAAE;QACD,KAAK,CAAC,EAAE,OAAO,GAAG,SAAS,GAAG,WAAW,CAAA;KACrC,GACL,sBAAsB,CACvB,aAAa,EACb,MAAM,EACN,QAAQ,CAAC,KAAK,CAAC,EACf,IAAI,EACJ,YAAY,EACZ,aAAa,EACb,OAAO,CACR;IAgBD;;;;;;;;;;;;;;;;;;OAkBG;IACH,MAAM,CAAC,EACL,KAAK,GACN,GAAE;QACD,KAAK,CAAC,EAAE,OAAO,GAAG,SAAS,GAAG,WAAW,CAAA;KACrC,GAAG,sBAAsB,CAC7B,aAAa,EACb,MAAM,EACN,QAAQ,CAAC,KAAK,CAAC,EACf,IAAI,EACJ,YAAY,EACZ,aAAa,EACb,QAAQ,CACT;CAcF"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestQueryBuilder.js b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestQueryBuilder.js new file mode 100644 index 0000000..d57f0c6 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestQueryBuilder.js @@ -0,0 +1,310 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = require("tslib"); +const PostgrestFilterBuilder_1 = tslib_1.__importDefault(require("./PostgrestFilterBuilder")); +class PostgrestQueryBuilder { + /** + * Creates a query builder scoped to a Postgres table or view. + * + * @example + * ```ts + * import PostgrestQueryBuilder from '@supabase/postgrest-js' + * + * const query = new PostgrestQueryBuilder( + * new URL('https://xyzcompany.supabase.co/rest/v1/users'), + * { headers: { apikey: 'public-anon-key' } } + * ) + * ``` + */ + constructor(url, { headers = {}, schema, fetch, }) { + this.url = url; + this.headers = new Headers(headers); + this.schema = schema; + this.fetch = fetch; + } + /** + * Perform a SELECT query on the table or view. + * + * @param columns - The columns to retrieve, separated by commas. Columns can be renamed when returned with `customName:columnName` + * + * @param options - Named parameters + * + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * + * @param options.count - Count algorithm to use to count rows in the table or view. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + select(columns, options) { + const { head = false, count } = options !== null && options !== void 0 ? options : {}; + const method = head ? 'HEAD' : 'GET'; + // Remove whitespaces except when quoted + let quoted = false; + const cleanedColumns = (columns !== null && columns !== void 0 ? columns : '*') + .split('') + .map((c) => { + if (/\s/.test(c) && !quoted) { + return ''; + } + if (c === '"') { + quoted = !quoted; + } + return c; + }) + .join(''); + this.url.searchParams.set('select', cleanedColumns); + if (count) { + this.headers.append('Prefer', `count=${count}`); + } + return new PostgrestFilterBuilder_1.default({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + fetch: this.fetch, + }); + } + /** + * Perform an INSERT into the table or view. + * + * By default, inserted rows are not returned. To return it, chain the call + * with `.select()`. + * + * @param values - The values to insert. Pass an object to insert a single row + * or an array to insert multiple rows. + * + * @param options - Named parameters + * + * @param options.count - Count algorithm to use to count inserted rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + * + * @param options.defaultToNull - Make missing fields default to `null`. + * Otherwise, use the default value for the column. Only applies for bulk + * inserts. + */ + insert(values, { count, defaultToNull = true, } = {}) { + var _a; + const method = 'POST'; + if (count) { + this.headers.append('Prefer', `count=${count}`); + } + if (!defaultToNull) { + this.headers.append('Prefer', `missing=default`); + } + if (Array.isArray(values)) { + const columns = values.reduce((acc, x) => acc.concat(Object.keys(x)), []); + if (columns.length > 0) { + const uniqueColumns = [...new Set(columns)].map((column) => `"${column}"`); + this.url.searchParams.set('columns', uniqueColumns.join(',')); + } + } + return new PostgrestFilterBuilder_1.default({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + body: values, + fetch: (_a = this.fetch) !== null && _a !== void 0 ? _a : fetch, + }); + } + /** + * Perform an UPSERT on the table or view. Depending on the column(s) passed + * to `onConflict`, `.upsert()` allows you to perform the equivalent of + * `.insert()` if a row with the corresponding `onConflict` columns doesn't + * exist, or if it does exist, perform an alternative action depending on + * `ignoreDuplicates`. + * + * By default, upserted rows are not returned. To return it, chain the call + * with `.select()`. + * + * @param values - The values to upsert with. Pass an object to upsert a + * single row or an array to upsert multiple rows. + * + * @param options - Named parameters + * + * @param options.onConflict - Comma-separated UNIQUE column(s) to specify how + * duplicate rows are determined. Two rows are duplicates if all the + * `onConflict` columns are equal. + * + * @param options.ignoreDuplicates - If `true`, duplicate rows are ignored. If + * `false`, duplicate rows are merged with existing rows. + * + * @param options.count - Count algorithm to use to count upserted rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + * + * @param options.defaultToNull - Make missing fields default to `null`. + * Otherwise, use the default value for the column. This only applies when + * inserting new rows, not when merging with existing rows under + * `ignoreDuplicates: false`. This also only applies when doing bulk upserts. + * + * @example Upsert a single row using a unique key + * ```ts + * // Upserting a single row, overwriting based on the 'username' unique column + * const { data, error } = await supabase + * .from('users') + * .upsert({ username: 'supabot' }, { onConflict: 'username' }) + * + * // Example response: + * // { + * // data: [ + * // { id: 4, message: 'bar', username: 'supabot' } + * // ], + * // error: null + * // } + * ``` + * + * @example Upsert with conflict resolution and exact row counting + * ```ts + * // Upserting and returning exact count + * const { data, error, count } = await supabase + * .from('users') + * .upsert( + * { + * id: 3, + * message: 'foo', + * username: 'supabot' + * }, + * { + * onConflict: 'username', + * count: 'exact' + * } + * ) + * + * // Example response: + * // { + * // data: [ + * // { + * // id: 42, + * // handle: "saoirse", + * // display_name: "Saoirse" + * // } + * // ], + * // count: 1, + * // error: null + * // } + * ``` + */ + upsert(values, { onConflict, ignoreDuplicates = false, count, defaultToNull = true, } = {}) { + var _a; + const method = 'POST'; + this.headers.append('Prefer', `resolution=${ignoreDuplicates ? 'ignore' : 'merge'}-duplicates`); + if (onConflict !== undefined) + this.url.searchParams.set('on_conflict', onConflict); + if (count) { + this.headers.append('Prefer', `count=${count}`); + } + if (!defaultToNull) { + this.headers.append('Prefer', 'missing=default'); + } + if (Array.isArray(values)) { + const columns = values.reduce((acc, x) => acc.concat(Object.keys(x)), []); + if (columns.length > 0) { + const uniqueColumns = [...new Set(columns)].map((column) => `"${column}"`); + this.url.searchParams.set('columns', uniqueColumns.join(',')); + } + } + return new PostgrestFilterBuilder_1.default({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + body: values, + fetch: (_a = this.fetch) !== null && _a !== void 0 ? _a : fetch, + }); + } + /** + * Perform an UPDATE on the table or view. + * + * By default, updated rows are not returned. To return it, chain the call + * with `.select()` after filters. + * + * @param values - The values to update with + * + * @param options - Named parameters + * + * @param options.count - Count algorithm to use to count updated rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + update(values, { count, } = {}) { + var _a; + const method = 'PATCH'; + if (count) { + this.headers.append('Prefer', `count=${count}`); + } + return new PostgrestFilterBuilder_1.default({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + body: values, + fetch: (_a = this.fetch) !== null && _a !== void 0 ? _a : fetch, + }); + } + /** + * Perform a DELETE on the table or view. + * + * By default, deleted rows are not returned. To return it, chain the call + * with `.select()` after filters. + * + * @param options - Named parameters + * + * @param options.count - Count algorithm to use to count deleted rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + delete({ count, } = {}) { + var _a; + const method = 'DELETE'; + if (count) { + this.headers.append('Prefer', `count=${count}`); + } + return new PostgrestFilterBuilder_1.default({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + fetch: (_a = this.fetch) !== null && _a !== void 0 ? _a : fetch, + }); + } +} +exports.default = PostgrestQueryBuilder; +//# sourceMappingURL=PostgrestQueryBuilder.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestQueryBuilder.js.map b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestQueryBuilder.js.map new file mode 100644 index 0000000..9659de1 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestQueryBuilder.js.map @@ -0,0 +1 @@ +{"version":3,"file":"PostgrestQueryBuilder.js","sourceRoot":"","sources":["../../src/PostgrestQueryBuilder.ts"],"names":[],"mappings":";;;AAAA,8FAA6D;AAU7D,MAAqB,qBAAqB;IAaxC;;;;;;;;;;;;OAYG;IACH,YACE,GAAQ,EACR,EACE,OAAO,GAAG,EAAE,EACZ,MAAM,EACN,KAAK,GAKN;QAED,IAAI,CAAC,GAAG,GAAG,GAAG,CA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C,CAAA;QACjD,CAAC;QAED,OAAO,IAAI,gCAAsB,CAAC;YAChC,MAAM;YACN,GAAG,EAAE,IAAI,CAAC,GAAG;YACb,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,KAAK,EAAE,MAAA,IAAI,CAAC,KAAK,mCAAI,KAAK;SAC3B,CAAC,CAAA;IACJ,CAAC;CACF;AA7eD,wCA6eC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestTransformBuilder.d.ts b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestTransformBuilder.d.ts new file mode 100644 index 0000000..1d9e1f4 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestTransformBuilder.d.ts @@ -0,0 +1,159 @@ +import PostgrestBuilder from './PostgrestBuilder'; +import PostgrestFilterBuilder, { InvalidMethodError } from './PostgrestFilterBuilder'; +import { GetResult } from './select-query-parser/result'; +import { CheckMatchingArrayTypes } from './types/types'; +import { ClientServerOptions, GenericSchema } from './types/common/common'; +import type { MaxAffectedEnabled } from './types/feature-flags'; +export default class PostgrestTransformBuilder, Result, RelationName = unknown, Relationships = unknown, Method = unknown> extends PostgrestBuilder { + /** + * Perform a SELECT on the query result. + * + * By default, `.insert()`, `.update()`, `.upsert()`, and `.delete()` do not + * return modified rows. By calling this method, modified rows are returned in + * `data`. + * + * @param columns - The columns to retrieve, separated by commas + */ + select>(columns?: Query): PostgrestFilterBuilder; + order(column: ColumnName, options?: { + ascending?: boolean; + nullsFirst?: boolean; + referencedTable?: undefined; + }): this; + order(column: string, options?: { + ascending?: boolean; + nullsFirst?: boolean; + referencedTable?: string; + }): this; + /** + * @deprecated Use `options.referencedTable` instead of `options.foreignTable` + */ + order(column: ColumnName, options?: { + ascending?: boolean; + nullsFirst?: boolean; + foreignTable?: undefined; + }): this; + /** + * @deprecated Use `options.referencedTable` instead of `options.foreignTable` + */ + order(column: string, options?: { + ascending?: boolean; + nullsFirst?: boolean; + foreignTable?: string; + }): this; + /** + * Limit the query result by `count`. + * + * @param count - The maximum number of rows to return + * @param options - Named parameters + * @param options.referencedTable - Set this to limit rows of referenced + * tables instead of the parent table + * @param options.foreignTable - Deprecated, use `options.referencedTable` + * instead + */ + limit(count: number, { foreignTable, referencedTable, }?: { + foreignTable?: string; + referencedTable?: string; + }): this; + /** + * Limit the query result by starting at an offset `from` and ending at the offset `to`. + * Only records within this range are returned. + * This respects the query order and if there is no order clause the range could behave unexpectedly. + * The `from` and `to` values are 0-based and inclusive: `range(1, 3)` will include the second, third + * and fourth rows of the query. + * + * @param from - The starting index from which to limit the result + * @param to - The last index to which to limit the result + * @param options - Named parameters + * @param options.referencedTable - Set this to limit rows of referenced + * tables instead of the parent table + * @param options.foreignTable - Deprecated, use `options.referencedTable` + * instead + */ + range(from: number, to: number, { foreignTable, referencedTable, }?: { + foreignTable?: string; + referencedTable?: string; + }): this; + /** + * Set the AbortSignal for the fetch request. + * + * @param signal - The AbortSignal to use for the fetch request + */ + abortSignal(signal: AbortSignal): this; + /** + * Return `data` as a single object instead of an array of objects. + * + * Query result must be one row (e.g. using `.limit(1)`), otherwise this + * returns an error. + */ + single(): PostgrestBuilder; + /** + * Return `data` as a single object instead of an array of objects. + * + * Query result must be zero or one row (e.g. using `.limit(1)`), otherwise + * this returns an error. + */ + maybeSingle(): PostgrestBuilder; + /** + * Return `data` as a string in CSV format. + */ + csv(): PostgrestBuilder; + /** + * Return `data` as an object in [GeoJSON](https://geojson.org) format. + */ + geojson(): PostgrestBuilder>; + /** + * Return `data` as the EXPLAIN plan for the query. + * + * You need to enable the + * [db_plan_enabled](https://supabase.com/docs/guides/database/debugging-performance#enabling-explain) + * setting before using this method. + * + * @param options - Named parameters + * + * @param options.analyze - If `true`, the query will be executed and the + * actual run time will be returned + * + * @param options.verbose - If `true`, the query identifier will be returned + * and `data` will include the output columns of the query + * + * @param options.settings - If `true`, include information on configuration + * parameters that affect query planning + * + * @param options.buffers - If `true`, include information on buffer usage + * + * @param options.wal - If `true`, include information on WAL record generation + * + * @param options.format - The format of the output, can be `"text"` (default) + * or `"json"` + */ + explain({ analyze, verbose, settings, buffers, wal, format, }?: { + analyze?: boolean; + verbose?: boolean; + settings?: boolean; + buffers?: boolean; + wal?: boolean; + format?: 'json' | 'text'; + }): PostgrestBuilder | PostgrestBuilder[], false>; + /** + * Rollback the query. + * + * `data` will still be returned, but the query is not committed. + */ + rollback(): this; + /** + * Override the type of the returned `data`. + * + * @typeParam NewResult - The new result type to override with + * @deprecated Use overrideTypes() method at the end of your call chain instead + */ + returns(): PostgrestTransformBuilder, RelationName, Relationships, Method>; + /** + * Set the maximum number of rows that can be affected by the query. + * Only available in PostgREST v13+ and only works with PATCH and DELETE methods. + * + * @param value - The maximum number of rows that can be affected + */ + maxAffected(value: number): MaxAffectedEnabled extends true ? Method extends 'PATCH' | 'DELETE' | 'RPC' ? this : InvalidMethodError<'maxAffected method only available on update or delete'> : InvalidMethodError<'maxAffected method only available on postgrest 13+'>; +} +//# sourceMappingURL=PostgrestTransformBuilder.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestTransformBuilder.d.ts.map b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestTransformBuilder.d.ts.map new file mode 100644 index 0000000..057db1f --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestTransformBuilder.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"PostgrestTransformBuilder.d.ts","sourceRoot":"","sources":["../../src/PostgrestTransformBuilder.ts"],"names":[],"mappings":"AAAA,OAAO,gBAAgB,MAAM,oBAAoB,CAAA;AACjD,OAAO,sBAAsB,EAAE,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAA;AACrF,OAAO,EAAE,SAAS,EAAE,MAAM,8BAA8B,CAAA;AACxD,OAAO,EAAE,uBAAuB,EAAE,MAAM,eAAe,CAAA;AACvD,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BAAgB,CAAC,aAAa,EAAE,MAAM,CAAC;IAK9C;;OAEG;IACH,OAAO,IAAI,gBAAgB,CAAC,aAAa,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAKnE;;;;;;;;;;;;;;;;;;;;;;;;OAwBG;IACH,OAAO,CAAC,EACN,OAAe,EACf,OAAe,EACf,QAAgB,EAChB,OAAe,EACf,GAAW,EACX,MAAe,GAChB,GAAE;QACD,OAAO,CAAC,EAAE,OAAO,CAAA;QACjB,OAAO,CAAC,EAAE,OAAO,CAAA;QACjB,QAAQ,CAAC,EAAE,OAAO,CAAA;QAClB,OAAO,CAAC,EAAE,OAAO,CAAA;QACjB,GAAG,CAAC,EAAE,OAAO,CAAA;QACb,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,CAAA;KACpB;IAuBN;;;;OAIG;IACH,QAAQ,IAAI,IAAI;IAKhB;;;;;OAKG;IACH,OAAO,CAAC,SAAS,KAAK,yBAAyB,CAC7C,aAAa,EACb,MAAM,EACN,GAAG,EACH,uBAAuB,CAAC,MAAM,EAAE,SAAS,CAAC,EAC1C,YAAY,EACZ,aAAa,EACb,MAAM,CACP;IAYD;;;;;OAKG;IACH,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,kBAAkB,CAAC,aAAa,CAAC,kBAAkB,CAAC,CAAC,SAAS,IAAI,GAE1F,MAAM,SAAS,OAAO,GAAG,QAAQ,GAAG,KAAK,GACvC,IAAI,GACJ,kBAAkB,CAAC,uDAAuD,CAAC,GAC7E,kBAAkB,CAAC,oDAAoD,CAAC;CAS7E"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestTransformBuilder.js b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestTransformBuilder.js new file mode 100644 index 0000000..53cdcad --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestTransformBuilder.js @@ -0,0 +1,224 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = require("tslib"); +const PostgrestBuilder_1 = tslib_1.__importDefault(require("./PostgrestBuilder")); +class PostgrestTransformBuilder extends PostgrestBuilder_1.default { + /** + * Perform a SELECT on the query result. + * + * By default, `.insert()`, `.update()`, `.upsert()`, and `.delete()` do not + * return modified rows. By calling this method, modified rows are returned in + * `data`. + * + * @param columns - The columns to retrieve, separated by commas + */ + select(columns) { + // Remove whitespaces except when quoted + let quoted = false; + const cleanedColumns = (columns !== null && columns !== void 0 ? columns : '*') + .split('') + .map((c) => { + if (/\s/.test(c) && !quoted) { + return ''; + } + if (c === '"') { + quoted = !quoted; + } + return c; + }) + .join(''); + this.url.searchParams.set('select', cleanedColumns); + this.headers.append('Prefer', 'return=representation'); + return this; + } + /** + * Order the query result by `column`. + * + * You can call this method multiple times to order by multiple columns. + * + * You can order referenced tables, but it only affects the ordering of the + * parent table if you use `!inner` in the query. + * + * @param column - The column to order by + * @param options - Named parameters + * @param options.ascending - If `true`, the result will be in ascending order + * @param options.nullsFirst - If `true`, `null`s appear first. If `false`, + * `null`s appear last. + * @param options.referencedTable - Set this to order a referenced table by + * its columns + * @param options.foreignTable - Deprecated, use `options.referencedTable` + * instead + */ + order(column, { ascending = true, nullsFirst, foreignTable, referencedTable = foreignTable, } = {}) { + const key = referencedTable ? `${referencedTable}.order` : 'order'; + const existingOrder = this.url.searchParams.get(key); + this.url.searchParams.set(key, `${existingOrder ? `${existingOrder},` : ''}${column}.${ascending ? 'asc' : 'desc'}${nullsFirst === undefined ? '' : nullsFirst ? '.nullsfirst' : '.nullslast'}`); + return this; + } + /** + * Limit the query result by `count`. + * + * @param count - The maximum number of rows to return + * @param options - Named parameters + * @param options.referencedTable - Set this to limit rows of referenced + * tables instead of the parent table + * @param options.foreignTable - Deprecated, use `options.referencedTable` + * instead + */ + limit(count, { foreignTable, referencedTable = foreignTable, } = {}) { + const key = typeof referencedTable === 'undefined' ? 'limit' : `${referencedTable}.limit`; + this.url.searchParams.set(key, `${count}`); + return this; + } + /** + * Limit the query result by starting at an offset `from` and ending at the offset `to`. + * Only records within this range are returned. + * This respects the query order and if there is no order clause the range could behave unexpectedly. + * The `from` and `to` values are 0-based and inclusive: `range(1, 3)` will include the second, third + * and fourth rows of the query. + * + * @param from - The starting index from which to limit the result + * @param to - The last index to which to limit the result + * @param options - Named parameters + * @param options.referencedTable - Set this to limit rows of referenced + * tables instead of the parent table + * @param options.foreignTable - Deprecated, use `options.referencedTable` + * instead + */ + range(from, to, { foreignTable, referencedTable = foreignTable, } = {}) { + const keyOffset = typeof referencedTable === 'undefined' ? 'offset' : `${referencedTable}.offset`; + const keyLimit = typeof referencedTable === 'undefined' ? 'limit' : `${referencedTable}.limit`; + this.url.searchParams.set(keyOffset, `${from}`); + // Range is inclusive, so add 1 + this.url.searchParams.set(keyLimit, `${to - from + 1}`); + return this; + } + /** + * Set the AbortSignal for the fetch request. + * + * @param signal - The AbortSignal to use for the fetch request + */ + abortSignal(signal) { + this.signal = signal; + return this; + } + /** + * Return `data` as a single object instead of an array of objects. + * + * Query result must be one row (e.g. using `.limit(1)`), otherwise this + * returns an error. + */ + single() { + this.headers.set('Accept', 'application/vnd.pgrst.object+json'); + return this; + } + /** + * Return `data` as a single object instead of an array of objects. + * + * Query result must be zero or one row (e.g. using `.limit(1)`), otherwise + * this returns an error. + */ + maybeSingle() { + // Temporary partial fix for https://github.com/supabase/postgrest-js/issues/361 + // Issue persists e.g. for `.insert([...]).select().maybeSingle()` + if (this.method === 'GET') { + this.headers.set('Accept', 'application/json'); + } + else { + this.headers.set('Accept', 'application/vnd.pgrst.object+json'); + } + this.isMaybeSingle = true; + return this; + } + /** + * Return `data` as a string in CSV format. + */ + csv() { + this.headers.set('Accept', 'text/csv'); + return this; + } + /** + * Return `data` as an object in [GeoJSON](https://geojson.org) format. + */ + geojson() { + this.headers.set('Accept', 'application/geo+json'); + return this; + } + /** + * Return `data` as the EXPLAIN plan for the query. + * + * You need to enable the + * [db_plan_enabled](https://supabase.com/docs/guides/database/debugging-performance#enabling-explain) + * setting before using this method. + * + * @param options - Named parameters + * + * @param options.analyze - If `true`, the query will be executed and the + * actual run time will be returned + * + * @param options.verbose - If `true`, the query identifier will be returned + * and `data` will include the output columns of the query + * + * @param options.settings - If `true`, include information on configuration + * parameters that affect query planning + * + * @param options.buffers - If `true`, include information on buffer usage + * + * @param options.wal - If `true`, include information on WAL record generation + * + * @param options.format - The format of the output, can be `"text"` (default) + * or `"json"` + */ + explain({ analyze = false, verbose = false, settings = false, buffers = false, wal = false, format = 'text', } = {}) { + var _a; + const options = [ + analyze ? 'analyze' : null, + verbose ? 'verbose' : null, + settings ? 'settings' : null, + buffers ? 'buffers' : null, + wal ? 'wal' : null, + ] + .filter(Boolean) + .join('|'); + // An Accept header can carry multiple media types but postgrest-js always sends one + const forMediatype = (_a = this.headers.get('Accept')) !== null && _a !== void 0 ? _a : 'application/json'; + this.headers.set('Accept', `application/vnd.pgrst.plan+${format}; for="${forMediatype}"; options=${options};`); + if (format === 'json') { + return this; + } + else { + return this; + } + } + /** + * Rollback the query. + * + * `data` will still be returned, but the query is not committed. + */ + rollback() { + this.headers.append('Prefer', 'tx=rollback'); + return this; + } + /** + * Override the type of the returned `data`. + * + * @typeParam NewResult - The new result type to override with + * @deprecated Use overrideTypes() method at the end of your call chain instead + */ + returns() { + return this; + } + /** + * Set the maximum number of rows that can be affected by the query. + * Only available in PostgREST v13+ and only works with PATCH and DELETE methods. + * + * @param value - The maximum number of rows that can be affected + */ + maxAffected(value) { + this.headers.append('Prefer', 'handling=strict'); + this.headers.append('Prefer', `max-affected=${value}`); + return this; + } +} +exports.default = PostgrestTransformBuilder; +//# sourceMappingURL=PostgrestTransformBuilder.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestTransformBuilder.js.map b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestTransformBuilder.js.map new file mode 100644 index 0000000..0af7fbb --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/PostgrestTransformBuilder.js.map @@ -0,0 +1 @@ +{"version":3,"file":"PostgrestTransformBuilder.js","sourceRoot":"","sources":["../../src/PostgrestTransformBuilder.ts"],"names":[],"mappings":";;;AAAA,kFAAiD;AAOjD,MAAqB,yBAQnB,SAAQ,0BAAuC;IAC/C;;;;;;;;OAQG;IACH,MAAM,CAIJ,OAAe;QAcf,wCAAwC;QACxC,IAAI,MAAM,GAAG,KAAK,CAAA;QAClB,MAAM,cAAc,GAAG,CAAC,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,GAAG,CAAC;aACpC,KAAK,CAAC,EAAE,CAAC;aACT,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE;YACT,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;gBAC5B,OAAO,EAAE,CAAA;YACX,CAAC;YACD,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;gBACd,MAAM,GAAG,CAAC,MAAM,CAAA;YAClB,CAAC;YACD,OAAO,CAAC,CAAA;QACV,CAAC,CAAC;aACD,IAAI,CAAC,EAAE,CAAC,CAAA;QACX,IAAI,CAAC,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,QAAQ,EAAE,cAAc,CAAC,CAAA;QACnD,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,QAAQ,EAAE,uBAAuB,CAAC,CAAA;QACtD,OAAO,IAYN,CAAA;IACH,CAAC;IAwBD;;;;;;;;;;;;;;;;;OAiBG;IACH,KAAK,CACH,MAAc,EACd,EACE,SAAS,GAAG,IAAI,EAChB,UAAU,EACV,YAAY,EACZ,eAAe,GAAG,YAAY,MAM5B,EAAE;QAEN,MAAM,GAAG,GAAG,eAAe,CAAC,CAAC,CAAC,GAAG,eAAe,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAA;QAClE,MAAM,aAAa,GAAG,IAAI,CAAC,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,GAAG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ff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/constants.d.ts b/backend/node_modules/@supabase/postgrest-js/dist/cjs/constants.d.ts new file mode 100644 index 0000000..12eb562 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/constants.d.ts @@ -0,0 +1,4 @@ +export declare const DEFAULT_HEADERS: { + 'X-Client-Info': string; +}; +//# sourceMappingURL=constants.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/constants.d.ts.map b/backend/node_modules/@supabase/postgrest-js/dist/cjs/constants.d.ts.map new file mode 100644 index 0000000..68e5791 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/constants.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,eAAe;;CAAiD,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/constants.js b/backend/node_modules/@supabase/postgrest-js/dist/cjs/constants.js new file mode 100644 index 0000000..c4ddfc0 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/constants.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DEFAULT_HEADERS = void 0; +const version_1 = require("./version"); +exports.DEFAULT_HEADERS = { 'X-Client-Info': `postgrest-js/${version_1.version}` }; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/constants.js.map b/backend/node_modules/@supabase/postgrest-js/dist/cjs/constants.js.map new file mode 100644 index 0000000..5c6b50a --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":";;;AAAA,uCAAmC;AACtB,QAAA,eAAe,GAAG,EAAE,eAAe,EAAE,gBAAgB,iBAAO,EAAE,EAAE,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/index.d.ts b/backend/node_modules/@supabase/postgrest-js/dist/cjs/index.d.ts new file mode 100644 index 0000000..f8887cd --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/index.d.ts @@ -0,0 +1,20 @@ +import PostgrestClient from './PostgrestClient'; +import PostgrestQueryBuilder from './PostgrestQueryBuilder'; +import PostgrestFilterBuilder from './PostgrestFilterBuilder'; +import PostgrestTransformBuilder from './PostgrestTransformBuilder'; +import PostgrestBuilder from './PostgrestBuilder'; +import PostgrestError from './PostgrestError'; +export { PostgrestClient, PostgrestQueryBuilder, PostgrestFilterBuilder, PostgrestTransformBuilder, PostgrestBuilder, PostgrestError, }; +declare const _default: { + PostgrestClient: typeof PostgrestClient; + PostgrestQueryBuilder: typeof PostgrestQueryBuilder; + PostgrestFilterBuilder: typeof PostgrestFilterBuilder; + PostgrestTransformBuilder: typeof PostgrestTransformBuilder; + PostgrestBuilder: typeof PostgrestBuilder; + PostgrestError: typeof PostgrestError; +}; +export default _default; +export type { PostgrestResponse, PostgrestResponseFailure, PostgrestResponseSuccess, PostgrestSingleResponse, PostgrestMaybeSingleResponse, } from './types/types'; +export type { ClientServerOptions as PostgrestClientOptions } from './types/common/common'; +export type { GetResult as UnstableGetResult } from './select-query-parser/result'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/index.d.ts.map b/backend/node_modules/@supabase/postgrest-js/dist/cjs/index.d.ts.map new file mode 100644 index 0000000..9c870ce --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AACA,OAAO,eAAe,MAAM,mBAAmB,CAAA;AAC/C,OAAO,qBAAqB,MAAM,yBAAyB,CAAA;AAC3D,OAAO,sBAAsB,MAAM,0BAA0B,CAAA;AAC7D,OAAO,yBAAyB,MAAM,6BAA6B,CAAA;AACnE,OAAO,gBAAgB,MAAM,oBAAoB,CAAA;AACjD,OAAO,cAAc,MAAM,kBAAkB,CAAA;AAE7C,OAAO,EACL,eAAe,EACf,qBAAqB,EACrB,sBAAsB,EACtB,yBAAyB,EACzB,gBAAgB,EAChB,cAAc,GACf,CAAA;;;;;;;;;AACD,wBAOC;AACD,YAAY,EACV,iBAAiB,EACjB,wBAAwB,EACxB,wBAAwB,EACxB,uBAAuB,EACvB,4BAA4B,GAC7B,MAAM,eAAe,CAAA;AACtB,YAAY,EAAE,mBAAmB,IAAI,sBAAsB,EAAE,MAAM,uBAAuB,CAAA;AAG1F,YAAY,EAAE,SAAS,IAAI,iBAAiB,EAAE,MAAM,8BAA8B,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/index.js b/backend/node_modules/@supabase/postgrest-js/dist/cjs/index.js new file mode 100644 index 0000000..23c9093 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/index.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PostgrestError = exports.PostgrestBuilder = exports.PostgrestTransformBuilder = exports.PostgrestFilterBuilder = exports.PostgrestQueryBuilder = exports.PostgrestClient = void 0; +const tslib_1 = require("tslib"); +// Always update wrapper.mjs when updating this file. +const PostgrestClient_1 = tslib_1.__importDefault(require("./PostgrestClient")); +exports.PostgrestClient = PostgrestClient_1.default; +const PostgrestQueryBuilder_1 = tslib_1.__importDefault(require("./PostgrestQueryBuilder")); +exports.PostgrestQueryBuilder = PostgrestQueryBuilder_1.default; +const PostgrestFilterBuilder_1 = tslib_1.__importDefault(require("./PostgrestFilterBuilder")); +exports.PostgrestFilterBuilder = PostgrestFilterBuilder_1.default; +const PostgrestTransformBuilder_1 = tslib_1.__importDefault(require("./PostgrestTransformBuilder")); +exports.PostgrestTransformBuilder = PostgrestTransformBuilder_1.default; +const PostgrestBuilder_1 = tslib_1.__importDefault(require("./PostgrestBuilder")); +exports.PostgrestBuilder = PostgrestBuilder_1.default; +const PostgrestError_1 = tslib_1.__importDefault(require("./PostgrestError")); +exports.PostgrestError = PostgrestError_1.default; +exports.default = { + PostgrestClient: PostgrestClient_1.default, + PostgrestQueryBuilder: PostgrestQueryBuilder_1.default, + PostgrestFilterBuilder: PostgrestFilterBuilder_1.default, + PostgrestTransformBuilder: PostgrestTransformBuilder_1.default, + PostgrestBuilder: PostgrestBuilder_1.default, + PostgrestError: PostgrestError_1.default, +}; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/index.js.map b/backend/node_modules/@supabase/postgrest-js/dist/cjs/index.js.map new file mode 100644 index 0000000..5f72a4c --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;AAAA,qDAAqD;AACrD,gFAA+C;AAQ7C,0BARK,yBAAe,CAQL;AAPjB,4FAA2D;AAQzD,gCARK,+BAAqB,CAQL;AAPvB,8FAA6D;AAQ3D,iCARK,gCAAsB,CAQL;AAPxB,oGAAmE;AAQjE,oCARK,mCAAyB,CAQL;AAP3B,kFAAiD;AAQ/C,2BARK,0BAAgB,CAQL;AAPlB,8EAA6C;AAQ3C,yBARK,wBAAc,CAQL;AAEhB,kBAAe;IACb,eAAe,EAAf,yBAAe;IACf,qBAAqB,EAArB,+BAAqB;IACrB,sBAAsB,EAAtB,gCAAsB;IACtB,yBAAyB,EAAzB,mCAAyB;IACzB,gBAAgB,EAAhB,0BAAgB;IAChB,cAAc,EAAd,wBAAc;CACf,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/parser.d.ts b/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/parser.d.ts new file mode 100644 index 0000000..8c9f4c5 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/parser.d.ts @@ -0,0 +1,258 @@ +import { SimplifyDeep } from '../types/types'; +import { JsonPathToAccessor } from './utils'; +/** + * Parses a query. + * A query is a sequence of nodes, separated by `,`, ensuring that there is + * no remaining input after all nodes have been parsed. + * + * Returns an array of parsed nodes, or an error. + */ +export type ParseQuery = string extends Query ? GenericStringError : ParseNodes> extends [infer Nodes, `${infer Remainder}`] ? Nodes extends Ast.Node[] ? EatWhitespace extends '' ? SimplifyDeep : ParserError<`Unexpected input: ${Remainder}`> : ParserError<'Invalid nodes array structure'> : ParseNodes>; +/** + * Notes: all `Parse*` types assume that their input strings have their whitespace + * removed. They return tuples of ["Return Value", "Remainder of text"] or + * a `ParserError`. + */ +/** + * Parses a sequence of nodes, separated by `,`. + * + * Returns a tuple of ["Parsed fields", "Remainder of text"] or an error. + */ +type ParseNodes = string extends Input ? GenericStringError : ParseNodesHelper; +type ParseNodesHelper = ParseNode extends [infer Node, `${infer Remainder}`] ? Node extends Ast.Node ? EatWhitespace extends `,${infer Remainder}` ? ParseNodesHelper, [...Nodes, Node]> : [[...Nodes, Node], EatWhitespace] : ParserError<'Invalid node type in nodes helper'> : ParseNode; +/** + * Parses a node. + * A node is one of the following: + * - `*` + * - a field, as defined above + * - a renamed field, `renamed_field:field` + * - a spread field, `...field` + */ +type ParseNode = Input extends '' ? ParserError<'Empty string'> : Input extends `*${infer Remainder}` ? [Ast.StarNode, EatWhitespace] : Input extends `...${infer Remainder}` ? ParseField> extends [infer TargetField, `${infer Remainder}`] ? TargetField extends Ast.FieldNode ? [{ + type: 'spread'; + target: TargetField; +}, EatWhitespace] : ParserError<'Invalid target field type in spread'> : ParserError<`Unable to parse spread resource at \`${Input}\``> : ParseIdentifier extends [infer NameOrAlias, `${infer Remainder}`] ? EatWhitespace extends `::${infer _}` ? ParseField : EatWhitespace extends `:${infer Remainder}` ? ParseField> extends [infer Field, `${infer Remainder}`] ? Field extends Ast.FieldNode ? [Omit & { + alias: NameOrAlias; +}, EatWhitespace] : ParserError<'Invalid field type in alias parsing'> : ParserError<`Unable to parse renamed field at \`${Input}\``> : ParseField : ParserError<`Expected identifier at \`${Input}\``>; +/** + * Parses a field without preceding alias. + * A field is one of the following: + * - a top-level `count` field: https://docs.postgrest.org/en/v12/references/api/aggregate_functions.html#the-case-of-count + * - a field with an embedded resource + * - `field(nodes)` + * - `field!hint(nodes)` + * - `field!inner(nodes)` + * - `field!left(nodes)` + * - `field!hint!inner(nodes)` + * - `field!hint!left(nodes)` + * - a field without an embedded resource (see {@link ParseNonEmbeddedResourceField}) + */ +type ParseField = Input extends '' ? ParserError<'Empty string'> : ParseIdentifier extends [infer Name, `${infer Remainder}`] ? Name extends 'count' ? ParseCountField : Remainder extends `!inner${infer Remainder}` ? ParseEmbeddedResource> extends [ + infer Children, + `${infer Remainder}` +] ? Children extends Ast.Node[] ? [ + { + type: 'field'; + name: Name; + innerJoin: true; + children: Children; + }, + Remainder +] : ParserError<'Invalid children array in inner join'> : CreateParserErrorIfRequired>, `Expected embedded resource after "!inner" at \`${Remainder}\``> : EatWhitespace extends `!left${infer Remainder}` ? ParseEmbeddedResource> extends [ + infer Children, + `${infer Remainder}` +] ? Children extends Ast.Node[] ? [ + { + type: 'field'; + name: Name; + children: Children; + }, + EatWhitespace +] : ParserError<'Invalid children array in left join'> : CreateParserErrorIfRequired>, `Expected embedded resource after "!left" at \`${EatWhitespace}\``> : EatWhitespace extends `!${infer Remainder}` ? ParseIdentifier> extends [infer Hint, `${infer Remainder}`] ? EatWhitespace extends `!inner${infer Remainder}` ? ParseEmbeddedResource> extends [ + infer Children, + `${infer Remainder}` +] ? Children extends Ast.Node[] ? [ + { + type: 'field'; + name: Name; + hint: Hint; + innerJoin: true; + children: Children; + }, + EatWhitespace +] : ParserError<'Invalid children array in hint inner join'> : ParseEmbeddedResource> : ParseEmbeddedResource> extends [ + infer Children, + `${infer Remainder}` +] ? Children extends Ast.Node[] ? [ + { + type: 'field'; + name: Name; + hint: Hint; + children: Children; + }, + EatWhitespace +] : ParserError<'Invalid children array in hint'> : ParseEmbeddedResource> : ParserError<`Expected identifier after "!" at \`${EatWhitespace}\``> : EatWhitespace extends `(${infer _}` ? ParseEmbeddedResource> extends [ + infer Children, + `${infer Remainder}` +] ? Children extends Ast.Node[] ? [ + { + type: 'field'; + name: Name; + children: Children; + }, + EatWhitespace +] : ParserError<'Invalid children array in field'> : ParseEmbeddedResource> : ParseNonEmbeddedResourceField : ParserError<`Expected identifier at \`${Input}\``>; +type ParseCountField = ParseIdentifier extends ['count', `${infer Remainder}`] ? (EatWhitespace extends `()${infer Remainder_}` ? EatWhitespace : EatWhitespace) extends `${infer Remainder}` ? Remainder extends `::${infer _}` ? ParseFieldTypeCast extends [infer CastType, `${infer Remainder}`] ? [ + { + type: 'field'; + name: 'count'; + aggregateFunction: 'count'; + castType: CastType; + }, + Remainder +] : ParseFieldTypeCast : [{ + type: 'field'; + name: 'count'; + aggregateFunction: 'count'; +}, Remainder] : never : ParserError<`Expected "count" at \`${Input}\``>; +/** + * Parses an embedded resource, which is an opening `(`, followed by a sequence of + * 0 or more nodes separated by `,`, then a closing `)`. + * + * Returns a tuple of ["Parsed fields", "Remainder of text"], an error, + * or the original string input indicating that no opening `(` was found. + */ +type ParseEmbeddedResource = Input extends `(${infer Remainder}` ? EatWhitespace extends `)${infer Remainder}` ? [[], EatWhitespace] : ParseNodes> extends [infer Nodes, `${infer Remainder}`] ? Nodes extends Ast.Node[] ? EatWhitespace extends `)${infer Remainder}` ? [Nodes, EatWhitespace] : ParserError<`Expected ")" at \`${EatWhitespace}\``> : ParserError<'Invalid nodes array in embedded resource'> : ParseNodes> : ParserError<`Expected "(" at \`${Input}\``>; +/** + * Parses a field excluding embedded resources, without preceding field renaming. + * This is one of the following: + * - `field` + * - `field.aggregate()` + * - `field.aggregate()::type` + * - `field::type` + * - `field::type.aggregate()` + * - `field::type.aggregate()::type` + * - `field->json...` + * - `field->json.aggregate()` + * - `field->json.aggregate()::type` + * - `field->json::type` + * - `field->json::type.aggregate()` + * - `field->json::type.aggregate()::type` + */ +type ParseNonEmbeddedResourceField = ParseIdentifier extends [infer Name, `${infer Remainder}`] ? (Remainder extends `->${infer PathAndRest}` ? ParseJsonAccessor extends [ + infer PropertyName, + infer PropertyType, + `${infer Remainder}` +] ? [ + { + type: 'field'; + name: Name; + alias: PropertyName; + castType: PropertyType; + jsonPath: JsonPathToAccessor; + }, + Remainder +] : ParseJsonAccessor : [{ + type: 'field'; + name: Name; +}, Remainder]) extends infer Parsed ? Parsed extends [infer Field, `${infer Remainder}`] ? (Remainder extends `::${infer _}` ? ParseFieldTypeCast extends [infer CastType, `${infer Remainder}`] ? [Omit & { + castType: CastType; +}, Remainder] : ParseFieldTypeCast : [Field, Remainder]) extends infer Parsed ? Parsed extends [infer Field, `${infer Remainder}`] ? Remainder extends `.${infer _}` ? ParseFieldAggregation extends [ + infer AggregateFunction, + `${infer Remainder}` +] ? Remainder extends `::${infer _}` ? ParseFieldTypeCast extends [infer CastType, `${infer Remainder}`] ? [ + Omit & { + aggregateFunction: AggregateFunction; + castType: CastType; + }, + Remainder +] : ParseFieldTypeCast : [Field & { + aggregateFunction: AggregateFunction; +}, Remainder] : ParseFieldAggregation : [Field, Remainder] : Parsed : never : Parsed : never : ParserError<`Expected identifier at \`${Input}\``>; +/** + * Parses a JSON property accessor of the shape `->a->b->c`. The last accessor in + * the series may convert to text by using the ->> operator instead of ->. + * + * Returns a tuple of ["Last property name", "Last property type", "Remainder of text"] + */ +type ParseJsonAccessor = Input extends `->${infer Remainder}` ? Remainder extends `>${infer Remainder}` ? ParseIdentifier extends [infer Name, `${infer Remainder}`] ? [Name, 'text', EatWhitespace] : ParserError<'Expected property name after `->>`'> : ParseIdentifier extends [infer Name, `${infer Remainder}`] ? ParseJsonAccessor extends [ + infer PropertyName, + infer PropertyType, + `${infer Remainder}` +] ? [PropertyName, PropertyType, EatWhitespace] : [Name, 'json', EatWhitespace] : ParserError<'Expected property name after `->`'> : ParserError<'Expected ->'>; +/** + * Parses a field typecast (`::type`), returning a tuple of ["Type", "Remainder of text"]. + */ +type ParseFieldTypeCast = EatWhitespace extends `::${infer Remainder}` ? ParseIdentifier> extends [`${infer CastType}`, `${infer Remainder}`] ? [CastType, EatWhitespace] : ParserError<`Invalid type for \`::\` operator at \`${Remainder}\``> : ParserError<'Expected ::'>; +/** + * Parses a field aggregation (`.max()`), returning a tuple of ["Aggregate function", "Remainder of text"] + */ +type ParseFieldAggregation = EatWhitespace extends `.${infer Remainder}` ? ParseIdentifier> extends [ + `${infer FunctionName}`, + `${infer Remainder}` +] ? FunctionName extends Token.AggregateFunction ? EatWhitespace extends `()${infer Remainder}` ? [FunctionName, EatWhitespace] : ParserError<`Expected \`()\` after \`.\` operator \`${FunctionName}\``> : ParserError<`Invalid type for \`.\` operator \`${FunctionName}\``> : ParserError<`Invalid type for \`.\` operator at \`${Remainder}\``> : ParserError<'Expected .'>; +/** + * Parses a (possibly double-quoted) identifier. + * Identifiers are sequences of 1 or more letters. + */ +type ParseIdentifier = ParseLetters extends [infer Name, `${infer Remainder}`] ? [Name, EatWhitespace] : ParseQuotedLetters extends [infer Name, `${infer Remainder}`] ? [Name, EatWhitespace] : ParserError<`No (possibly double-quoted) identifier at \`${Input}\``>; +/** + * Parse a consecutive sequence of 1 or more letter, where letters are `[0-9a-zA-Z_]`. + */ +type ParseLetters = string extends Input ? GenericStringError : ParseLettersHelper extends [`${infer Letters}`, `${infer Remainder}`] ? Letters extends '' ? ParserError<`Expected letter at \`${Input}\``> : [Letters, Remainder] : ParseLettersHelper; +type ParseLettersHelper = string extends Input ? GenericStringError : Input extends `${infer L}${infer Remainder}` ? L extends Token.Letter ? ParseLettersHelper : [Acc, Input] : [Acc, '']; +/** + * Parse a consecutive sequence of 1 or more double-quoted letters, + * where letters are `[^"]`. + */ +type ParseQuotedLetters = string extends Input ? GenericStringError : Input extends `"${infer Remainder}` ? ParseQuotedLettersHelper extends [`${infer Letters}`, `${infer Remainder}`] ? Letters extends '' ? ParserError<`Expected string at \`${Remainder}\``> : [Letters, Remainder] : ParseQuotedLettersHelper : ParserError<`Not a double-quoted string at \`${Input}\``>; +type ParseQuotedLettersHelper = string extends Input ? GenericStringError : Input extends `${infer L}${infer Remainder}` ? L extends '"' ? [Acc, Remainder] : ParseQuotedLettersHelper : ParserError<`Missing closing double-quote in \`"${Acc}${Input}\``>; +/** + * Trims whitespace from the left of the input. + */ +type EatWhitespace = string extends Input ? GenericStringError : Input extends `${Token.Whitespace}${infer Remainder}` ? EatWhitespace : Input; +/** + * Creates a new {@link ParserError} if the given input is not already a parser error. + */ +type CreateParserErrorIfRequired = Input extends ParserError ? Input : ParserError; +/** + * Parser errors. + */ +export type ParserError = { + error: true; +} & Message; +type GenericStringError = ParserError<'Received a generic string'>; +export declare namespace Ast { + type Node = FieldNode | StarNode | SpreadNode; + type FieldNode = { + type: 'field'; + name: string; + alias?: string; + hint?: string; + innerJoin?: true; + castType?: string; + jsonPath?: string; + aggregateFunction?: Token.AggregateFunction; + children?: Node[]; + }; + type StarNode = { + type: 'star'; + }; + type SpreadNode = { + type: 'spread'; + target: FieldNode & { + children: Node[]; + }; + }; +} +declare namespace Token { + export type Whitespace = ' ' | '\n' | '\t'; + type LowerAlphabet = 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z'; + type Alphabet = LowerAlphabet | Uppercase; + type Digit = '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | '0'; + export type Letter = Alphabet | Digit | '_'; + export type AggregateFunction = 'count' | 'sum' | 'avg' | 'min' | 'max'; + export {}; +} +export {}; +//# sourceMappingURL=parser.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/parser.d.ts.map b/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/parser.d.ts.map new file mode 100644 index 0000000..0d86763 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/parser.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"parser.d.ts","sourceRoot":"","sources":["../../../src/select-query-parser/parser.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAA;AAC7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAA;AAE5C;;;;;;GAMG;AACH,MAAM,MAAM,UAAU,CAAC,KAAK,SAAS,MAAM,IAAI,MAAM,SAAS,KAAK,GAC/D,kBAAkB,GAClB,UAAU,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC,SAAS,CAAC,MAAM,KAAK,EAAE,GAAG,MAAM,SAAS,EAAE,CAAC,GAC1E,KAAK,SAAS,GAAG,CAAC,IAAI,EAAE,GACtB,aAAa,CAAC,SAAS,CAAC,SAAS,EAAE,GACjC,YAAY,CAAC,KAAK,CAAC,GACnB,WAAW,CAAC,qBAAqB,SAAS,EAAE,CAAC,GAC/C,WAAW,CAAC,+BAA+B,CAAC,GAC9C,UAAU,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC,CAAA;AAEtC;;;;GAIG;AAEH;;;;GAIG;AACH,KAAK,UAAU,CAAC,KAAK,SAAS,MAAM,IAAI,MAAM,SAAS,KAAK,GACxD,kBAAkB,GAClB,gBAAgB,CAAC,KAAK,EAAE,EAAE,CAAC,CAAA;AAE/B,KAAK,gBAAgB,CAAC,KAAK,SAAS,MAAM,EAAE,KAAK,SAAS,GAAG,CAAC,IAAI,EAAE,IAClE,SAAS,CAAC,KAAK,CAAC,SAAS,CAAC,MAAM,IAAI,EAAE,GAAG,MAAM,SAAS,EAAE,CAAC,GACvD,IAAI,SAAS,GAAG,CAAC,IAAI,GACnB,aAAa,CAAC,SAAS,C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 No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/parser.js b/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/parser.js new file mode 100644 index 0000000..7eb014e --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/parser.js @@ -0,0 +1,5 @@ +"use strict"; +// Credits to @bnjmnt4n (https://www.npmjs.com/package/postgrest-query) +// See https://github.com/PostgREST/postgrest/blob/2f91853cb1de18944a4556df09e52450b881cfb3/src/PostgREST/ApiRequest/QueryParams.hs#L282-L284 +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=parser.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/parser.js.map b/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/parser.js.map new file mode 100644 index 0000000..7771cfa --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/parser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"parser.js","sourceRoot":"","sources":["../../../src/select-query-parser/parser.ts"],"names":[],"mappings":";AAAA,uEAAuE;AACvE,6IAA6I"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/result.d.ts b/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/result.d.ts new file mode 100644 index 0000000..a1a9c59 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/result.d.ts @@ -0,0 +1,160 @@ +import { Ast, ParseQuery } from './parser'; +import { AggregateFunctions, ExtractFirstProperty, GenericSchema, IsNonEmptyArray, Prettify, TablesAndViews, TypeScriptTypes, ContainsNull, GenericRelationship, PostgreSQLTypes, GenericTable, ClientServerOptions } from './types'; +import { CheckDuplicateEmbededReference, GetComputedFields, GetFieldNodeResultName, IsAny, IsRelationNullable, IsStringUnion, JsonPathToType, ResolveRelationship, SelectQueryError } from './utils'; +import type { SpreadOnManyEnabled } from '../types/feature-flags'; +/** + * Main entry point for constructing the result type of a PostgREST query. + * + * @param Schema - Database schema. + * @param Row - The type of a row in the current table. + * @param RelationName - The name of the current table or view. + * @param Relationships - Relationships of the current table. + * @param Query - The select query string literal to parse. + */ +export type GetResult, RelationName, Relationships, Query extends string, ClientOptions extends ClientServerOptions> = IsAny extends true ? ParseQuery extends infer ParsedQuery ? ParsedQuery extends Ast.Node[] ? RelationName extends string ? ProcessNodesWithoutSchema : any : ParsedQuery : any : Relationships extends null ? ParseQuery extends infer ParsedQuery ? ParsedQuery extends Ast.Node[] ? RPCCallNodes : ParsedQuery : Row : ParseQuery extends infer ParsedQuery ? ParsedQuery extends Ast.Node[] ? RelationName extends string ? Relationships extends GenericRelationship[] ? ProcessNodes : SelectQueryError<'Invalid Relationships cannot infer result type'> : SelectQueryError<'Invalid RelationName cannot infer result type'> : ParsedQuery : never; +type ProcessSimpleFieldWithoutSchema = Field['aggregateFunction'] extends AggregateFunctions ? { + [K in GetFieldNodeResultName]: Field['castType'] extends PostgreSQLTypes ? TypeScriptTypes : number; +} : { + [K in GetFieldNodeResultName]: Field['castType'] extends PostgreSQLTypes ? TypeScriptTypes : any; +}; +type ProcessFieldNodeWithoutSchema = IsNonEmptyArray extends true ? { + [K in GetFieldNodeResultName]: Node['children'] extends Ast.Node[] ? ProcessNodesWithoutSchema[] : ProcessSimpleFieldWithoutSchema; +} : ProcessSimpleFieldWithoutSchema; +/** + * Processes a single Node without schema and returns the resulting TypeScript type. + */ +type ProcessNodeWithoutSchema = Node extends Ast.StarNode ? any : Node extends Ast.SpreadNode ? Node['target']['children'] extends Ast.StarNode[] ? any : Node['target']['children'] extends Ast.FieldNode[] ? { + [P in Node['target']['children'][number] as GetFieldNodeResultName

]: P['castType'] extends PostgreSQLTypes ? TypeScriptTypes : any; +} : any : Node extends Ast.FieldNode ? ProcessFieldNodeWithoutSchema : any; +/** + * Processes nodes when Schema is any, providing basic type inference + */ +type ProcessNodesWithoutSchema = {}> = Nodes extends [infer FirstNode, ...infer RestNodes] ? FirstNode extends Ast.Node ? RestNodes extends Ast.Node[] ? ProcessNodeWithoutSchema extends infer FieldResult ? FieldResult extends Record ? ProcessNodesWithoutSchema : FieldResult : any : any : any : Prettify; +/** + * Processes a single Node from a select chained after a rpc call + * + * @param Row - The type of a row in the current table. + * @param RelationName - The name of the current rpc function + * @param NodeType - The Node to process. + */ +export type ProcessRPCNode, RelationName extends string, NodeType extends Ast.Node> = NodeType['type'] extends Ast.StarNode['type'] ? Row : NodeType['type'] extends Ast.FieldNode['type'] ? ProcessSimpleField> : SelectQueryError<'RPC Unsupported node type.'>; +/** + * Process select call that can be chained after an rpc call + */ +export type RPCCallNodes, Acc extends Record = {}> = Nodes extends [infer FirstNode, ...infer RestNodes] ? FirstNode extends Ast.Node ? RestNodes extends Ast.Node[] ? ProcessRPCNode extends infer FieldResult ? FieldResult extends Record ? RPCCallNodes : FieldResult extends SelectQueryError ? SelectQueryError : SelectQueryError<'Could not retrieve a valid record or error value'> : SelectQueryError<'Processing node failed.'> : SelectQueryError<'Invalid rest nodes array in RPC call'> : SelectQueryError<'Invalid first node in RPC call'> : Prettify; +/** + * Recursively processes an array of Nodes and accumulates the resulting TypeScript type. + * + * @param Schema - Database schema. + * @param Row - The type of a row in the current table. + * @param RelationName - The name of the current table or view. + * @param Relationships - Relationships of the current table. + * @param Nodes - An array of AST nodes to process. + * @param Acc - Accumulator for the constructed type. + */ +export type ProcessNodes, RelationName extends string, Relationships extends GenericRelationship[], Nodes extends Ast.Node[], Acc extends Record = {}> = CheckDuplicateEmbededReference extends false ? Nodes extends [infer FirstNode, ...infer RestNodes] ? FirstNode extends Ast.Node ? RestNodes extends Ast.Node[] ? ProcessNode extends infer FieldResult ? FieldResult extends Record ? ProcessNodes : FieldResult extends SelectQueryError ? SelectQueryError : SelectQueryError<'Could not retrieve a valid record or error value'> : SelectQueryError<'Processing node failed.'> : SelectQueryError<'Invalid rest nodes array type in ProcessNodes'> : SelectQueryError<'Invalid first node type in ProcessNodes'> : Prettify : Prettify>; +/** + * Processes a single Node and returns the resulting TypeScript type. + * + * @param Schema - Database schema. + * @param Row - The type of a row in the current table. + * @param RelationName - The name of the current table or view. + * @param Relationships - Relationships of the current table. + * @param NodeType - The Node to process. + */ +export type ProcessNode, RelationName extends string, Relationships extends GenericRelationship[], NodeType extends Ast.Node> = NodeType['type'] extends Ast.StarNode['type'] ? GetComputedFields extends never ? Row : Omit> : NodeType['type'] extends Ast.SpreadNode['type'] ? ProcessSpreadNode> : NodeType['type'] extends Ast.FieldNode['type'] ? ProcessFieldNode> : SelectQueryError<'Unsupported node type.'>; +/** + * Processes a FieldNode and returns the resulting TypeScript type. + * + * @param Schema - Database schema. + * @param Row - The type of a row in the current table. + * @param RelationName - The name of the current table or view. + * @param Relationships - Relationships of the current table. + * @param Field - The FieldNode to process. + */ +type ProcessFieldNode, RelationName extends string, Relationships extends GenericRelationship[], Field extends Ast.FieldNode> = Field['children'] extends [] ? {} : IsNonEmptyArray extends true ? ProcessEmbeddedResource : ProcessSimpleField; +type ResolveJsonPathType = Path extends string ? JsonPathToType extends never ? TypeScriptTypes : JsonPathToType extends infer PathResult ? PathResult extends string ? PathResult : IsStringUnion extends true ? PathResult : CastType extends 'json' ? PathResult : TypeScriptTypes : TypeScriptTypes : TypeScriptTypes; +/** + * Processes a simple field (without embedded resources). + * + * @param Row - The type of a row in the current table. + * @param RelationName - The name of the current table or view. + * @param Field - The FieldNode to process. + */ +type ProcessSimpleField, RelationName extends string, Field extends Ast.FieldNode> = Field['name'] extends keyof Row | 'count' ? Field['aggregateFunction'] extends AggregateFunctions ? { + [K in GetFieldNodeResultName]: Field['castType'] extends PostgreSQLTypes ? TypeScriptTypes : number; +} : { + [K in GetFieldNodeResultName]: Field['castType'] extends PostgreSQLTypes ? ResolveJsonPathType : Row[Field['name']]; +} : SelectQueryError<`column '${Field['name']}' does not exist on '${RelationName}'.`>; +/** + * Processes an embedded resource (relation). + * + * @param Schema - Database schema. + * @param Row - The type of a row in the current table. + * @param RelationName - The name of the current table or view. + * @param Relationships - Relationships of the current table. + * @param Field - The FieldNode to process. + */ +export type ProcessEmbeddedResource & string> = ResolveRelationship extends infer Resolved ? Resolved extends { + referencedTable: Pick; + relation: GenericRelationship & { + match: 'refrel' | 'col' | 'fkname' | 'func'; + }; + direction: string; +} ? ProcessEmbeddedResourceResult : { + [K in GetFieldNodeResultName]: Resolved; +} : { + [K in GetFieldNodeResultName]: SelectQueryError<'Failed to resolve relationship.'> & string; +}; +/** + * Helper type to process the result of an embedded resource. + */ +type ProcessEmbeddedResourceResult; + relation: GenericRelationship & { + match: 'refrel' | 'col' | 'fkname' | 'func'; + isNotNullable?: boolean; + referencedRelation: string; + isSetofReturn?: boolean; + }; + direction: string; +}, Field extends Ast.FieldNode, CurrentTableOrView extends keyof TablesAndViews> = ProcessNodes extends Ast.Node[] ? Exclude : []> extends infer ProcessedChildren ? { + [K in GetFieldNodeResultName]: Resolved['direction'] extends 'forward' ? Field extends { + innerJoin: true; + } ? Resolved['relation']['isOneToOne'] extends true ? ProcessedChildren : ProcessedChildren[] : Resolved['relation']['isOneToOne'] extends true ? Resolved['relation']['match'] extends 'func' ? Resolved['relation']['isNotNullable'] extends true ? Resolved['relation']['isSetofReturn'] extends true ? ProcessedChildren : { + [P in keyof ProcessedChildren]: ProcessedChildren[P] | null; + } : ProcessedChildren | null : ProcessedChildren | null : ProcessedChildren[] : Resolved['relation']['referencedRelation'] extends CurrentTableOrView ? Resolved['relation']['match'] extends 'col' ? IsRelationNullable[CurrentTableOrView], Resolved['relation']> extends true ? ProcessedChildren | null : ProcessedChildren : ProcessedChildren[] : IsRelationNullable[CurrentTableOrView], Resolved['relation']> extends true ? Field extends { + innerJoin: true; + } ? ProcessedChildren : ProcessedChildren | null : ProcessedChildren; +} : { + [K in GetFieldNodeResultName]: SelectQueryError<'Failed to process embedded resource nodes.'> & string; +}; +/** + * Processes a SpreadNode by processing its target node. + * + * @param Schema - Database schema. + * @param Row - The type of a row in the current table. + * @param RelationName - The name of the current table or view. + * @param Relationships - Relationships of the current table. + * @param Spread - The SpreadNode to process. + */ +type ProcessSpreadNode, RelationName extends string, Relationships extends GenericRelationship[], Spread extends Ast.SpreadNode> = ProcessNode extends infer Result ? Result extends SelectQueryError ? SelectQueryError : ExtractFirstProperty extends unknown[] ? SpreadOnManyEnabled extends true ? ProcessManyToManySpreadNodeResult : { + [K in Spread['target']['name']]: SelectQueryError<`"${RelationName}" and "${Spread['target']['name']}" do not form a many-to-one or one-to-one relationship spread not possible`>; +} : ProcessSpreadNodeResult : never; +/** + * Helper type to process the result of a many-to-many spread node. + * Converts all fields in the spread object into arrays. + */ +type ProcessManyToManySpreadNodeResult = Result extends Record | null> ? Result : ExtractFirstProperty extends infer SpreadedObject ? SpreadedObject extends Array> ? { + [K in keyof SpreadedObject[number]]: Array; +} : SelectQueryError<'An error occurred spreading the many-to-many object'> : SelectQueryError<'An error occurred spreading the many-to-many object'>; +/** + * Helper type to process the result of a spread node. + */ +type ProcessSpreadNodeResult = Result extends Record | null> ? Result : ExtractFirstProperty extends infer SpreadedObject ? ContainsNull extends true ? Exclude<{ + [K in keyof SpreadedObject]: SpreadedObject[K] | null; +}, null> : Exclude<{ + [K in keyof SpreadedObject]: SpreadedObject[K]; +}, null> : SelectQueryError<'An error occurred spreading the object'>; +export {}; +//# sourceMappingURL=result.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/result.d.ts.map b/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/result.d.ts.map new file mode 100644 index 0000000..05e90d3 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/result.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"result.d.ts","sourceRoot":"","sources":["../../../src/select-query-parser/result.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,UAAU,EAAE,MAAM,UAAU,CAAA;AAC1C,OAAO,EAC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C,CAAC,MAAM,CAAC,GAAG,gBAAgB,CAAC,IAAI,YAAY,UAAU,MAAM,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,4EAA4E,CAAC;CAClL,GACH,uBAAuB,CAAC,MAAM,CAAC,GACnC,KAAK,CAAA;AAEX;;;GAGG;AACH,KAAK,iCAAiC,CAAC,MAAM,IAC3C,MAAM,SAAS,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,GAC1D,MAAM,GACN,oBAAoB,CAAC,MAAM,CAAC,SAAS,MAAM,cAAc,GACvD,cAAc,SAAS,KAAK,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,GACnD;KAAG,CAAC,IAAI,MAAM,cAAc,CAAC,MAAM,CAAC,GAAG,KAAK,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;CAAE,GACzE,gBAAgB,CAAC,qDAAqD,CAAC,GACzE,gBAAgB,CAAC,qDAAqD,CAAC,CAAA;AAE/E;;GAEG;AACH,KAAK,uBAAuB,CAAC,MAAM,IACjC,MAAM,SAAS,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,GAC1D,MAAM,GACN,oBAAoB,CAAC,MAAM,CAAC,SAAS,MAAM,cAAc,GACvD,YAAY,CAAC,cAAc,CAAC,SAAS,IAAI,GACvC,OAAO,CAAC;KAAG,CAAC,IAAI,MAAM,cAAc,GAAG,cAAc,CAAC,CAAC,CAAC,GAAG,IAAI;CAAE,EAAE,IAAI,CAAC,GACxE,OAAO,CAAC;KAAG,CAAC,IAAI,MAAM,cAAc,GAAG,cAAc,CAAC,CAAC,CAAC;CAAE,EAAE,IAAI,CAAC,GACnE,gBAAgB,CAAC,wCAAwC,CAAC,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/result.js b/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/result.js new file mode 100644 index 0000000..597898e --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/result.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=result.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/result.js.map b/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/result.js.map new file mode 100644 index 0000000..12c975e --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/result.js.map @@ -0,0 +1 @@ +{"version":3,"file":"result.js","sourceRoot":"","sources":["../../../src/select-query-parser/result.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/types.d.ts b/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/types.d.ts new file mode 100644 index 0000000..493c9ac --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/types.d.ts @@ -0,0 +1,32 @@ +import type { GenericRelationship, GenericSchema, GenericTable, ClientServerOptions, GenericSetofOption, GenericFunction } from '../types/common/common'; +import type { Prettify } from '../types/types'; +export type { GenericRelationship, GenericSchema, GenericTable, ClientServerOptions, GenericSetofOption, Prettify, GenericFunction, }; +export type AggregateWithoutColumnFunctions = 'count'; +export type AggregateWithColumnFunctions = 'sum' | 'avg' | 'min' | 'max' | AggregateWithoutColumnFunctions; +export type AggregateFunctions = AggregateWithColumnFunctions; +export type Json = string | number | boolean | null | { + [key: string]: Json | undefined; +} | Json[]; +type PostgresSQLNumberTypes = 'int2' | 'int4' | 'int8' | 'float4' | 'float8' | 'numeric'; +type PostgresSQLStringTypes = 'bytea' | 'bpchar' | 'varchar' | 'date' | 'text' | 'citext' | 'time' | 'timetz' | 'timestamp' | 'timestamptz' | 'uuid' | 'vector'; +type SingleValuePostgreSQLTypes = PostgresSQLNumberTypes | PostgresSQLStringTypes | 'bool' | 'json' | 'jsonb' | 'void' | 'record' | string; +type ArrayPostgreSQLTypes = `_${SingleValuePostgreSQLTypes}`; +type TypeScriptSingleValueTypes = T extends 'bool' ? boolean : T extends PostgresSQLNumberTypes ? number : T extends PostgresSQLStringTypes ? string : T extends 'json' | 'jsonb' ? Json : T extends 'void' ? undefined : T extends 'record' ? Record : unknown; +type StripUnderscore = T extends `_${infer U}` ? U : T; +export type PostgreSQLTypes = SingleValuePostgreSQLTypes | ArrayPostgreSQLTypes; +export type TypeScriptTypes = T extends ArrayPostgreSQLTypes ? TypeScriptSingleValueTypes>>[] : TypeScriptSingleValueTypes; +export type UnionToIntersection = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never; +export type LastOf = UnionToIntersection T : never> extends () => infer R ? R : never; +export type Push = [...T, V]; +export type UnionToTuple, N = [T] extends [never] ? true : false> = N extends true ? [] : Push>, L>; +export type UnionToArray = UnionToTuple; +export type ExtractFirstProperty = T extends { + [K in keyof T]: infer U; +} ? U : never; +export type ContainsNull = null extends T ? true : false; +export type IsNonEmptyArray = Exclude extends readonly [unknown, ...unknown[]] ? true : false; +export type TablesAndViews = Schema['Tables'] & Exclude; +export type GetTableRelationships = TablesAndViews[Tname] extends { + Relationships: infer R; +} ? R : false; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/types.d.ts.map b/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/types.d.ts.map new file mode 100644 index 0000000..d4e96ce --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/select-query-parser/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,mBAAmB,EACnB,aAAa,EACb,YAAY,EACZ,mBAAmB,EACnB,kBAAkB,EAClB,eAAe,EAChB,MAAM,wB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AM,MAAM,YAAY,CAAC,CAAC,IAAI,YAAY,CAAC,CAAC,CAAC,CAAA;AAG7C,MAAM,MAAM,oBAAoB,CAAC,CAAC,IAAI,CAAC,SAAS;KAAG,CAAC,IAAI,MAAM,CAAC,GAAG,MAAM,CAAC;CAAE,GAAG,CAAC,GAAG,KAAK,CAAA;AAGvF,MAAM,MAAM,YAAY,CAAC,CAAC,IAAI,IAAI,SAAS,CAAC,GAAG,IAAI,GAAG,KAAK,CAAA;AAE3D,MAAM,MAAM,eAAe,CAAC,CAAC,IAC3B,OAAO,CAAC,CAAC,EAAE,SAAS,CAAC,SAAS,SAAS,CAAC,OAAO,EAAE,GAAG,OAAO,EAAE,CAAC,GAAG,IAAI,GAAG,KAAK,CAAA;AAG/E,MAAM,MAAM,cAAc,CAAC,MAAM,SAAS,aAAa,IAAI,MAAM,CAAC,QAAQ,CAAC,GACzE,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,EAAE,CAAC,CAAA;AAE9B,MAAM,MAAM,qBAAqB,CAC/B,MAAM,SAAS,aAAa,EAC5B,KAAK,SAAS,MAAM,IAClB,cAAc,CAAC,MAAM,CAAC,CAAC,KAAK,CAAC,SAAS;IAAE,aAAa,EAAE,MAAM,CAAC,CAAA;CAAE,GAAG,CAAC,GAAG,KAAK,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/types.js b/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/types.js new file mode 100644 index 0000000..11e638d --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/types.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/types.js.map b/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/types.js.map new file mode 100644 index 0000000..03c3299 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/select-query-parser/types.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/utils.d.ts b/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/utils.d.ts new file mode 100644 index 0000000..b22e35f --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/utils.d.ts @@ -0,0 +1,283 @@ +import { Ast } from './parser'; +import { AggregateFunctions, ContainsNull, GenericRelationship, GenericSchema, GenericTable, IsNonEmptyArray, TablesAndViews, UnionToArray, GenericFunction, GenericSetofOption } from './types'; +export type IsAny = 0 extends 1 & T ? true : false; +export type SelectQueryError = { + error: true; +} & Message; +export type DeduplicateRelationships = T extends readonly [ + infer First, + ...infer Rest +] ? First extends Rest[number] ? DeduplicateRelationships : [First, ...DeduplicateRelationships] : T; +export type GetFieldNodeResultName = Field['alias'] extends string ? Field['alias'] : Field['aggregateFunction'] extends AggregateFunctions ? Field['aggregateFunction'] : Field['name']; +type FilterRelationNodes = UnionToArray<{ + [K in keyof Nodes]: Nodes[K] extends Ast.SpreadNode ? Nodes[K]['target'] : Nodes[K] extends Ast.FieldNode ? IsNonEmptyArray extends true ? Nodes[K] : never : never; +}[number]>; +type ResolveRelationships = UnionToArray<{ + [K in keyof Nodes]: Nodes[K] extends Ast.FieldNode ? ResolveRelationship extends infer Relation ? Relation extends { + relation: { + referencedRelation: string; + foreignKeyName: string; + match: string; + }; + from: string; + } ? { + referencedTable: Relation['relation']['referencedRelation']; + fkName: Relation['relation']['foreignKeyName']; + from: Relation['from']; + match: Relation['relation']['match']; + fieldName: GetFieldNodeResultName; + } : Relation : never : never; +}>[0]; +/** + * Checks if a relation is implicitly referenced twice, requiring disambiguation + */ +type IsDoubleReference = T extends { + referencedTable: infer RT; + fieldName: infer FN; + match: infer M; +} ? M extends 'col' | 'refrel' ? U extends { + referencedTable: RT; + fieldName: FN; + match: M; +} ? true : false : false : false; +/** + * Compares one element with all other elements in the array to find duplicates + */ +type CheckDuplicates = Arr extends [infer Head, ...infer Tail] ? IsDoubleReference extends true ? Head | CheckDuplicates : CheckDuplicates : never; +/** + * Iterates over the elements of the array to find duplicates + */ +type FindDuplicatesWithinDeduplicated = Arr extends [infer Head, ...infer Tail] ? CheckDuplicates | FindDuplicatesWithinDeduplicated : never; +type FindDuplicates = FindDuplicatesWithinDeduplicated>; +export type CheckDuplicateEmbededReference = FilterRelationNodes extends infer RelationsNodes ? RelationsNodes extends Ast.FieldNode[] ? ResolveRelationships extends infer ResolvedRels ? ResolvedRels extends unknown[] ? FindDuplicates extends infer Duplicates ? Duplicates extends never ? false : Duplicates extends { + fieldName: infer FieldName; +} ? FieldName extends string ? { + [K in FieldName]: SelectQueryError<`table "${RelationName}" specified more than once use hinting for desambiguation`>; +} : false : false : false : false : false : false : false; +/** + * Returns a boolean representing whether there is a foreign key referencing + * a given relation. + */ +type HasFKeyToFRel = Relationships extends [infer R] ? R extends { + referencedRelation: FRelName; +} ? true : false : Relationships extends [infer R, ...infer Rest] ? HasFKeyToFRel extends true ? true : HasFKeyToFRel : false; +/** + * Checks if there is more than one relation to a given foreign relation name in the Relationships. + */ +type HasMultipleFKeysToFRelDeduplicated = Relationships extends [ + infer R, + ...infer Rest +] ? R extends { + referencedRelation: FRelName; +} ? HasFKeyToFRel extends true ? true : HasMultipleFKeysToFRelDeduplicated : HasMultipleFKeysToFRelDeduplicated : false; +type HasMultipleFKeysToFRel = HasMultipleFKeysToFRelDeduplicated>; +type CheckRelationshipError & string, FoundRelation> = FoundRelation extends SelectQueryError ? FoundRelation : FoundRelation extends { + relation: { + referencedRelation: infer RelatedRelationName; + name: string; + }; + direction: 'reverse'; +} ? RelatedRelationName extends string ? HasMultipleFKeysToFRel extends true ? SelectQueryError<`Could not embed because more than one relationship was found for '${RelatedRelationName}' and '${CurrentTableOrView}' you need to hint the column with ${RelatedRelationName}! ?`> : FoundRelation : never : FoundRelation extends { + relation: { + referencedRelation: infer RelatedRelationName; + name: string; + }; + direction: 'forward'; + from: infer From; +} ? RelatedRelationName extends string ? From extends keyof TablesAndViews & string ? HasMultipleFKeysToFRel[From]['Relationships']> extends true ? SelectQueryError<`Could not embed because more than one relationship was found for '${From}' and '${RelatedRelationName}' you need to hint the column with ${From}! ?`> : FoundRelation : never : never : FoundRelation; +/** + * Resolves relationships for embedded resources and retrieves the referenced Table + */ +export type ResolveRelationship & string> = ResolveReverseRelationship extends infer ReverseRelationship ? ReverseRelationship extends false ? CheckRelationshipError> : CheckRelationshipError : never; +/** + * Resolves reverse relationships (from children to parent) + */ +type ResolveReverseRelationship & string> = FindFieldMatchingRelationships extends infer FoundRelation ? FoundRelation extends never ? false : FoundRelation extends { + referencedRelation: infer RelatedRelationName; +} ? RelatedRelationName extends string ? RelatedRelationName extends keyof TablesAndViews ? FoundRelation extends { + hint: string; +} ? { + referencedTable: TablesAndViews[RelatedRelationName]; + relation: FoundRelation; + direction: 'reverse'; + from: CurrentTableOrView; +} : HasMultipleFKeysToFRel extends true ? SelectQueryError<`Could not embed because more than one relationship was found for '${RelatedRelationName}' and '${CurrentTableOrView}' you need to hint the column with ${RelatedRelationName}! ?`> : { + referencedTable: TablesAndViews[RelatedRelationName]; + relation: FoundRelation; + direction: 'reverse'; + from: CurrentTableOrView; +} : SelectQueryError<`Relation '${RelatedRelationName}' not found in schema.`> : false : false : false; +export type FindMatchingTableRelationships = Relationships extends [infer R, ...infer Rest] ? Rest extends GenericRelationship[] ? R extends { + referencedRelation: infer ReferencedRelation; +} ? ReferencedRelation extends keyof Schema['Tables'] ? R extends { + foreignKeyName: value; +} ? R & { + match: 'fkname'; +} : R extends { + referencedRelation: value; +} ? R & { + match: 'refrel'; +} : R extends { + columns: [value]; +} ? R & { + match: 'col'; +} : FindMatchingTableRelationships : FindMatchingTableRelationships : false : false : false; +export type FindMatchingViewRelationships = Relationships extends [infer R, ...infer Rest] ? Rest extends GenericRelationship[] ? R extends { + referencedRelation: infer ReferencedRelation; +} ? ReferencedRelation extends keyof Schema['Views'] ? R extends { + foreignKeyName: value; +} ? R & { + match: 'fkname'; +} : R extends { + referencedRelation: value; +} ? R & { + match: 'refrel'; +} : R extends { + columns: [value]; +} ? R & { + match: 'col'; +} : FindMatchingViewRelationships : FindMatchingViewRelationships : false : false : false; +export type FindMatchingHintTableRelationships = Relationships extends [infer R, ...infer Rest] ? Rest extends GenericRelationship[] ? R extends { + referencedRelation: infer ReferencedRelation; +} ? ReferencedRelation extends name ? R extends { + foreignKeyName: hint; +} ? R & { + match: 'fkname'; +} : R extends { + referencedRelation: hint; +} ? R & { + match: 'refrel'; +} : R extends { + columns: [hint]; +} ? R & { + match: 'col'; +} : FindMatchingHintTableRelationships : FindMatchingHintTableRelationships : false : false : false; +export type FindMatchingHintViewRelationships = Relationships extends [infer R, ...infer Rest] ? Rest extends GenericRelationship[] ? R extends { + referencedRelation: infer ReferencedRelation; +} ? ReferencedRelation extends name ? R extends { + foreignKeyName: hint; +} ? R & { + match: 'fkname'; +} : R extends { + referencedRelation: hint; +} ? R & { + match: 'refrel'; +} : R extends { + columns: [hint]; +} ? R & { + match: 'col'; +} : FindMatchingHintViewRelationships : FindMatchingHintViewRelationships : false : false : false; +type IsColumnsNullable, Columns extends (keyof Table['Row'])[]> = Columns extends [infer Column, ...infer Rest] ? Column extends keyof Table['Row'] ? ContainsNull extends true ? true : IsColumnsNullable : false : false; +export type IsRelationNullable
= IsColumnsNullable; +type TableForwardRelationships = TName extends keyof TablesAndViews ? UnionToArray>> extends infer R ? R extends (GenericRelationship & { + from: keyof TablesAndViews; +})[] ? R : [] : [] : []; +type RecursivelyFindRelationships> = Keys extends infer K ? K extends keyof TablesAndViews ? FilterRelationships[K]['Relationships'], TName, K> extends never ? RecursivelyFindRelationships> : FilterRelationships[K]['Relationships'], TName, K> | RecursivelyFindRelationships> : false : false; +type FilterRelationships = R extends readonly (infer Rel)[] ? Rel extends { + referencedRelation: TName; +} ? Rel & { + from: From; +} : never : never; +export type ResolveForwardRelationship & string> = FindFieldMatchingRelationships[Field['name']]['Relationships'], Ast.FieldNode & { + name: CurrentTableOrView; + hint: Field['hint']; +}> extends infer FoundByName ? FoundByName extends GenericRelationship ? { + referencedTable: TablesAndViews[Field['name']]; + relation: FoundByName; + direction: 'forward'; + from: Field['name']; + type: 'found-by-name'; +} : FindFieldMatchingRelationships, Field> extends infer FoundByMatch ? FoundByMatch extends GenericRelationship & { + from: keyof TablesAndViews; +} ? { + referencedTable: TablesAndViews[FoundByMatch['from']]; + relation: FoundByMatch; + direction: 'forward'; + from: CurrentTableOrView; + type: 'found-by-match'; +} : FindJoinTableRelationship extends infer FoundByJoinTable ? FoundByJoinTable extends GenericRelationship ? { + referencedTable: TablesAndViews[FoundByJoinTable['referencedRelation']]; + relation: FoundByJoinTable & { + match: 'refrel'; + }; + direction: 'forward'; + from: CurrentTableOrView; + type: 'found-by-join-table'; +} : ResolveEmbededFunctionJoinTableRelationship extends infer FoundEmbededFunctionJoinTableRelation ? FoundEmbededFunctionJoinTableRelation extends GenericSetofOption ? { + referencedTable: TablesAndViews[FoundEmbededFunctionJoinTableRelation['to']]; + relation: { + foreignKeyName: `${Field['name']}_${CurrentTableOrView}_${FoundEmbededFunctionJoinTableRelation['to']}_forward`; + columns: []; + isOneToOne: FoundEmbededFunctionJoinTableRelation['isOneToOne'] extends true ? true : false; + referencedColumns: []; + referencedRelation: FoundEmbededFunctionJoinTableRelation['to']; + } & { + match: 'func'; + isNotNullable: FoundEmbededFunctionJoinTableRelation['isNotNullable'] extends true ? true : FoundEmbededFunctionJoinTableRelation['isSetofReturn'] extends true ? false : true; + isSetofReturn: FoundEmbededFunctionJoinTableRelation['isSetofReturn']; + }; + direction: 'forward'; + from: CurrentTableOrView; + type: 'found-by-embeded-function'; +} : SelectQueryError<`could not find the relation between ${CurrentTableOrView} and ${Field['name']}`> : SelectQueryError<`could not find the relation between ${CurrentTableOrView} and ${Field['name']}`> : SelectQueryError<`could not find the relation between ${CurrentTableOrView} and ${Field['name']}`> : SelectQueryError<`could not find the relation between ${CurrentTableOrView} and ${Field['name']}`> : SelectQueryError<`could not find the relation between ${CurrentTableOrView} and ${Field['name']}`>; +/** + * Given a CurrentTableOrView, finds all join tables to this relation. + * For example, if products and categories are linked via product_categories table: + * + * @example + * Given: + * - CurrentTableView = 'products' + * - FieldName = "categories" + * + * It should return this relationship from product_categories: + * { + * foreignKeyName: "product_categories_category_id_fkey", + * columns: ["category_id"], + * isOneToOne: false, + * referencedRelation: "categories", + * referencedColumns: ["id"] + * } + */ +type ResolveJoinTableRelationship & string, FieldName extends string> = { + [TableName in keyof TablesAndViews]: DeduplicateRelationships[TableName]['Relationships']> extends readonly (infer Rel)[] ? Rel extends { + referencedRelation: CurrentTableOrView; + } ? DeduplicateRelationships[TableName]['Relationships']> extends readonly (infer OtherRel)[] ? OtherRel extends { + referencedRelation: FieldName; + } ? OtherRel : never : never : never : never; +}[keyof TablesAndViews]; +type ResolveEmbededFunctionJoinTableRelationship & string, FieldName extends string> = FindMatchingFunctionBySetofFrom extends infer Fn ? Fn extends GenericFunction ? Fn['SetofOptions'] : false : false; +export type FindJoinTableRelationship & string, FieldName extends string> = ResolveJoinTableRelationship extends infer Result ? [Result] extends [never] ? false : Result : never; +/** + * Finds a matching relationship based on the FieldNode's name and optional hint. + */ +export type FindFieldMatchingRelationships = Field extends { + hint: string; +} ? FindMatchingHintTableRelationships extends GenericRelationship ? FindMatchingHintTableRelationships & { + branch: 'found-in-table-via-hint'; + hint: Field['hint']; +} : FindMatchingHintViewRelationships extends GenericRelationship ? FindMatchingHintViewRelationships & { + branch: 'found-in-view-via-hint'; + hint: Field['hint']; +} : SelectQueryError<'Failed to find matching relation via hint'> : FindMatchingTableRelationships extends GenericRelationship ? FindMatchingTableRelationships & { + branch: 'found-in-table-via-name'; + name: Field['name']; +} : FindMatchingViewRelationships extends GenericRelationship ? FindMatchingViewRelationships & { + branch: 'found-in-view-via-name'; + name: Field['name']; +} : SelectQueryError<'Failed to find matching relation via name'>; +export type JsonPathToAccessor = Path extends `${infer P1}->${infer P2}` ? P2 extends `>${infer Rest}` ? JsonPathToAccessor<`${P1}.${Rest}`> : P2 extends string ? JsonPathToAccessor<`${P1}.${P2}`> : Path : Path extends `>${infer Rest}` ? JsonPathToAccessor : Path extends `${infer P1}::${infer _}` ? JsonPathToAccessor : Path extends `${infer P1}${')' | ','}${infer _}` ? P1 : Path; +export type JsonPathToType = Path extends '' ? T : ContainsNull extends true ? JsonPathToType, Path> : Path extends `${infer Key}.${infer Rest}` ? Key extends keyof T ? JsonPathToType : never : Path extends keyof T ? T[Path] : never; +export type IsStringUnion = string extends T ? false : T extends string ? [T] extends [never] ? false : true : false; +type MatchingFunctionBySetofFrom = Fn['SetofOptions'] extends GenericSetofOption ? TableName extends Fn['SetofOptions']['from'] ? Fn : never : false; +type FindMatchingFunctionBySetofFrom = FnUnion extends infer Fn extends GenericFunction ? MatchingFunctionBySetofFrom : false; +type ComputedField, FieldName extends keyof TablesAndViews[RelationName]['Row']> = FieldName extends keyof Schema['Functions'] ? Schema['Functions'][FieldName] extends { + Args: { + '': TablesAndViews[RelationName]['Row']; + }; + Returns: any; +} ? FieldName : never : never; +export type GetComputedFields> = { + [K in keyof TablesAndViews[RelationName]['Row']]: ComputedField; +}[keyof TablesAndViews[RelationName]['Row']]; +export {}; +//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/utils.d.ts.map b/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/utils.d.ts.map new file mode 100644 index 0000000..5aec0b6 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/select-query-parser/utils.ts"],"names":[],"mappings":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e,EAC1B,SAAS,SAAS,MAAM,IACtB,EAAE,CAAC,cAAc,CAAC,SAAS,kBAAkB,GAC7C,SAAS,SAAS,EAAE,CAAC,cAAc,CAAC,CAAC,MAAM,CAAC,GAC1C,EAAE,GACF,KAAK,GACP,KAAK,CAAA;AAET,KAAK,+BAA+B,CAClC,OAAO,EACP,SAAS,SAAS,MAAM,IACtB,OAAO,SAAS,MAAM,EAAE,SAAS,eAAe,GAChD,2BAA2B,CAAC,EAAE,EAAE,SAAS,CAAC,GAC1C,KAAK,CAAA;AAET,KAAK,aAAa,CAChB,MAAM,SAAS,aAAa,EAC5B,YAAY,SAAS,MAAM,cAAc,CAAC,MAAM,CAAC,EACjD,SAAS,SAAS,MAAM,cAAc,CAAC,MAAM,CAAC,CAAC,YAAY,CAAC,CAAC,KAAK,CAAC,IACjE,SAAS,SAAS,MAAM,MAAM,CAAC,WAAW,CAAC,GAC3C,MAAM,CAAC,WAAW,CAAC,CAAC,SAAS,CAAC,SAAS;IACrC,IAAI,EAAE;QAAE,EAAE,EAAE,cAAc,CAAC,MAAM,CAAC,CAAC,YAAY,CAAC,CAAC,KAAK,CAAC,CAAA;KAAE,CAAA;IACzD,OAAO,EAAE,GAAG,CAAA;CACb,GACC,SAAS,GACT,KAAK,GACP,KAAK,CAAA;AAIT,MAAM,MAAM,iBAAiB,CAC3B,MAAM,SAAS,aAAa,EAC5B,YAAY,SAAS,MAAM,cAAc,CAAC,MAAM,CAAC,IAC/C;KACD,CAAC,IAAI,MAAM,cAAc,CAAC,MAAM,CAAC,CAAC,YAAY,CAAC,CAAC,KAAK,CAAC,GAAG,aAAa,CAAC,MAAM,EAAE,YAAY,EAAE,CAAC,CAAC;CACjG,CAAC,MAAM,cAAc,CAAC,MAAM,CAAC,CAAC,YAAY,CAAC,CAAC,KAAK,CAAC,CAAC,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/utils.js b/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/utils.js new file mode 100644 index 0000000..ee02fa6 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/utils.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/utils.js.map b/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/utils.js.map new file mode 100644 index 0000000..445f7d5 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/select-query-parser/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/select-query-parser/utils.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/common/common.d.ts b/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/common/common.d.ts new file mode 100644 index 0000000..cde152d --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/common/common.d.ts @@ -0,0 +1,46 @@ +export type Fetch = typeof fetch; +export type GenericRelationship = { + foreignKeyName: string; + columns: string[]; + isOneToOne?: boolean; + referencedRelation: string; + referencedColumns: string[]; +}; +export type GenericTable = { + Row: Record; + Insert: Record; + Update: Record; + Relationships: GenericRelationship[]; +}; +export type GenericUpdatableView = { + Row: Record; + Insert: Record; + Update: Record; + Relationships: GenericRelationship[]; +}; +export type GenericNonUpdatableView = { + Row: Record; + Relationships: GenericRelationship[]; +}; +export type GenericView = GenericUpdatableView | GenericNonUpdatableView; +export type GenericSetofOption = { + isSetofReturn?: boolean | undefined; + isOneToOne?: boolean | undefined; + isNotNullable?: boolean | undefined; + to: string; + from: string; +}; +export type GenericFunction = { + Args: Record | never; + Returns: unknown; + SetofOptions?: GenericSetofOption; +}; +export type GenericSchema = { + Tables: Record; + Views: Record; + Functions: Record; +}; +export type ClientServerOptions = { + PostgrestVersion?: string; +}; +//# sourceMappingURL=common.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/common/common.d.ts.map b/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/common/common.d.ts.map new file mode 100644 index 0000000..5514b04 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/common/common.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"common.d.ts","sourceRoot":"","sources":["../../../../src/types/common/common.ts"],"names":[],"mappings":"AAEA,MAAM,MAAM,KAAK,GAAG,OAAO,KAAK,CAAA;AAEhC,MAAM,MAAM,mBAAmB,GAAG;IAChC,cAAc,EAAE,MAAM,CAAA;IACtB,OAAO,EAAE,MAAM,EAAE,CAAA;IACjB,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB,kBAAkB,EAAE,MAAM,CAAA;IAC1B,iBAAiB,EAAE,MAAM,EAAE,CAAA;CAC5B,CAAA;AAED,MAAM,MAAM,YAAY,GAAG;IACzB,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC5B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC/B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC/B,aAAa,EAAE,mBAAmB,EAAE,CAAA;CACrC,CAAA;AAED,MAAM,MAAM,oBAAoB,GAAG;IACjC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC5B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC/B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC/B,aAAa,EAAE,mBAAmB,EAAE,CAAA;CACrC,CAAA;AAED,MAAM,MAAM,uBAAuB,GAAG;IACpC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC5B,aAAa,EAAE,mBAAmB,EAAE,CAAA;CACrC,CAAA;AAED,MAAM,MAAM,WAAW,GAAG,oBAAoB,GAAG,uBAAuB,CAAA;AAExE,MAAM,MAAM,kBAAkB,GAAG;IAC/B,aAAa,CAAC,EAAE,OAAO,GAAG,SAAS,CAAA;IACnC,UAAU,CAAC,EAAE,OAAO,GAAG,SAAS,CAAA;IAChC,aAAa,CAAC,EAAE,OAAO,GAAG,SAAS,CAAA;IACnC,EAAE,EAAE,MAAM,CAAA;IACV,IAAI,EAAE,MAAM,CAAA;CACb,CAAA;AAED,MAAM,MAAM,eAAe,GAAG;IAC5B,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,KAAK,CAAA;IACrC,OAAO,EAAE,OAAO,CAAA;IAChB,YAAY,CAAC,EAAE,kBAAkB,CAAA;CAClC,CAAA;AAED,MAAM,MAAM,aAAa,GAAG;IAC1B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,CAAA;IACpC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAA;IAClC,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,eAAe,CAAC,CAAA;CAC3C,CAAA;AAED,MAAM,MAAM,mBAAmB,GAAG;IAChC,gBAAgB,CAAC,EAAE,MAAM,CAAA;CAC1B,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/common/common.js b/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/common/common.js new file mode 100644 index 0000000..0b169a2 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/common/common.js @@ -0,0 +1,4 @@ +"use strict"; +// Types that are shared between supabase-js and postgrest-js +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=common.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/common/common.js.map b/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/common/common.js.map new file mode 100644 index 0000000..7f46fa4 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/common/common.js.map @@ -0,0 +1 @@ +{"version":3,"file":"common.js","sourceRoot":"","sources":["../../../../src/types/common/common.ts"],"names":[],"mappings":";AAAA,6DAA6D"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/common/rpc.d.ts b/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/common/rpc.d.ts new file mode 100644 index 0000000..8626432 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/common/rpc.d.ts @@ -0,0 +1,40 @@ +import type { GenericFunction, GenericSchema, GenericSetofOption } from './common'; +type IsMatchingArgs = [FnArgs] extends [Record] ? PassedArgs extends Record ? true : false : keyof PassedArgs extends keyof FnArgs ? PassedArgs extends FnArgs ? true : false : false; +type MatchingFunctionArgs = Fn extends { + Args: infer A extends GenericFunction['Args']; +} ? IsMatchingArgs extends true ? Fn : never : false; +type FindMatchingFunctionByArgs = FnUnion extends infer Fn extends GenericFunction ? MatchingFunctionArgs : false; +type TablesAndViews = Schema['Tables'] & Exclude; +type UnionToIntersection = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never; +type LastOf = UnionToIntersection T : never> extends () => infer R ? R : never; +type IsAny = 0 extends 1 & T ? true : false; +type ExactMatch = [T] extends [S] ? ([S] extends [T] ? true : false) : false; +type ExtractExactFunction = Fns extends infer F ? F extends GenericFunction ? ExactMatch extends true ? F : never : never : never; +type IsNever = [T] extends [never] ? true : false; +type RpcFunctionNotFound = { + Row: any; + Result: { + error: true; + } & "Couldn't infer function definition matching provided arguments"; + RelationName: FnName; + Relationships: null; +}; +type CrossSchemaError = { + error: true; +} & `Function returns SETOF from a different schema ('${TableRef}'). Use .overrideTypes() to specify the return type explicitly.`; +export type GetRpcFunctionFilterBuilderByArgs = { + 0: Schema['Functions'][FnName]; + 1: IsAny extends true ? any : IsNever extends true ? IsNever> extends true ? LastOf : ExtractExactFunction : Args extends Record ? LastOf : Args extends GenericFunction['Args'] ? IsNever>> extends true ? LastOf : LastOf> : ExtractExactFunction extends GenericFunction ? ExtractExactFunction : any; +}[1] extends infer Fn ? IsAny extends true ? { + Row: any; + Result: any; + RelationName: FnName; + Relationships: null; +} : Fn extends GenericFunction ? { + Row: Fn['SetofOptions'] extends GenericSetofOption ? Fn['SetofOptions']['to'] extends keyof TablesAndViews ? TablesAndViews[Fn['SetofOptions']['to']]['Row'] : Fn['Returns'] extends any[] ? Fn['Returns'][number] extends Record ? Fn['Returns'][number] : CrossSchemaError : Fn['Returns'] extends Record ? Fn['Returns'] : CrossSchemaError : Fn['Returns'] extends any[] ? Fn['Returns'][number] extends Record ? Fn['Returns'][number] : never : Fn['Returns'] extends Record ? Fn['Returns'] : never; + Result: Fn['SetofOptions'] extends GenericSetofOption ? Fn['SetofOptions']['isSetofReturn'] extends true ? Fn['SetofOptions']['isOneToOne'] extends true ? Fn['Returns'][] : Fn['Returns'] : Fn['Returns'] : Fn['Returns']; + RelationName: Fn['SetofOptions'] extends GenericSetofOption ? Fn['SetofOptions']['to'] : FnName; + Relationships: Fn['SetofOptions'] extends GenericSetofOption ? Fn['SetofOptions']['to'] extends keyof Schema['Tables'] ? Schema['Tables'][Fn['SetofOptions']['to']]['Relationships'] : Fn['SetofOptions']['to'] extends keyof Schema['Views'] ? Schema['Views'][Fn['SetofOptions']['to']]['Relationships'] : null : null; +} : Fn extends false ? RpcFunctionNotFound : RpcFunctionNotFound : RpcFunctionNotFound; +export {}; +//# sourceMappingURL=rpc.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/common/rpc.d.ts.map b/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/common/rpc.d.ts.map new file mode 100644 index 0000000..f20dce3 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/common/rpc.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rpc.d.ts","sourceRoot":"","sources":["../../../../src/types/common/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Ac,CAAC,CAAC,eAAe,CAAC,SAAS,IAAI,GAC9C,EAAE,CAAC,cAAc,CAAC,CAAC,YAAY,CAAC,SAAS,IAAI,GAC3C,EAAE,CAAC,SAAS,CAAC,EAAE,GACf,EAAE,CAAC,SAAS,CAAC,GACf,EAAE,CAAC,SAAS,CAAC,GACf,EAAE,CAAC,SAAS,CAAC,CAAA;IACjB,YAAY,EAAE,EAAE,CAAC,cAAc,CAAC,SAAS,kBAAkB,GACvD,EAAE,CAAC,cAAc,CAAC,CAAC,IAAI,CAAC,GACxB,MAAM,CAAA;IACV,aAAa,EAAE,EAAE,CAAC,cAAc,CAAC,SAAS,kBAAkB,GACxD,EAAE,CAAC,cAAc,CAAC,CAAC,IAAI,CAAC,SAAS,MAAM,MAAM,CAAC,QAAQ,CAAC,GACrD,MAAM,CAAC,QAAQ,CAAC,CAAC,EAAE,CAAC,cAAc,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,eAAe,CAAC,GAC3D,EAAE,CAAC,cAAc,CAAC,CAAC,IAAI,CAAC,SAAS,MAAM,MAAM,CAAC,OAAO,CAAC,GACpD,MAAM,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,cAAc,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,eAAe,CAAC,GAC1D,IAAI,GACR,IAAI,CAAA;CACT,GAED,EAAE,SAAS,KAAK,GACd,mBAAmB,CAAC,MAAM,CAAC,GAC3B,mBAAmB,CAAC,MAAM,CAAC,GACjC,mBAAmB,CAAC,MAAM,CAAC,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/common/rpc.js b/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/common/rpc.js new file mode 100644 index 0000000..43a02af --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/common/rpc.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=rpc.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/common/rpc.js.map b/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/common/rpc.js.map new file mode 100644 index 0000000..8622927 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/common/rpc.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rpc.js","sourceRoot":"","sources":["../../../../src/types/common/rpc.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/feature-flags.d.ts b/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/feature-flags.d.ts new file mode 100644 index 0000000..af120b8 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/feature-flags.d.ts @@ -0,0 +1,7 @@ +type IsPostgrest13 = PostgrestVersion extends `13${string}` ? true : false; +type IsPostgrest14 = PostgrestVersion extends `14${string}` ? true : false; +type IsPostgrestVersionGreaterThan12 = IsPostgrest13 extends true ? true : IsPostgrest14 extends true ? true : false; +export type MaxAffectedEnabled = IsPostgrestVersionGreaterThan12 extends true ? true : false; +export type SpreadOnManyEnabled = IsPostgrestVersionGreaterThan12 extends true ? true : false; +export {}; +//# sourceMappingURL=feature-flags.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/feature-flags.d.ts.map b/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/feature-flags.d.ts.map new file mode 100644 index 0000000..e82abf6 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/feature-flags.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"feature-flags.d.ts","sourceRoot":"","sources":["../../../src/types/feature-flags.ts"],"names":[],"mappings":"AAAA,KAAK,aAAa,CAAC,gBAAgB,SAAS,MAAM,GAAG,SAAS,IAC5D,gBAAgB,SAAS,KAAK,MAAM,EAAE,GAAG,IAAI,GAAG,KAAK,CAAA;AACvD,KAAK,aAAa,CAAC,gBAAgB,SAAS,MAAM,GAAG,SAAS,IAC5D,gBAAgB,SAAS,KAAK,MAAM,EAAE,GAAG,IAAI,GAAG,KAAK,CAAA;AAEvD,KAAK,+BAA+B,CAAC,gBAAgB,SAAS,MAAM,GAAG,SAAS,IAC9E,aAAa,CAAC,gBAAgB,CAAC,SAAS,IAAI,GACxC,IAAI,GACJ,aAAa,CAAC,gBAAgB,CAAC,SAAS,IAAI,GAC1C,IAAI,GACJ,KAAK,CAAA;AAEb,MAAM,MAAM,kBAAkB,CAAC,gBAAgB,SAAS,MAAM,GAAG,SAAS,IACxE,+BAA+B,CAAC,gBAAgB,CAAC,SAAS,IAAI,GAAG,IAAI,GAAG,KAAK,CAAA;AAE/E,MAAM,MAAM,mBAAmB,CAAC,gBAAgB,SAAS,MAAM,GAAG,SAAS,IACzE,+BAA+B,CAAC,gBAAgB,CAAC,SAAS,IAAI,GAAG,IAAI,GAAG,KAAK,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/feature-flags.js b/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/feature-flags.js new file mode 100644 index 0000000..956f9c2 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/feature-flags.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=feature-flags.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/feature-flags.js.map b/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/feature-flags.js.map new file mode 100644 index 0000000..4e2db75 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/feature-flags.js.map @@ -0,0 +1 @@ +{"version":3,"file":"feature-flags.js","sourceRoot":"","sources":["../../../src/types/feature-flags.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/types.d.ts b/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/types.d.ts new file mode 100644 index 0000000..8d129dc --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/types.d.ts @@ -0,0 +1,69 @@ +import PostgrestError from '../PostgrestError'; +import { ContainsNull } from '../select-query-parser/types'; +import { SelectQueryError } from '../select-query-parser/utils'; +import { ClientServerOptions } from './common/common'; +/** + * Response format + * + * {@link https://github.com/supabase/supabase-js/issues/32} + */ +interface PostgrestResponseBase { + status: number; + statusText: string; +} +export interface PostgrestResponseSuccess extends PostgrestResponseBase { + error: null; + data: T; + count: number | null; +} +export interface PostgrestResponseFailure extends PostgrestResponseBase { + error: PostgrestError; + data: null; + count: null; +} +export type PostgrestSingleResponse = PostgrestResponseSuccess | PostgrestResponseFailure; +export type PostgrestMaybeSingleResponse = PostgrestSingleResponse; +export type PostgrestResponse = PostgrestSingleResponse; +export type DatabaseWithOptions = { + db: Database; + options: Options; +}; +export type Prettify = { + [K in keyof T]: T[K]; +} & {}; +export type SimplifyDeep = ConditionalSimplifyDeep | Map, object>; +type ConditionalSimplifyDeep = Type extends ExcludeType ? Type : Type extends IncludeType ? { + [TypeKey in keyof Type]: ConditionalSimplifyDeep; +} : Type; +type NonRecursiveType = BuiltIns | Function | (new (...arguments_: any[]) => unknown); +type BuiltIns = Primitive | void | Date | RegExp; +type Primitive = null | undefined | string | number | boolean | symbol | bigint; +export type IsValidResultOverride = Result extends any[] ? NewResult extends any[] ? true : ErrorResult : NewResult extends any[] ? ErrorNewResult : true; +/** + * Utility type to check if array types match between Result and NewResult. + * Returns either the valid NewResult type or an error message type. + */ +export type CheckMatchingArrayTypes = Result extends SelectQueryError ? NewResult : IsValidResultOverride> or .returns> (deprecated) for array results or .single() to convert the result to a single object'; +}, { + Error: 'Type mismatch: Cannot cast single object to array type. Remove Array wrapper from return type or make sure you are not using .single() up in the calling chain'; +}> extends infer ValidationResult ? ValidationResult extends true ? ContainsNull extends true ? NewResult | null : NewResult : ValidationResult : never; +type Simplify = T extends object ? { + [K in keyof T]: T[K]; +} : T; +type ExplicitKeys = { + [K in keyof T]: string extends K ? never : K; +}[keyof T]; +type MergeExplicit = { + [K in ExplicitKeys | ExplicitKeys]: K extends keyof New ? K extends keyof Row ? Row[K] extends SelectQueryError ? New[K] : New[K] extends any[] ? Row[K] extends any[] ? Array, NonNullable>>> : New[K] : IsPlainObject> extends true ? IsPlainObject> extends true ? ContainsNull extends true ? // If the override wants to preserve optionality + Simplify, NonNullable>> | null : Simplify>> : New[K] : New[K] : New[K] : K extends keyof Row ? Row[K] : never; +}; +type MergeDeep = Simplify & (string extends keyof Row ? { + [K: string]: Row[string]; +} : {})>; +type IsPlainObject = T extends any[] ? false : T extends object ? true : false; +export type MergePartialResult = Options extends { + merge: true; +} ? Result extends any[] ? NewResult extends any[] ? Array>> : never : Simplify> : NewResult; +export {}; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/types.d.ts.map b/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/types.d.ts.map new file mode 100644 index 0000000..d280068 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/types/types.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,mBAAmB,CAAA;AAC9C,OAAO,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAA;AAC3D,OAAO,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAA;AAC/D,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAA;AAErD;;;;GAIG;AACH,UAAU,qBAAqB;IAC7B,MAAM,EAAE,MAAM,CAAA;IACd,UAAU,EAAE,MAAM,CAAA;CACnB;AACD,MAAM,WAAW,wBAAwB,CAAC,CAAC,CAAE,SAAQ,qBAAqB;IACxE,KAAK,EAAE,IAAI,CAAA;IACX,IAAI,EAAE,CAAC,CAAA;IACP,KAAK,EAAE,MAA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AAC,GAAG,EAAE,GAAG,IAAI,QAAQ,CACjC,aAAa,CAAC,GAAG,EAAE,GAAG,CAAC,GAKrB,CAAC,MAAM,SAAS,MAAM,GAAG,GAAG;IAAE,CAAC,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC,CAAA;CAAE,GAAG,EAAE,CAAC,CACjE,CAAA;AAGD,KAAK,aAAa,CAAC,CAAC,IAAI,CAAC,SAAS,GAAG,EAAE,GAAG,KAAK,GAAG,CAAC,SAAS,MAAM,GAAG,IAAI,GAAG,KAAK,CAAA;AAIjF,MAAM,MAAM,kBAAkB,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,IAAI,OAAO,SAAS;IAAE,KAAK,EAAE,IAAI,CAAA;CAAE,GACxF,MAAM,SAAS,GAAG,EAAE,GAClB,SAAS,SAAS,GAAG,EAAE,GACrB,KAAK,CAAC,QAAQ,CAAC,SAAS,CAAC,SAAS,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,GAC7D,KAAK,GACP,QAAQ,CAAC,SAAS,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC,GACxC,SAAS,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/types.js b/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/types.js new file mode 100644 index 0000000..11e638d --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/types.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/types.js.map b/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/types.js.map new file mode 100644 index 0000000..ec2c184 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/types/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/types/types.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/version.d.ts b/backend/node_modules/@supabase/postgrest-js/dist/cjs/version.d.ts new file mode 100644 index 0000000..da11aac --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/version.d.ts @@ -0,0 +1,2 @@ +export declare const version = "2.87.1"; +//# sourceMappingURL=version.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/version.d.ts.map b/backend/node_modules/@supabase/postgrest-js/dist/cjs/version.d.ts.map new file mode 100644 index 0000000..0f6a672 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/version.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,OAAO,WAAW,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/version.js b/backend/node_modules/@supabase/postgrest-js/dist/cjs/version.js new file mode 100644 index 0000000..31bcb0a --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/version.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.version = void 0; +// Generated automatically during releases by scripts/update-version-files.ts +// This file provides runtime access to the package version for: +// - HTTP request headers (e.g., X-Client-Info header for API requests) +// - Debugging and support (identifying which version is running) +// - Telemetry and logging (version reporting in errors/analytics) +// - Ensuring build artifacts match the published package version +exports.version = '2.87.1'; +//# sourceMappingURL=version.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/cjs/version.js.map b/backend/node_modules/@supabase/postgrest-js/dist/cjs/version.js.map new file mode 100644 index 0000000..de7f383 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/cjs/version.js.map @@ -0,0 +1 @@ +{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":";;;AAAA,6EAA6E;AAC7E,gEAAgE;AAChE,uEAAuE;AACvE,iEAAiE;AACjE,kEAAkE;AAClE,iEAAiE;AACpD,QAAA,OAAO,GAAG,QAAQ,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/postgrest-js/dist/esm/wrapper.mjs b/backend/node_modules/@supabase/postgrest-js/dist/esm/wrapper.mjs new file mode 100644 index 0000000..4f5b8da --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/dist/esm/wrapper.mjs @@ -0,0 +1,28 @@ +import * as index from '../cjs/index.js' +const { + PostgrestClient, + PostgrestQueryBuilder, + PostgrestFilterBuilder, + PostgrestTransformBuilder, + PostgrestBuilder, + PostgrestError, +} = index.default || index + +export { + PostgrestBuilder, + PostgrestClient, + PostgrestFilterBuilder, + PostgrestQueryBuilder, + PostgrestTransformBuilder, + PostgrestError, +} + +// compatibility with CJS output +export default { + PostgrestClient, + PostgrestQueryBuilder, + PostgrestFilterBuilder, + PostgrestTransformBuilder, + PostgrestBuilder, + PostgrestError, +} diff --git a/backend/node_modules/@supabase/postgrest-js/package.json b/backend/node_modules/@supabase/postgrest-js/package.json new file mode 100644 index 0000000..ea40aaa --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/package.json @@ -0,0 +1,72 @@ +{ + "name": "@supabase/postgrest-js", + "version": "2.87.1", + "description": "Isomorphic PostgREST client", + "keywords": [ + "postgrest", + "supabase" + ], + "homepage": "https://github.com/supabase/supabase-js/tree/master/packages/core/postgrest-js", + "bugs": "https://github.com/supabase/supabase-js/issues", + "license": "MIT", + "author": "Supabase", + "files": [ + "dist", + "src" + ], + "main": "dist/cjs/index.js", + "module": "dist/esm/wrapper.mjs", + "exports": { + "import": { + "types": "./dist/cjs/index.d.ts", + "default": "./dist/esm/wrapper.mjs" + }, + "require": { + "types": "./dist/cjs/index.d.ts", + "default": "./dist/cjs/index.js" + } + }, + "types": "./dist/cjs/index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/supabase/supabase-js.git", + "directory": "packages/core/postgrest-js" + }, + "scripts": { + "build": "npm run build:cjs && npm run build:esm", + "format": "node scripts/format.js", + "format:check": "node scripts/format.js check", + "build:cjs": "tsc -p tsconfig.json", + "build:esm": "node scripts/copy-wrapper.cjs", + "build:module": "npm run build:cjs", + "docs": "typedoc src/index.ts --out docs/v2", + "docs:json": "typedoc --json docs/v2/spec.json --excludeExternals src/index.ts", + "test:ci:postgrest": "npm run db:clean && npm run db:run && npm run test:run && npm run db:clean && npm run test:smoke", + "test:run": "jest --runInBand --coverage -u", + "test:smoke": "node test/smoke.cjs && node test/smoke.mjs", + "test:update": "npm run db:clean && npm run db:run && npm run db:generate-test-types && jest --runInBand --updateSnapshot && npm run db:clean", + "test:types": "npm run build && tstyche", + "test:types:ci": "tstyche --target '4.7,5.5,latest'", + "test:types:watch": "chokidar 'src/**/*.ts' 'test/**/*.ts' -c 'npm run test:types'", + "type-check": "tsc --noEmit --project tsconfig.json", + "type-check:test": "tsc --noEmit --project tsconfig.test.json", + "db:clean": "cd test/db && docker compose down --volumes", + "db:run": "cd test/db && docker compose up --detach && wait-for-localhost 3000", + "db:generate-test-types": "cd test/db && docker compose up --detach && wait-for-localhost 8080 && wait-for-localhost 3000 && curl --location 'http://0.0.0.0:8080/generators/typescript?included_schemas=public,personal&detect_one_to_one_relationships=true' > ../types.generated.ts && node ../scripts/update-json-type.js && cd ../../ && npm run format" + }, + "dependencies": { + "tslib": "2.8.1" + }, + "devDependencies": { + "chokidar-cli": "^3.0.0", + "node-abort-controller": "^3.0.1", + "tstyche": "^4.3.0", + "type-fest": "^4.32.0", + "wait-for-localhost-cli": "^4.0.0", + "zod": "^3.25.76", + "prettier": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } +} diff --git a/backend/node_modules/@supabase/postgrest-js/src/PostgrestBuilder.ts b/backend/node_modules/@supabase/postgrest-js/src/PostgrestBuilder.ts new file mode 100644 index 0000000..3547fd4 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/src/PostgrestBuilder.ts @@ -0,0 +1,333 @@ +import type { + PostgrestSingleResponse, + PostgrestResponseSuccess, + CheckMatchingArrayTypes, + MergePartialResult, + IsValidResultOverride, +} from './types/types' +import { ClientServerOptions, Fetch } from './types/common/common' +import PostgrestError from './PostgrestError' +import { ContainsNull } from './select-query-parser/types' + +export default abstract class PostgrestBuilder< + ClientOptions extends ClientServerOptions, + Result, + ThrowOnError extends boolean = false, +> implements + PromiseLike< + ThrowOnError extends true ? PostgrestResponseSuccess : PostgrestSingleResponse + > +{ + protected method: 'GET' | 'HEAD' | 'POST' | 'PATCH' | 'DELETE' + protected url: URL + protected headers: Headers + protected schema?: string + protected body?: unknown + protected shouldThrowOnError = false + protected signal?: AbortSignal + protected fetch: Fetch + protected isMaybeSingle: boolean + + /** + * Creates a builder configured for a specific PostgREST request. + * + * @example + * ```ts + * import PostgrestQueryBuilder from '@supabase/postgrest-js' + * + * const builder = new PostgrestQueryBuilder( + * new URL('https://xyzcompany.supabase.co/rest/v1/users'), + * { headers: new Headers({ apikey: 'public-anon-key' }) } + * ) + * ``` + */ + constructor(builder: { + method: 'GET' | 'HEAD' | 'POST' | 'PATCH' | 'DELETE' + url: URL + headers: HeadersInit + schema?: string + body?: unknown + shouldThrowOnError?: boolean + signal?: AbortSignal + fetch?: Fetch + isMaybeSingle?: boolean + }) { + this.method = builder.method + this.url = builder.url + this.headers = new Headers(builder.headers) + this.schema = builder.schema + this.body = builder.body + this.shouldThrowOnError = builder.shouldThrowOnError ?? false + this.signal = builder.signal + this.isMaybeSingle = builder.isMaybeSingle ?? false + + if (builder.fetch) { + this.fetch = builder.fetch + } else { + this.fetch = fetch + } + } + + /** + * If there's an error with the query, throwOnError will reject the promise by + * throwing the error instead of returning it as part of a successful response. + * + * {@link https://github.com/supabase/supabase-js/issues/92} + */ + throwOnError(): this & PostgrestBuilder { + this.shouldThrowOnError = true + return this as this & PostgrestBuilder + } + + /** + * Set an HTTP header for the request. + */ + setHeader(name: string, value: string): this { + this.headers = new Headers(this.headers) + this.headers.set(name, value) + return this + } + + then< + TResult1 = ThrowOnError extends true + ? PostgrestResponseSuccess + : PostgrestSingleResponse, + TResult2 = never, + >( + onfulfilled?: + | (( + value: ThrowOnError extends true + ? PostgrestResponseSuccess + : PostgrestSingleResponse + ) => TResult1 | PromiseLike) + | undefined + | null, + onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null + ): PromiseLike { + // https://postgrest.org/en/stable/api.html#switching-schemas + if (this.schema === undefined) { + // skip + } else if (['GET', 'HEAD'].includes(this.method)) { + this.headers.set('Accept-Profile', this.schema) + } else { + this.headers.set('Content-Profile', this.schema) + } + if (this.method !== 'GET' && this.method !== 'HEAD') { + this.headers.set('Content-Type', 'application/json') + } + + // NOTE: Invoke w/o `this` to avoid illegal invocation error. + // https://github.com/supabase/postgrest-js/pull/247 + const _fetch = this.fetch + let res = _fetch(this.url.toString(), { + method: this.method, + headers: this.headers, + body: JSON.stringify(this.body), + signal: this.signal, + }).then(async (res) => { + let error = null + let data = null + let count: number | null = null + let status = res.status + let statusText = res.statusText + + if (res.ok) { + if (this.method !== 'HEAD') { + const body = await res.text() + if (body === '') { + // Prefer: return=minimal + } else if (this.headers.get('Accept') === 'text/csv') { + data = body + } else if ( + this.headers.get('Accept') && + this.headers.get('Accept')?.includes('application/vnd.pgrst.plan+text') + ) { + data = body + } else { + data = JSON.parse(body) + } + } + + const countHeader = this.headers.get('Prefer')?.match(/count=(exact|planned|estimated)/) + const contentRange = res.headers.get('content-range')?.split('/') + if (countHeader && contentRange && contentRange.length > 1) { + count = parseInt(contentRange[1]) + } + + // Temporary partial fix for https://github.com/supabase/postgrest-js/issues/361 + // Issue persists e.g. for `.insert([...]).select().maybeSingle()` + if (this.isMaybeSingle && this.method === 'GET' && Array.isArray(data)) { + if (data.length > 1) { + error = { + // https://github.com/PostgREST/postgrest/blob/a867d79c42419af16c18c3fb019eba8df992626f/src/PostgREST/Error.hs#L553 + code: 'PGRST116', + details: `Results contain ${data.length} rows, application/vnd.pgrst.object+json requires 1 row`, + hint: null, + message: 'JSON object requested, multiple (or no) rows returned', + } + data = null + count = null + status = 406 + statusText = 'Not Acceptable' + } else if (data.length === 1) { + data = data[0] + } else { + data = null + } + } + } else { + const body = await res.text() + + try { + error = JSON.parse(body) + + // Workaround for https://github.com/supabase/postgrest-js/issues/295 + if (Array.isArray(error) && res.status === 404) { + data = [] + error = null + status = 200 + statusText = 'OK' + } + } catch { + // Workaround for https://github.com/supabase/postgrest-js/issues/295 + if (res.status === 404 && body === '') { + status = 204 + statusText = 'No Content' + } else { + error = { + message: body, + } + } + } + + if (error && this.isMaybeSingle && error?.details?.includes('0 rows')) { + error = null + status = 200 + statusText = 'OK' + } + + if (error && this.shouldThrowOnError) { + throw new PostgrestError(error) + } + } + + const postgrestResponse = { + error, + data, + count, + status, + statusText, + } + + return postgrestResponse + }) + if (!this.shouldThrowOnError) { + res = res.catch((fetchError) => { + // Build detailed error information including cause if available + // Note: We don't populate code/hint for client-side network errors since those + // fields are meant for upstream service errors (PostgREST/PostgreSQL) + let errorDetails = '' + + // Add cause information if available (e.g., DNS errors, network failures) + const cause = fetchError?.cause + if (cause) { + const causeMessage = cause?.message ?? '' + const causeCode = cause?.code ?? '' + + errorDetails = `${fetchError?.name ?? 'FetchError'}: ${fetchError?.message}` + errorDetails += `\n\nCaused by: ${cause?.name ?? 'Error'}: ${causeMessage}` + if (causeCode) { + errorDetails += ` (${causeCode})` + } + if (cause?.stack) { + errorDetails += `\n${cause.stack}` + } + } else { + // No cause available, just include the error stack + errorDetails = fetchError?.stack ?? '' + } + + return { + error: { + message: `${fetchError?.name ?? 'FetchError'}: ${fetchError?.message}`, + details: errorDetails, + hint: '', + code: '', + }, + data: null, + count: null, + status: 0, + statusText: '', + } + }) + } + + return res.then(onfulfilled, onrejected) + } + + /** + * Override the type of the returned `data`. + * + * @typeParam NewResult - The new result type to override with + * @deprecated Use overrideTypes() method at the end of your call chain instead + */ + returns(): PostgrestBuilder< + ClientOptions, + CheckMatchingArrayTypes, + ThrowOnError + > { + /* istanbul ignore next */ + return this as unknown as PostgrestBuilder< + ClientOptions, + CheckMatchingArrayTypes, + ThrowOnError + > + } + + /** + * Override the type of the returned `data` field in the response. + * + * @typeParam NewResult - The new type to cast the response data to + * @typeParam Options - Optional type configuration (defaults to { merge: true }) + * @typeParam Options.merge - When true, merges the new type with existing return type. When false, replaces the existing types entirely (defaults to true) + * @example + * ```typescript + * // Merge with existing types (default behavior) + * const query = supabase + * .from('users') + * .select() + * .overrideTypes<{ custom_field: string }>() + * + * // Replace existing types completely + * const replaceQuery = supabase + * .from('users') + * .select() + * .overrideTypes<{ id: number; name: string }, { merge: false }>() + * ``` + * @returns A PostgrestBuilder instance with the new type + */ + overrideTypes< + NewResult, + Options extends { merge?: boolean } = { merge: true }, + >(): PostgrestBuilder< + ClientOptions, + IsValidResultOverride extends true + ? // Preserve the optionality of the result if the overriden type is an object (case of chaining with `maybeSingle`) + ContainsNull extends true + ? MergePartialResult, Options> | null + : MergePartialResult + : CheckMatchingArrayTypes, + ThrowOnError + > { + return this as unknown as PostgrestBuilder< + ClientOptions, + IsValidResultOverride extends true + ? // Preserve the optionality of the result if the overriden type is an object (case of chaining with `maybeSingle`) + ContainsNull extends true + ? MergePartialResult, Options> | null + : MergePartialResult + : CheckMatchingArrayTypes, + ThrowOnError + > + } +} diff --git a/backend/node_modules/@supabase/postgrest-js/src/PostgrestClient.ts b/backend/node_modules/@supabase/postgrest-js/src/PostgrestClient.ts new file mode 100644 index 0000000..dbc11bc --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/src/PostgrestClient.ts @@ -0,0 +1,219 @@ +import PostgrestQueryBuilder from './PostgrestQueryBuilder' +import PostgrestFilterBuilder from './PostgrestFilterBuilder' +import { Fetch, GenericSchema, ClientServerOptions } from './types/common/common' +import { GetRpcFunctionFilterBuilderByArgs } from './types/common/rpc' + +/** + * PostgREST client. + * + * @typeParam Database - Types for the schema from the [type + * generator](https://supabase.com/docs/reference/javascript/next/typescript-support) + * + * @typeParam SchemaName - Postgres schema to switch to. Must be a string + * literal, the same one passed to the constructor. If the schema is not + * `"public"`, this must be supplied manually. + */ +export default class PostgrestClient< + Database = any, + ClientOptions extends ClientServerOptions = Database extends { + __InternalSupabase: infer I extends ClientServerOptions + } + ? I + : {}, + SchemaName extends string & + keyof Omit = 'public' extends keyof Omit< + Database, + '__InternalSupabase' + > + ? 'public' + : string & keyof Omit, + Schema extends GenericSchema = Omit< + Database, + '__InternalSupabase' + >[SchemaName] extends GenericSchema + ? Omit[SchemaName] + : any, +> { + url: string + headers: Headers + schemaName?: SchemaName + fetch?: Fetch + + // TODO: Add back shouldThrowOnError once we figure out the typings + /** + * Creates a PostgREST client. + * + * @param url - URL of the PostgREST endpoint + * @param options - Named parameters + * @param options.headers - Custom headers + * @param options.schema - Postgres schema to switch to + * @param options.fetch - Custom fetch + * @example + * ```ts + * import PostgrestClient from '@supabase/postgrest-js' + * + * const postgrest = new PostgrestClient('https://xyzcompany.supabase.co/rest/v1', { + * headers: { apikey: 'public-anon-key' }, + * schema: 'public', + * }) + * ``` + */ + constructor( + url: string, + { + headers = {}, + schema, + fetch, + }: { + headers?: HeadersInit + schema?: SchemaName + fetch?: Fetch + } = {} + ) { + this.url = url + this.headers = new Headers(headers) + this.schemaName = schema + this.fetch = fetch + } + from< + TableName extends string & keyof Schema['Tables'], + Table extends Schema['Tables'][TableName], + >(relation: TableName): PostgrestQueryBuilder + from( + relation: ViewName + ): PostgrestQueryBuilder + /** + * Perform a query on a table or a view. + * + * @param relation - The table or view name to query + */ + from(relation: string): PostgrestQueryBuilder { + if (!relation || typeof relation !== 'string' || relation.trim() === '') { + throw new Error('Invalid relation name: relation must be a non-empty string.') + } + + const url = new URL(`${this.url}/${relation}`) + return new PostgrestQueryBuilder(url, { + headers: new Headers(this.headers), + schema: this.schemaName, + fetch: this.fetch, + }) + } + + /** + * Select a schema to query or perform an function (rpc) call. + * + * The schema needs to be on the list of exposed schemas inside Supabase. + * + * @param schema - The schema to query + */ + schema>( + schema: DynamicSchema + ): PostgrestClient< + Database, + ClientOptions, + DynamicSchema, + Database[DynamicSchema] extends GenericSchema ? Database[DynamicSchema] : any + > { + return new PostgrestClient(this.url, { + headers: this.headers, + schema, + fetch: this.fetch, + }) + } + + /** + * Perform a function call. + * + * @param fn - The function name to call + * @param args - The arguments to pass to the function call + * @param options - Named parameters + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * @param options.get - When set to `true`, the function will be called with + * read-only access mode. + * @param options.count - Count algorithm to use to count rows returned by the + * function. Only applicable for [set-returning + * functions](https://www.postgresql.org/docs/current/functions-srf.html). + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + * + * @example + * ```ts + * // For cross-schema functions where type inference fails, use overrideTypes: + * const { data } = await supabase + * .schema('schema_b') + * .rpc('function_a', {}) + * .overrideTypes<{ id: string; user_id: string }[]>() + * ``` + */ + rpc< + FnName extends string & keyof Schema['Functions'], + Args extends Schema['Functions'][FnName]['Args'] = never, + FilterBuilder extends GetRpcFunctionFilterBuilderByArgs< + Schema, + FnName, + Args + > = GetRpcFunctionFilterBuilderByArgs, + >( + fn: FnName, + args: Args = {} as Args, + { + head = false, + get = false, + count, + }: { + head?: boolean + get?: boolean + count?: 'exact' | 'planned' | 'estimated' + } = {} + ): PostgrestFilterBuilder< + ClientOptions, + Schema, + FilterBuilder['Row'], + FilterBuilder['Result'], + FilterBuilder['RelationName'], + FilterBuilder['Relationships'], + 'RPC' + > { + let method: 'HEAD' | 'GET' | 'POST' + const url = new URL(`${this.url}/rpc/${fn}`) + let body: unknown | undefined + if (head || get) { + method = head ? 'HEAD' : 'GET' + Object.entries(args) + // params with undefined value needs to be filtered out, otherwise it'll + // show up as `?param=undefined` + .filter(([_, value]) => value !== undefined) + // array values need special syntax + .map(([name, value]) => [name, Array.isArray(value) ? `{${value.join(',')}}` : `${value}`]) + .forEach(([name, value]) => { + url.searchParams.append(name, value) + }) + } else { + method = 'POST' + body = args + } + + const headers = new Headers(this.headers) + if (count) { + headers.set('Prefer', `count=${count}`) + } + + return new PostgrestFilterBuilder({ + method, + url, + headers, + schema: this.schemaName, + body, + fetch: this.fetch ?? fetch, + }) + } +} diff --git a/backend/node_modules/@supabase/postgrest-js/src/PostgrestError.ts b/backend/node_modules/@supabase/postgrest-js/src/PostgrestError.ts new file mode 100644 index 0000000..151f994 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/src/PostgrestError.ts @@ -0,0 +1,31 @@ +/** + * Error format + * + * {@link https://postgrest.org/en/stable/api.html?highlight=options#errors-and-http-status-codes} + */ +export default class PostgrestError extends Error { + details: string + hint: string + code: string + + /** + * @example + * ```ts + * import PostgrestError from '@supabase/postgrest-js' + * + * throw new PostgrestError({ + * message: 'Row level security prevented the request', + * details: 'RLS denied the insert', + * hint: 'Check your policies', + * code: 'PGRST301', + * }) + * ``` + */ + constructor(context: { message: string; details: string; hint: string; code: string }) { + super(context.message) + this.name = 'PostgrestError' + this.details = context.details + this.hint = context.hint + this.code = context.code + } +} diff --git a/backend/node_modules/@supabase/postgrest-js/src/PostgrestFilterBuilder.ts b/backend/node_modules/@supabase/postgrest-js/src/PostgrestFilterBuilder.ts new file mode 100644 index 0000000..60e6ef1 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/src/PostgrestFilterBuilder.ts @@ -0,0 +1,659 @@ +import PostgrestTransformBuilder from './PostgrestTransformBuilder' +import { JsonPathToAccessor, JsonPathToType } from './select-query-parser/utils' +import { ClientServerOptions, GenericSchema } from './types/common/common' + +type FilterOperator = + | 'eq' + | 'neq' + | 'gt' + | 'gte' + | 'lt' + | 'lte' + | 'like' + | 'ilike' + | 'is' + | 'isdistinct' + | 'in' + | 'cs' + | 'cd' + | 'sl' + | 'sr' + | 'nxl' + | 'nxr' + | 'adj' + | 'ov' + | 'fts' + | 'plfts' + | 'phfts' + | 'wfts' + | 'match' + | 'imatch' + +export type IsStringOperator = Path extends `${string}->>${string}` + ? true + : false + +const PostgrestReservedCharsRegexp = new RegExp('[,()]') + +// Match relationship filters with `table.column` syntax and resolve underlying +// column value. If not matched, fallback to generic type. +// TODO: Validate the relationship itself ala select-query-parser. Currently we +// assume that all tables have valid relationships to each other, despite +// nonexistent foreign keys. +type ResolveFilterValue< + Schema extends GenericSchema, + Row extends Record, + ColumnName extends string, +> = ColumnName extends `${infer RelationshipTable}.${infer Remainder}` + ? Remainder extends `${infer _}.${infer _}` + ? ResolveFilterValue + : ResolveFilterRelationshipValue + : ColumnName extends keyof Row + ? Row[ColumnName] + : // If the column selection is a jsonpath like `data->value` or `data->>value` we attempt to match + // the expected type with the parsed custom json type + IsStringOperator extends true + ? string + : JsonPathToType> extends infer JsonPathValue + ? JsonPathValue extends never + ? never + : JsonPathValue + : never + +type ResolveFilterRelationshipValue< + Schema extends GenericSchema, + RelationshipTable extends string, + RelationshipColumn extends string, +> = Schema['Tables'] & Schema['Views'] extends infer TablesAndViews + ? RelationshipTable extends keyof TablesAndViews + ? 'Row' extends keyof TablesAndViews[RelationshipTable] + ? RelationshipColumn extends keyof TablesAndViews[RelationshipTable]['Row'] + ? TablesAndViews[RelationshipTable]['Row'][RelationshipColumn] + : unknown + : unknown + : unknown + : never + +export type InvalidMethodError = { Error: S } + +export default class PostgrestFilterBuilder< + ClientOptions extends ClientServerOptions, + Schema extends GenericSchema, + Row extends Record, + Result, + RelationName = unknown, + Relationships = unknown, + Method = unknown, +> extends PostgrestTransformBuilder< + ClientOptions, + Schema, + Row, + Result, + RelationName, + Relationships, + Method +> { + /** + * Match only rows where `column` is equal to `value`. + * + * To check if the value of `column` is NULL, you should use `.is()` instead. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + eq( + column: ColumnName, + value: ResolveFilterValue extends never + ? NonNullable + : // We want to infer the type before wrapping it into a `NonNullable` to avoid too deep + // type resolution error + ResolveFilterValue extends infer ResolvedFilterValue + ? NonNullable + : // We should never enter this case as all the branches are covered above + never + ): this { + this.url.searchParams.append(column, `eq.${value}`) + return this + } + + /** + * Match only rows where `column` is not equal to `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + neq( + column: ColumnName, + value: ResolveFilterValue extends never + ? unknown + : ResolveFilterValue extends infer ResolvedFilterValue + ? ResolvedFilterValue + : never + ): this { + this.url.searchParams.append(column, `neq.${value}`) + return this + } + + gt(column: ColumnName, value: Row[ColumnName]): this + gt(column: string, value: unknown): this + /** + * Match only rows where `column` is greater than `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + gt(column: string, value: unknown): this { + this.url.searchParams.append(column, `gt.${value}`) + return this + } + + gte(column: ColumnName, value: Row[ColumnName]): this + gte(column: string, value: unknown): this + /** + * Match only rows where `column` is greater than or equal to `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + gte(column: string, value: unknown): this { + this.url.searchParams.append(column, `gte.${value}`) + return this + } + + lt(column: ColumnName, value: Row[ColumnName]): this + lt(column: string, value: unknown): this + /** + * Match only rows where `column` is less than `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + lt(column: string, value: unknown): this { + this.url.searchParams.append(column, `lt.${value}`) + return this + } + + lte(column: ColumnName, value: Row[ColumnName]): this + lte(column: string, value: unknown): this + /** + * Match only rows where `column` is less than or equal to `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + lte(column: string, value: unknown): this { + this.url.searchParams.append(column, `lte.${value}`) + return this + } + + like(column: ColumnName, pattern: string): this + like(column: string, pattern: string): this + /** + * Match only rows where `column` matches `pattern` case-sensitively. + * + * @param column - The column to filter on + * @param pattern - The pattern to match with + */ + like(column: string, pattern: string): this { + this.url.searchParams.append(column, `like.${pattern}`) + return this + } + + likeAllOf( + column: ColumnName, + patterns: readonly string[] + ): this + likeAllOf(column: string, patterns: readonly string[]): this + /** + * Match only rows where `column` matches all of `patterns` case-sensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + likeAllOf(column: string, patterns: readonly string[]): this { + this.url.searchParams.append(column, `like(all).{${patterns.join(',')}}`) + return this + } + + likeAnyOf( + column: ColumnName, + patterns: readonly string[] + ): this + likeAnyOf(column: string, patterns: readonly string[]): this + /** + * Match only rows where `column` matches any of `patterns` case-sensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + likeAnyOf(column: string, patterns: readonly string[]): this { + this.url.searchParams.append(column, `like(any).{${patterns.join(',')}}`) + return this + } + + ilike(column: ColumnName, pattern: string): this + ilike(column: string, pattern: string): this + /** + * Match only rows where `column` matches `pattern` case-insensitively. + * + * @param column - The column to filter on + * @param pattern - The pattern to match with + */ + ilike(column: string, pattern: string): this { + this.url.searchParams.append(column, `ilike.${pattern}`) + return this + } + + ilikeAllOf( + column: ColumnName, + patterns: readonly string[] + ): this + ilikeAllOf(column: string, patterns: readonly string[]): this + /** + * Match only rows where `column` matches all of `patterns` case-insensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + ilikeAllOf(column: string, patterns: readonly string[]): this { + this.url.searchParams.append(column, `ilike(all).{${patterns.join(',')}}`) + return this + } + + ilikeAnyOf( + column: ColumnName, + patterns: readonly string[] + ): this + ilikeAnyOf(column: string, patterns: readonly string[]): this + /** + * Match only rows where `column` matches any of `patterns` case-insensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + ilikeAnyOf(column: string, patterns: readonly string[]): this { + this.url.searchParams.append(column, `ilike(any).{${patterns.join(',')}}`) + return this + } + + regexMatch(column: ColumnName, pattern: string): this + regexMatch(column: string, pattern: string): this + /** + * Match only rows where `column` matches the PostgreSQL regex `pattern` + * case-sensitively (using the `~` operator). + * + * @param column - The column to filter on + * @param pattern - The PostgreSQL regular expression pattern to match with + */ + regexMatch(column: string, pattern: string): this { + this.url.searchParams.append(column, `match.${pattern}`) + return this + } + + regexIMatch(column: ColumnName, pattern: string): this + regexIMatch(column: string, pattern: string): this + /** + * Match only rows where `column` matches the PostgreSQL regex `pattern` + * case-insensitively (using the `~*` operator). + * + * @param column - The column to filter on + * @param pattern - The PostgreSQL regular expression pattern to match with + */ + regexIMatch(column: string, pattern: string): this { + this.url.searchParams.append(column, `imatch.${pattern}`) + return this + } + + is( + column: ColumnName, + value: Row[ColumnName] & (boolean | null) + ): this + is(column: string, value: boolean | null): this + /** + * Match only rows where `column` IS `value`. + * + * For non-boolean columns, this is only relevant for checking if the value of + * `column` is NULL by setting `value` to `null`. + * + * For boolean columns, you can also set `value` to `true` or `false` and it + * will behave the same way as `.eq()`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + is(column: string, value: boolean | null): this { + this.url.searchParams.append(column, `is.${value}`) + return this + } + + /** + * Match only rows where `column` IS DISTINCT FROM `value`. + * + * Unlike `.neq()`, this treats `NULL` as a comparable value. Two `NULL` values + * are considered equal (not distinct), and comparing `NULL` with any non-NULL + * value returns true (distinct). + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + isDistinct( + column: ColumnName, + value: ResolveFilterValue extends never + ? unknown + : ResolveFilterValue extends infer ResolvedFilterValue + ? ResolvedFilterValue + : never + ): this { + this.url.searchParams.append(column, `isdistinct.${value}`) + return this + } + + /** + * Match only rows where `column` is included in the `values` array. + * + * @param column - The column to filter on + * @param values - The values array to filter with + */ + in( + column: ColumnName, + values: ReadonlyArray< + ResolveFilterValue extends never + ? unknown + : // We want to infer the type before wrapping it into a `NonNullable` to avoid too deep + // type resolution error + ResolveFilterValue extends infer ResolvedFilterValue + ? ResolvedFilterValue + : // We should never enter this case as all the branches are covered above + never + > + ): this { + const cleanedValues = Array.from(new Set(values)) + .map((s) => { + // handle postgrest reserved characters + // https://postgrest.org/en/v7.0.0/api.html#reserved-characters + if (typeof s === 'string' && PostgrestReservedCharsRegexp.test(s)) return `"${s}"` + else return `${s}` + }) + .join(',') + this.url.searchParams.append(column, `in.(${cleanedValues})`) + return this + } + + contains( + column: ColumnName, + value: string | ReadonlyArray | Record + ): this + contains(column: string, value: string | readonly unknown[] | Record): this + /** + * Only relevant for jsonb, array, and range columns. Match only rows where + * `column` contains every element appearing in `value`. + * + * @param column - The jsonb, array, or range column to filter on + * @param value - The jsonb, array, or range value to filter with + */ + contains(column: string, value: string | readonly unknown[] | Record): this { + if (typeof value === 'string') { + // range types can be inclusive '[', ']' or exclusive '(', ')' so just + // keep it simple and accept a string + this.url.searchParams.append(column, `cs.${value}`) + } else if (Array.isArray(value)) { + // array + this.url.searchParams.append(column, `cs.{${value.join(',')}}`) + } else { + // json + this.url.searchParams.append(column, `cs.${JSON.stringify(value)}`) + } + return this + } + + containedBy( + column: ColumnName, + value: string | ReadonlyArray | Record + ): this + containedBy(column: string, value: string | readonly unknown[] | Record): this + /** + * Only relevant for jsonb, array, and range columns. Match only rows where + * every element appearing in `column` is contained by `value`. + * + * @param column - The jsonb, array, or range column to filter on + * @param value - The jsonb, array, or range value to filter with + */ + containedBy(column: string, value: string | readonly unknown[] | Record): this { + if (typeof value === 'string') { + // range + this.url.searchParams.append(column, `cd.${value}`) + } else if (Array.isArray(value)) { + // array + this.url.searchParams.append(column, `cd.{${value.join(',')}}`) + } else { + // json + this.url.searchParams.append(column, `cd.${JSON.stringify(value)}`) + } + return this + } + + rangeGt(column: ColumnName, range: string): this + rangeGt(column: string, range: string): this + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is greater than any element in `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeGt(column: string, range: string): this { + this.url.searchParams.append(column, `sr.${range}`) + return this + } + + rangeGte(column: ColumnName, range: string): this + rangeGte(column: string, range: string): this + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is either contained in `range` or greater than any element in + * `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeGte(column: string, range: string): this { + this.url.searchParams.append(column, `nxl.${range}`) + return this + } + + rangeLt(column: ColumnName, range: string): this + rangeLt(column: string, range: string): this + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is less than any element in `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeLt(column: string, range: string): this { + this.url.searchParams.append(column, `sl.${range}`) + return this + } + + rangeLte(column: ColumnName, range: string): this + rangeLte(column: string, range: string): this + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is either contained in `range` or less than any element in + * `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeLte(column: string, range: string): this { + this.url.searchParams.append(column, `nxr.${range}`) + return this + } + + rangeAdjacent(column: ColumnName, range: string): this + rangeAdjacent(column: string, range: string): this + /** + * Only relevant for range columns. Match only rows where `column` is + * mutually exclusive to `range` and there can be no element between the two + * ranges. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeAdjacent(column: string, range: string): this { + this.url.searchParams.append(column, `adj.${range}`) + return this + } + + overlaps( + column: ColumnName, + value: string | ReadonlyArray + ): this + overlaps(column: string, value: string | readonly unknown[]): this + /** + * Only relevant for array and range columns. Match only rows where + * `column` and `value` have an element in common. + * + * @param column - The array or range column to filter on + * @param value - The array or range value to filter with + */ + overlaps(column: string, value: string | readonly unknown[]): this { + if (typeof value === 'string') { + // range + this.url.searchParams.append(column, `ov.${value}`) + } else { + // array + this.url.searchParams.append(column, `ov.{${value.join(',')}}`) + } + return this + } + + textSearch( + column: ColumnName, + query: string, + options?: { config?: string; type?: 'plain' | 'phrase' | 'websearch' } + ): this + textSearch( + column: string, + query: string, + options?: { config?: string; type?: 'plain' | 'phrase' | 'websearch' } + ): this + /** + * Only relevant for text and tsvector columns. Match only rows where + * `column` matches the query string in `query`. + * + * @param column - The text or tsvector column to filter on + * @param query - The query text to match with + * @param options - Named parameters + * @param options.config - The text search configuration to use + * @param options.type - Change how the `query` text is interpreted + */ + textSearch( + column: string, + query: string, + { config, type }: { config?: string; type?: 'plain' | 'phrase' | 'websearch' } = {} + ): this { + let typePart = '' + if (type === 'plain') { + typePart = 'pl' + } else if (type === 'phrase') { + typePart = 'ph' + } else if (type === 'websearch') { + typePart = 'w' + } + const configPart = config === undefined ? '' : `(${config})` + this.url.searchParams.append(column, `${typePart}fts${configPart}.${query}`) + return this + } + + match(query: Record): this + match(query: Record): this + /** + * Match only rows where each column in `query` keys is equal to its + * associated value. Shorthand for multiple `.eq()`s. + * + * @param query - The object to filter with, with column names as keys mapped + * to their filter values + */ + match(query: Record): this { + Object.entries(query).forEach(([column, value]) => { + this.url.searchParams.append(column, `eq.${value}`) + }) + return this + } + + not( + column: ColumnName, + operator: FilterOperator, + value: Row[ColumnName] + ): this + not(column: string, operator: string, value: unknown): this + /** + * Match only rows which doesn't satisfy the filter. + * + * Unlike most filters, `opearator` and `value` are used as-is and need to + * follow [PostgREST + * syntax](https://postgrest.org/en/stable/api.html#operators). You also need + * to make sure they are properly sanitized. + * + * @param column - The column to filter on + * @param operator - The operator to be negated to filter with, following + * PostgREST syntax + * @param value - The value to filter with, following PostgREST syntax + */ + not(column: string, operator: string, value: unknown): this { + this.url.searchParams.append(column, `not.${operator}.${value}`) + return this + } + + /** + * Match only rows which satisfy at least one of the filters. + * + * Unlike most filters, `filters` is used as-is and needs to follow [PostgREST + * syntax](https://postgrest.org/en/stable/api.html#operators). You also need + * to make sure it's properly sanitized. + * + * It's currently not possible to do an `.or()` filter across multiple tables. + * + * @param filters - The filters to use, following PostgREST syntax + * @param options - Named parameters + * @param options.referencedTable - Set this to filter on referenced tables + * instead of the parent table + * @param options.foreignTable - Deprecated, use `referencedTable` instead + */ + or( + filters: string, + { + foreignTable, + referencedTable = foreignTable, + }: { foreignTable?: string; referencedTable?: string } = {} + ): this { + const key = referencedTable ? `${referencedTable}.or` : 'or' + this.url.searchParams.append(key, `(${filters})`) + return this + } + + filter( + column: ColumnName, + operator: `${'' | 'not.'}${FilterOperator}`, + value: unknown + ): this + filter(column: string, operator: string, value: unknown): this + /** + * Match only rows which satisfy the filter. This is an escape hatch - you + * should use the specific filter methods wherever possible. + * + * Unlike most filters, `opearator` and `value` are used as-is and need to + * follow [PostgREST + * syntax](https://postgrest.org/en/stable/api.html#operators). You also need + * to make sure they are properly sanitized. + * + * @param column - The column to filter on + * @param operator - The operator to filter with, following PostgREST syntax + * @param value - The value to filter with, following PostgREST syntax + */ + filter(column: string, operator: string, value: unknown): this { + this.url.searchParams.append(column, `${operator}.${value}`) + return this + } +} diff --git a/backend/node_modules/@supabase/postgrest-js/src/PostgrestQueryBuilder.ts b/backend/node_modules/@supabase/postgrest-js/src/PostgrestQueryBuilder.ts new file mode 100644 index 0000000..25bb604 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/src/PostgrestQueryBuilder.ts @@ -0,0 +1,504 @@ +import PostgrestFilterBuilder from './PostgrestFilterBuilder' +import { GetResult } from './select-query-parser/result' +import { + ClientServerOptions, + Fetch, + GenericSchema, + GenericTable, + GenericView, +} from './types/common/common' + +export default class PostgrestQueryBuilder< + ClientOptions extends ClientServerOptions, + Schema extends GenericSchema, + Relation extends GenericTable | GenericView, + RelationName = unknown, + Relationships = Relation extends { Relationships: infer R } ? R : unknown, +> { + url: URL + headers: Headers + schema?: string + signal?: AbortSignal + fetch?: Fetch + + /** + * Creates a query builder scoped to a Postgres table or view. + * + * @example + * ```ts + * import PostgrestQueryBuilder from '@supabase/postgrest-js' + * + * const query = new PostgrestQueryBuilder( + * new URL('https://xyzcompany.supabase.co/rest/v1/users'), + * { headers: { apikey: 'public-anon-key' } } + * ) + * ``` + */ + constructor( + url: URL, + { + headers = {}, + schema, + fetch, + }: { + headers?: HeadersInit + schema?: string + fetch?: Fetch + } + ) { + this.url = url + this.headers = new Headers(headers) + this.schema = schema + this.fetch = fetch + } + + /** + * Perform a SELECT query on the table or view. + * + * @param columns - The columns to retrieve, separated by commas. Columns can be renamed when returned with `customName:columnName` + * + * @param options - Named parameters + * + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * + * @param options.count - Count algorithm to use to count rows in the table or view. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + select< + Query extends string = '*', + ResultOne = GetResult< + Schema, + Relation['Row'], + RelationName, + Relationships, + Query, + ClientOptions + >, + >( + columns?: Query, + options?: { + head?: boolean + count?: 'exact' | 'planned' | 'estimated' + } + ): PostgrestFilterBuilder< + ClientOptions, + Schema, + Relation['Row'], + ResultOne[], + RelationName, + Relationships, + 'GET' + > { + const { head = false, count } = options ?? {} + + const method = head ? 'HEAD' : 'GET' + // Remove whitespaces except when quoted + let quoted = false + const cleanedColumns = (columns ?? '*') + .split('') + .map((c) => { + if (/\s/.test(c) && !quoted) { + return '' + } + if (c === '"') { + quoted = !quoted + } + return c + }) + .join('') + this.url.searchParams.set('select', cleanedColumns) + + if (count) { + this.headers.append('Prefer', `count=${count}`) + } + + return new PostgrestFilterBuilder({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + fetch: this.fetch, + }) + } + + // TODO(v3): Make `defaultToNull` consistent for both single & bulk inserts. + insert( + values: Row, + options?: { + count?: 'exact' | 'planned' | 'estimated' + } + ): PostgrestFilterBuilder< + ClientOptions, + Schema, + Relation['Row'], + null, + RelationName, + Relationships, + 'POST' + > + insert( + values: Row[], + options?: { + count?: 'exact' | 'planned' | 'estimated' + defaultToNull?: boolean + } + ): PostgrestFilterBuilder< + ClientOptions, + Schema, + Relation['Row'], + null, + RelationName, + Relationships, + 'POST' + > + /** + * Perform an INSERT into the table or view. + * + * By default, inserted rows are not returned. To return it, chain the call + * with `.select()`. + * + * @param values - The values to insert. Pass an object to insert a single row + * or an array to insert multiple rows. + * + * @param options - Named parameters + * + * @param options.count - Count algorithm to use to count inserted rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + * + * @param options.defaultToNull - Make missing fields default to `null`. + * Otherwise, use the default value for the column. Only applies for bulk + * inserts. + */ + insert( + values: Row | Row[], + { + count, + defaultToNull = true, + }: { + count?: 'exact' | 'planned' | 'estimated' + defaultToNull?: boolean + } = {} + ): PostgrestFilterBuilder< + ClientOptions, + Schema, + Relation['Row'], + null, + RelationName, + Relationships, + 'POST' + > { + const method = 'POST' + + if (count) { + this.headers.append('Prefer', `count=${count}`) + } + if (!defaultToNull) { + this.headers.append('Prefer', `missing=default`) + } + + if (Array.isArray(values)) { + const columns = values.reduce((acc, x) => acc.concat(Object.keys(x)), [] as string[]) + if (columns.length > 0) { + const uniqueColumns = [...new Set(columns)].map((column) => `"${column}"`) + this.url.searchParams.set('columns', uniqueColumns.join(',')) + } + } + + return new PostgrestFilterBuilder({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + body: values, + fetch: this.fetch ?? fetch, + }) + } + + // TODO(v3): Make `defaultToNull` consistent for both single & bulk upserts. + upsert( + values: Row, + options?: { + onConflict?: string + ignoreDuplicates?: boolean + count?: 'exact' | 'planned' | 'estimated' + } + ): PostgrestFilterBuilder< + ClientOptions, + Schema, + Relation['Row'], + null, + RelationName, + Relationships, + 'POST' + > + upsert( + values: Row[], + options?: { + onConflict?: string + ignoreDuplicates?: boolean + count?: 'exact' | 'planned' | 'estimated' + defaultToNull?: boolean + } + ): PostgrestFilterBuilder< + ClientOptions, + Schema, + Relation['Row'], + null, + RelationName, + Relationships, + 'POST' + > + /** + * Perform an UPSERT on the table or view. Depending on the column(s) passed + * to `onConflict`, `.upsert()` allows you to perform the equivalent of + * `.insert()` if a row with the corresponding `onConflict` columns doesn't + * exist, or if it does exist, perform an alternative action depending on + * `ignoreDuplicates`. + * + * By default, upserted rows are not returned. To return it, chain the call + * with `.select()`. + * + * @param values - The values to upsert with. Pass an object to upsert a + * single row or an array to upsert multiple rows. + * + * @param options - Named parameters + * + * @param options.onConflict - Comma-separated UNIQUE column(s) to specify how + * duplicate rows are determined. Two rows are duplicates if all the + * `onConflict` columns are equal. + * + * @param options.ignoreDuplicates - If `true`, duplicate rows are ignored. If + * `false`, duplicate rows are merged with existing rows. + * + * @param options.count - Count algorithm to use to count upserted rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + * + * @param options.defaultToNull - Make missing fields default to `null`. + * Otherwise, use the default value for the column. This only applies when + * inserting new rows, not when merging with existing rows under + * `ignoreDuplicates: false`. This also only applies when doing bulk upserts. + * + * @example Upsert a single row using a unique key + * ```ts + * // Upserting a single row, overwriting based on the 'username' unique column + * const { data, error } = await supabase + * .from('users') + * .upsert({ username: 'supabot' }, { onConflict: 'username' }) + * + * // Example response: + * // { + * // data: [ + * // { id: 4, message: 'bar', username: 'supabot' } + * // ], + * // error: null + * // } + * ``` + * + * @example Upsert with conflict resolution and exact row counting + * ```ts + * // Upserting and returning exact count + * const { data, error, count } = await supabase + * .from('users') + * .upsert( + * { + * id: 3, + * message: 'foo', + * username: 'supabot' + * }, + * { + * onConflict: 'username', + * count: 'exact' + * } + * ) + * + * // Example response: + * // { + * // data: [ + * // { + * // id: 42, + * // handle: "saoirse", + * // display_name: "Saoirse" + * // } + * // ], + * // count: 1, + * // error: null + * // } + * ``` + */ + + + upsert( + values: Row | Row[], + { + onConflict, + ignoreDuplicates = false, + count, + defaultToNull = true, + }: { + onConflict?: string + ignoreDuplicates?: boolean + count?: 'exact' | 'planned' | 'estimated' + defaultToNull?: boolean + } = {} + ): PostgrestFilterBuilder< + ClientOptions, + Schema, + Relation['Row'], + null, + RelationName, + Relationships, + 'POST' + > { + const method = 'POST' + + this.headers.append('Prefer', `resolution=${ignoreDuplicates ? 'ignore' : 'merge'}-duplicates`) + + if (onConflict !== undefined) this.url.searchParams.set('on_conflict', onConflict) + if (count) { + this.headers.append('Prefer', `count=${count}`) + } + if (!defaultToNull) { + this.headers.append('Prefer', 'missing=default') + } + + if (Array.isArray(values)) { + const columns = values.reduce((acc, x) => acc.concat(Object.keys(x)), [] as string[]) + if (columns.length > 0) { + const uniqueColumns = [...new Set(columns)].map((column) => `"${column}"`) + this.url.searchParams.set('columns', uniqueColumns.join(',')) + } + } + + return new PostgrestFilterBuilder({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + body: values, + fetch: this.fetch ?? fetch, + }) + } + + /** + * Perform an UPDATE on the table or view. + * + * By default, updated rows are not returned. To return it, chain the call + * with `.select()` after filters. + * + * @param values - The values to update with + * + * @param options - Named parameters + * + * @param options.count - Count algorithm to use to count updated rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + update( + values: Row, + { + count, + }: { + count?: 'exact' | 'planned' | 'estimated' + } = {} + ): PostgrestFilterBuilder< + ClientOptions, + Schema, + Relation['Row'], + null, + RelationName, + Relationships, + 'PATCH' + > { + const method = 'PATCH' + if (count) { + this.headers.append('Prefer', `count=${count}`) + } + + return new PostgrestFilterBuilder({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + body: values, + fetch: this.fetch ?? fetch, + }) + } + + /** + * Perform a DELETE on the table or view. + * + * By default, deleted rows are not returned. To return it, chain the call + * with `.select()` after filters. + * + * @param options - Named parameters + * + * @param options.count - Count algorithm to use to count deleted rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + delete({ + count, + }: { + count?: 'exact' | 'planned' | 'estimated' + } = {}): PostgrestFilterBuilder< + ClientOptions, + Schema, + Relation['Row'], + null, + RelationName, + Relationships, + 'DELETE' + > { + const method = 'DELETE' + if (count) { + this.headers.append('Prefer', `count=${count}`) + } + + return new PostgrestFilterBuilder({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + fetch: this.fetch ?? fetch, + }) + } +} diff --git a/backend/node_modules/@supabase/postgrest-js/src/PostgrestTransformBuilder.ts b/backend/node_modules/@supabase/postgrest-js/src/PostgrestTransformBuilder.ts new file mode 100644 index 0000000..52b5541 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/src/PostgrestTransformBuilder.ts @@ -0,0 +1,373 @@ +import PostgrestBuilder from './PostgrestBuilder' +import PostgrestFilterBuilder, { InvalidMethodError } from './PostgrestFilterBuilder' +import { GetResult } from './select-query-parser/result' +import { CheckMatchingArrayTypes } from './types/types' +import { ClientServerOptions, GenericSchema } from './types/common/common' +import type { MaxAffectedEnabled } from './types/feature-flags' + +export default class PostgrestTransformBuilder< + ClientOptions extends ClientServerOptions, + Schema extends GenericSchema, + Row extends Record, + Result, + RelationName = unknown, + Relationships = unknown, + Method = unknown, +> extends PostgrestBuilder { + /** + * Perform a SELECT on the query result. + * + * By default, `.insert()`, `.update()`, `.upsert()`, and `.delete()` do not + * return modified rows. By calling this method, modified rows are returned in + * `data`. + * + * @param columns - The columns to retrieve, separated by commas + */ + select< + Query extends string = '*', + NewResultOne = GetResult, + >( + columns?: Query + ): PostgrestFilterBuilder< + ClientOptions, + Schema, + Row, + Method extends 'RPC' + ? Result extends unknown[] + ? NewResultOne[] + : NewResultOne + : NewResultOne[], + RelationName, + Relationships, + Method + > { + // Remove whitespaces except when quoted + let quoted = false + const cleanedColumns = (columns ?? '*') + .split('') + .map((c) => { + if (/\s/.test(c) && !quoted) { + return '' + } + if (c === '"') { + quoted = !quoted + } + return c + }) + .join('') + this.url.searchParams.set('select', cleanedColumns) + this.headers.append('Prefer', 'return=representation') + return this as unknown as PostgrestFilterBuilder< + ClientOptions, + Schema, + Row, + Method extends 'RPC' + ? Result extends unknown[] + ? NewResultOne[] + : NewResultOne + : NewResultOne[], + RelationName, + Relationships, + Method + > + } + + order( + column: ColumnName, + options?: { ascending?: boolean; nullsFirst?: boolean; referencedTable?: undefined } + ): this + order( + column: string, + options?: { ascending?: boolean; nullsFirst?: boolean; referencedTable?: string } + ): this + /** + * @deprecated Use `options.referencedTable` instead of `options.foreignTable` + */ + order( + column: ColumnName, + options?: { ascending?: boolean; nullsFirst?: boolean; foreignTable?: undefined } + ): this + /** + * @deprecated Use `options.referencedTable` instead of `options.foreignTable` + */ + order( + column: string, + options?: { ascending?: boolean; nullsFirst?: boolean; foreignTable?: string } + ): this + /** + * Order the query result by `column`. + * + * You can call this method multiple times to order by multiple columns. + * + * You can order referenced tables, but it only affects the ordering of the + * parent table if you use `!inner` in the query. + * + * @param column - The column to order by + * @param options - Named parameters + * @param options.ascending - If `true`, the result will be in ascending order + * @param options.nullsFirst - If `true`, `null`s appear first. If `false`, + * `null`s appear last. + * @param options.referencedTable - Set this to order a referenced table by + * its columns + * @param options.foreignTable - Deprecated, use `options.referencedTable` + * instead + */ + order( + column: string, + { + ascending = true, + nullsFirst, + foreignTable, + referencedTable = foreignTable, + }: { + ascending?: boolean + nullsFirst?: boolean + foreignTable?: string + referencedTable?: string + } = {} + ): this { + const key = referencedTable ? `${referencedTable}.order` : 'order' + const existingOrder = this.url.searchParams.get(key) + + this.url.searchParams.set( + key, + `${existingOrder ? `${existingOrder},` : ''}${column}.${ascending ? 'asc' : 'desc'}${ + nullsFirst === undefined ? '' : nullsFirst ? '.nullsfirst' : '.nullslast' + }` + ) + return this + } + + /** + * Limit the query result by `count`. + * + * @param count - The maximum number of rows to return + * @param options - Named parameters + * @param options.referencedTable - Set this to limit rows of referenced + * tables instead of the parent table + * @param options.foreignTable - Deprecated, use `options.referencedTable` + * instead + */ + limit( + count: number, + { + foreignTable, + referencedTable = foreignTable, + }: { foreignTable?: string; referencedTable?: string } = {} + ): this { + const key = typeof referencedTable === 'undefined' ? 'limit' : `${referencedTable}.limit` + this.url.searchParams.set(key, `${count}`) + return this + } + + /** + * Limit the query result by starting at an offset `from` and ending at the offset `to`. + * Only records within this range are returned. + * This respects the query order and if there is no order clause the range could behave unexpectedly. + * The `from` and `to` values are 0-based and inclusive: `range(1, 3)` will include the second, third + * and fourth rows of the query. + * + * @param from - The starting index from which to limit the result + * @param to - The last index to which to limit the result + * @param options - Named parameters + * @param options.referencedTable - Set this to limit rows of referenced + * tables instead of the parent table + * @param options.foreignTable - Deprecated, use `options.referencedTable` + * instead + */ + range( + from: number, + to: number, + { + foreignTable, + referencedTable = foreignTable, + }: { foreignTable?: string; referencedTable?: string } = {} + ): this { + const keyOffset = + typeof referencedTable === 'undefined' ? 'offset' : `${referencedTable}.offset` + const keyLimit = typeof referencedTable === 'undefined' ? 'limit' : `${referencedTable}.limit` + this.url.searchParams.set(keyOffset, `${from}`) + // Range is inclusive, so add 1 + this.url.searchParams.set(keyLimit, `${to - from + 1}`) + return this + } + + /** + * Set the AbortSignal for the fetch request. + * + * @param signal - The AbortSignal to use for the fetch request + */ + abortSignal(signal: AbortSignal): this { + this.signal = signal + return this + } + + /** + * Return `data` as a single object instead of an array of objects. + * + * Query result must be one row (e.g. using `.limit(1)`), otherwise this + * returns an error. + */ + single(): PostgrestBuilder< + ClientOptions, + ResultOne + > { + this.headers.set('Accept', 'application/vnd.pgrst.object+json') + return this as unknown as PostgrestBuilder + } + + /** + * Return `data` as a single object instead of an array of objects. + * + * Query result must be zero or one row (e.g. using `.limit(1)`), otherwise + * this returns an error. + */ + maybeSingle< + ResultOne = Result extends (infer ResultOne)[] ? ResultOne : never, + >(): PostgrestBuilder { + // Temporary partial fix for https://github.com/supabase/postgrest-js/issues/361 + // Issue persists e.g. for `.insert([...]).select().maybeSingle()` + if (this.method === 'GET') { + this.headers.set('Accept', 'application/json') + } else { + this.headers.set('Accept', 'application/vnd.pgrst.object+json') + } + this.isMaybeSingle = true + return this as unknown as PostgrestBuilder + } + + /** + * Return `data` as a string in CSV format. + */ + csv(): PostgrestBuilder { + this.headers.set('Accept', 'text/csv') + return this as unknown as PostgrestBuilder + } + + /** + * Return `data` as an object in [GeoJSON](https://geojson.org) format. + */ + geojson(): PostgrestBuilder> { + this.headers.set('Accept', 'application/geo+json') + return this as unknown as PostgrestBuilder> + } + + /** + * Return `data` as the EXPLAIN plan for the query. + * + * You need to enable the + * [db_plan_enabled](https://supabase.com/docs/guides/database/debugging-performance#enabling-explain) + * setting before using this method. + * + * @param options - Named parameters + * + * @param options.analyze - If `true`, the query will be executed and the + * actual run time will be returned + * + * @param options.verbose - If `true`, the query identifier will be returned + * and `data` will include the output columns of the query + * + * @param options.settings - If `true`, include information on configuration + * parameters that affect query planning + * + * @param options.buffers - If `true`, include information on buffer usage + * + * @param options.wal - If `true`, include information on WAL record generation + * + * @param options.format - The format of the output, can be `"text"` (default) + * or `"json"` + */ + explain({ + analyze = false, + verbose = false, + settings = false, + buffers = false, + wal = false, + format = 'text', + }: { + analyze?: boolean + verbose?: boolean + settings?: boolean + buffers?: boolean + wal?: boolean + format?: 'json' | 'text' + } = {}) { + const options = [ + analyze ? 'analyze' : null, + verbose ? 'verbose' : null, + settings ? 'settings' : null, + buffers ? 'buffers' : null, + wal ? 'wal' : null, + ] + .filter(Boolean) + .join('|') + // An Accept header can carry multiple media types but postgrest-js always sends one + const forMediatype = this.headers.get('Accept') ?? 'application/json' + this.headers.set( + 'Accept', + `application/vnd.pgrst.plan+${format}; for="${forMediatype}"; options=${options};` + ) + if (format === 'json') { + return this as unknown as PostgrestBuilder[]> + } else { + return this as unknown as PostgrestBuilder + } + } + + /** + * Rollback the query. + * + * `data` will still be returned, but the query is not committed. + */ + rollback(): this { + this.headers.append('Prefer', 'tx=rollback') + return this + } + + /** + * Override the type of the returned `data`. + * + * @typeParam NewResult - The new result type to override with + * @deprecated Use overrideTypes() method at the end of your call chain instead + */ + returns(): PostgrestTransformBuilder< + ClientOptions, + Schema, + Row, + CheckMatchingArrayTypes, + RelationName, + Relationships, + Method + > { + return this as unknown as PostgrestTransformBuilder< + ClientOptions, + Schema, + Row, + CheckMatchingArrayTypes, + RelationName, + Relationships, + Method + > + } + + /** + * Set the maximum number of rows that can be affected by the query. + * Only available in PostgREST v13+ and only works with PATCH and DELETE methods. + * + * @param value - The maximum number of rows that can be affected + */ + maxAffected(value: number): MaxAffectedEnabled extends true + ? // TODO: update the RPC case to only work on RPC that returns SETOF rows + Method extends 'PATCH' | 'DELETE' | 'RPC' + ? this + : InvalidMethodError<'maxAffected method only available on update or delete'> + : InvalidMethodError<'maxAffected method only available on postgrest 13+'> { + this.headers.append('Prefer', 'handling=strict') + this.headers.append('Prefer', `max-affected=${value}`) + return this as unknown as MaxAffectedEnabled extends true + ? Method extends 'PATCH' | 'DELETE' | 'RPC' + ? this + : InvalidMethodError<'maxAffected method only available on update or delete'> + : InvalidMethodError<'maxAffected method only available on postgrest 13+'> + } +} diff --git a/backend/node_modules/@supabase/postgrest-js/src/constants.ts b/backend/node_modules/@supabase/postgrest-js/src/constants.ts new file mode 100644 index 0000000..9870d64 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/src/constants.ts @@ -0,0 +1,2 @@ +import { version } from './version' +export const DEFAULT_HEADERS = { 'X-Client-Info': `postgrest-js/${version}` } diff --git a/backend/node_modules/@supabase/postgrest-js/src/index.ts b/backend/node_modules/@supabase/postgrest-js/src/index.ts new file mode 100644 index 0000000..83772cd --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/src/index.ts @@ -0,0 +1,35 @@ +// Always update wrapper.mjs when updating this file. +import PostgrestClient from './PostgrestClient' +import PostgrestQueryBuilder from './PostgrestQueryBuilder' +import PostgrestFilterBuilder from './PostgrestFilterBuilder' +import PostgrestTransformBuilder from './PostgrestTransformBuilder' +import PostgrestBuilder from './PostgrestBuilder' +import PostgrestError from './PostgrestError' + +export { + PostgrestClient, + PostgrestQueryBuilder, + PostgrestFilterBuilder, + PostgrestTransformBuilder, + PostgrestBuilder, + PostgrestError, +} +export default { + PostgrestClient, + PostgrestQueryBuilder, + PostgrestFilterBuilder, + PostgrestTransformBuilder, + PostgrestBuilder, + PostgrestError, +} +export type { + PostgrestResponse, + PostgrestResponseFailure, + PostgrestResponseSuccess, + PostgrestSingleResponse, + PostgrestMaybeSingleResponse, +} from './types/types' +export type { ClientServerOptions as PostgrestClientOptions } from './types/common/common' +// https://github.com/supabase/postgrest-js/issues/551 +// To be replaced with a helper type that only uses public types +export type { GetResult as UnstableGetResult } from './select-query-parser/result' diff --git a/backend/node_modules/@supabase/postgrest-js/src/select-query-parser/parser.ts b/backend/node_modules/@supabase/postgrest-js/src/select-query-parser/parser.ts new file mode 100644 index 0000000..1f87aa8 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/src/select-query-parser/parser.ts @@ -0,0 +1,476 @@ +// Credits to @bnjmnt4n (https://www.npmjs.com/package/postgrest-query) +// See https://github.com/PostgREST/postgrest/blob/2f91853cb1de18944a4556df09e52450b881cfb3/src/PostgREST/ApiRequest/QueryParams.hs#L282-L284 + +import { SimplifyDeep } from '../types/types' +import { JsonPathToAccessor } from './utils' + +/** + * Parses a query. + * A query is a sequence of nodes, separated by `,`, ensuring that there is + * no remaining input after all nodes have been parsed. + * + * Returns an array of parsed nodes, or an error. + */ +export type ParseQuery = string extends Query + ? GenericStringError + : ParseNodes> extends [infer Nodes, `${infer Remainder}`] + ? Nodes extends Ast.Node[] + ? EatWhitespace extends '' + ? SimplifyDeep + : ParserError<`Unexpected input: ${Remainder}`> + : ParserError<'Invalid nodes array structure'> + : ParseNodes> + +/** + * Notes: all `Parse*` types assume that their input strings have their whitespace + * removed. They return tuples of ["Return Value", "Remainder of text"] or + * a `ParserError`. + */ + +/** + * Parses a sequence of nodes, separated by `,`. + * + * Returns a tuple of ["Parsed fields", "Remainder of text"] or an error. + */ +type ParseNodes = string extends Input + ? GenericStringError + : ParseNodesHelper + +type ParseNodesHelper = + ParseNode extends [infer Node, `${infer Remainder}`] + ? Node extends Ast.Node + ? EatWhitespace extends `,${infer Remainder}` + ? ParseNodesHelper, [...Nodes, Node]> + : [[...Nodes, Node], EatWhitespace] + : ParserError<'Invalid node type in nodes helper'> + : ParseNode +/** + * Parses a node. + * A node is one of the following: + * - `*` + * - a field, as defined above + * - a renamed field, `renamed_field:field` + * - a spread field, `...field` + */ +type ParseNode = Input extends '' + ? ParserError<'Empty string'> + : // `*` + Input extends `*${infer Remainder}` + ? [Ast.StarNode, EatWhitespace] + : // `...field` + Input extends `...${infer Remainder}` + ? ParseField> extends [infer TargetField, `${infer Remainder}`] + ? TargetField extends Ast.FieldNode + ? [{ type: 'spread'; target: TargetField }, EatWhitespace] + : ParserError<'Invalid target field type in spread'> + : ParserError<`Unable to parse spread resource at \`${Input}\``> + : ParseIdentifier extends [infer NameOrAlias, `${infer Remainder}`] + ? EatWhitespace extends `::${infer _}` + ? // It's a type cast and not an alias, so treat it as part of the field. + ParseField + : EatWhitespace extends `:${infer Remainder}` + ? // `alias:` + ParseField> extends [infer Field, `${infer Remainder}`] + ? Field extends Ast.FieldNode + ? [Omit & { alias: NameOrAlias }, EatWhitespace] + : ParserError<'Invalid field type in alias parsing'> + : ParserError<`Unable to parse renamed field at \`${Input}\``> + : // Otherwise, just parse it as a field without alias. + ParseField + : ParserError<`Expected identifier at \`${Input}\``> + +/** + * Parses a field without preceding alias. + * A field is one of the following: + * - a top-level `count` field: https://docs.postgrest.org/en/v12/references/api/aggregate_functions.html#the-case-of-count + * - a field with an embedded resource + * - `field(nodes)` + * - `field!hint(nodes)` + * - `field!inner(nodes)` + * - `field!left(nodes)` + * - `field!hint!inner(nodes)` + * - `field!hint!left(nodes)` + * - a field without an embedded resource (see {@link ParseNonEmbeddedResourceField}) + */ +type ParseField = Input extends '' + ? ParserError<'Empty string'> + : ParseIdentifier extends [infer Name, `${infer Remainder}`] + ? Name extends 'count' + ? ParseCountField + : Remainder extends `!inner${infer Remainder}` + ? ParseEmbeddedResource> extends [ + infer Children, + `${infer Remainder}`, + ] + ? Children extends Ast.Node[] + ? // `field!inner(nodes)` + [{ type: 'field'; name: Name; innerJoin: true; children: Children }, Remainder] + : ParserError<'Invalid children array in inner join'> + : CreateParserErrorIfRequired< + ParseEmbeddedResource>, + `Expected embedded resource after "!inner" at \`${Remainder}\`` + > + : EatWhitespace extends `!left${infer Remainder}` + ? ParseEmbeddedResource> extends [ + infer Children, + `${infer Remainder}`, + ] + ? Children extends Ast.Node[] + ? // `field!left(nodes)` + // !left is a noise word - treat it the same way as a non-`!inner`. + [{ type: 'field'; name: Name; children: Children }, EatWhitespace] + : ParserError<'Invalid children array in left join'> + : CreateParserErrorIfRequired< + ParseEmbeddedResource>, + `Expected embedded resource after "!left" at \`${EatWhitespace}\`` + > + : EatWhitespace extends `!${infer Remainder}` + ? ParseIdentifier> extends [infer Hint, `${infer Remainder}`] + ? EatWhitespace extends `!inner${infer Remainder}` + ? ParseEmbeddedResource> extends [ + infer Children, + `${infer Remainder}`, + ] + ? Children extends Ast.Node[] + ? // `field!hint!inner(nodes)` + [ + { + type: 'field' + name: Name + hint: Hint + innerJoin: true + children: Children + }, + EatWhitespace, + ] + : ParserError<'Invalid children array in hint inner join'> + : ParseEmbeddedResource> + : ParseEmbeddedResource> extends [ + infer Children, + `${infer Remainder}`, + ] + ? Children extends Ast.Node[] + ? // `field!hint(nodes)` + [ + { type: 'field'; name: Name; hint: Hint; children: Children }, + EatWhitespace, + ] + : ParserError<'Invalid children array in hint'> + : ParseEmbeddedResource> + : ParserError<`Expected identifier after "!" at \`${EatWhitespace}\``> + : EatWhitespace extends `(${infer _}` + ? ParseEmbeddedResource> extends [ + infer Children, + `${infer Remainder}`, + ] + ? Children extends Ast.Node[] + ? // `field(nodes)` + [{ type: 'field'; name: Name; children: Children }, EatWhitespace] + : ParserError<'Invalid children array in field'> + : // Return error if start of embedded resource was detected but not found. + ParseEmbeddedResource> + : // Otherwise it's a non-embedded resource field. + ParseNonEmbeddedResourceField + : ParserError<`Expected identifier at \`${Input}\``> + +type ParseCountField = + ParseIdentifier extends ['count', `${infer Remainder}`] + ? ( + EatWhitespace extends `()${infer Remainder_}` + ? EatWhitespace + : EatWhitespace + ) extends `${infer Remainder}` + ? Remainder extends `::${infer _}` + ? ParseFieldTypeCast extends [infer CastType, `${infer Remainder}`] + ? [ + { type: 'field'; name: 'count'; aggregateFunction: 'count'; castType: CastType }, + Remainder, + ] + : ParseFieldTypeCast + : [{ type: 'field'; name: 'count'; aggregateFunction: 'count' }, Remainder] + : never + : ParserError<`Expected "count" at \`${Input}\``> + +/** + * Parses an embedded resource, which is an opening `(`, followed by a sequence of + * 0 or more nodes separated by `,`, then a closing `)`. + * + * Returns a tuple of ["Parsed fields", "Remainder of text"], an error, + * or the original string input indicating that no opening `(` was found. + */ +type ParseEmbeddedResource = Input extends `(${infer Remainder}` + ? EatWhitespace extends `)${infer Remainder}` + ? [[], EatWhitespace] + : ParseNodes> extends [infer Nodes, `${infer Remainder}`] + ? Nodes extends Ast.Node[] + ? EatWhitespace extends `)${infer Remainder}` + ? [Nodes, EatWhitespace] + : ParserError<`Expected ")" at \`${EatWhitespace}\``> + : ParserError<'Invalid nodes array in embedded resource'> + : ParseNodes> + : ParserError<`Expected "(" at \`${Input}\``> + +/** + * Parses a field excluding embedded resources, without preceding field renaming. + * This is one of the following: + * - `field` + * - `field.aggregate()` + * - `field.aggregate()::type` + * - `field::type` + * - `field::type.aggregate()` + * - `field::type.aggregate()::type` + * - `field->json...` + * - `field->json.aggregate()` + * - `field->json.aggregate()::type` + * - `field->json::type` + * - `field->json::type.aggregate()` + * - `field->json::type.aggregate()::type` + */ +type ParseNonEmbeddedResourceField = + ParseIdentifier extends [infer Name, `${infer Remainder}`] + ? // Parse optional JSON path. + ( + Remainder extends `->${infer PathAndRest}` + ? ParseJsonAccessor extends [ + infer PropertyName, + infer PropertyType, + `${infer Remainder}`, + ] + ? [ + { + type: 'field' + name: Name + alias: PropertyName + castType: PropertyType + jsonPath: JsonPathToAccessor< + PathAndRest extends `${infer Path},${string}` ? Path : PathAndRest + > + }, + Remainder, + ] + : ParseJsonAccessor + : [{ type: 'field'; name: Name }, Remainder] + ) extends infer Parsed + ? Parsed extends [infer Field, `${infer Remainder}`] + ? // Parse optional typecast or aggregate function input typecast. + ( + Remainder extends `::${infer _}` + ? ParseFieldTypeCast extends [infer CastType, `${infer Remainder}`] + ? [Omit & { castType: CastType }, Remainder] + : ParseFieldTypeCast + : [Field, Remainder] + ) extends infer Parsed + ? Parsed extends [infer Field, `${infer Remainder}`] + ? // Parse optional aggregate function. + Remainder extends `.${infer _}` + ? ParseFieldAggregation extends [ + infer AggregateFunction, + `${infer Remainder}`, + ] + ? // Parse optional aggregate function output typecast. + Remainder extends `::${infer _}` + ? ParseFieldTypeCast extends [infer CastType, `${infer Remainder}`] + ? [ + Omit & { + aggregateFunction: AggregateFunction + castType: CastType + }, + Remainder, + ] + : ParseFieldTypeCast + : [Field & { aggregateFunction: AggregateFunction }, Remainder] + : ParseFieldAggregation + : [Field, Remainder] + : Parsed + : never + : Parsed + : never + : ParserError<`Expected identifier at \`${Input}\``> + +/** + * Parses a JSON property accessor of the shape `->a->b->c`. The last accessor in + * the series may convert to text by using the ->> operator instead of ->. + * + * Returns a tuple of ["Last property name", "Last property type", "Remainder of text"] + */ +type ParseJsonAccessor = Input extends `->${infer Remainder}` + ? Remainder extends `>${infer Remainder}` + ? ParseIdentifier extends [infer Name, `${infer Remainder}`] + ? [Name, 'text', EatWhitespace] + : ParserError<'Expected property name after `->>`'> + : ParseIdentifier extends [infer Name, `${infer Remainder}`] + ? ParseJsonAccessor extends [ + infer PropertyName, + infer PropertyType, + `${infer Remainder}`, + ] + ? [PropertyName, PropertyType, EatWhitespace] + : [Name, 'json', EatWhitespace] + : ParserError<'Expected property name after `->`'> + : ParserError<'Expected ->'> + +/** + * Parses a field typecast (`::type`), returning a tuple of ["Type", "Remainder of text"]. + */ +type ParseFieldTypeCast = + EatWhitespace extends `::${infer Remainder}` + ? ParseIdentifier> extends [`${infer CastType}`, `${infer Remainder}`] + ? [CastType, EatWhitespace] + : ParserError<`Invalid type for \`::\` operator at \`${Remainder}\``> + : ParserError<'Expected ::'> + +/** + * Parses a field aggregation (`.max()`), returning a tuple of ["Aggregate function", "Remainder of text"] + */ +type ParseFieldAggregation = + EatWhitespace extends `.${infer Remainder}` + ? ParseIdentifier> extends [ + `${infer FunctionName}`, + `${infer Remainder}`, + ] + ? // Ensure that aggregation function is valid. + FunctionName extends Token.AggregateFunction + ? EatWhitespace extends `()${infer Remainder}` + ? [FunctionName, EatWhitespace] + : ParserError<`Expected \`()\` after \`.\` operator \`${FunctionName}\``> + : ParserError<`Invalid type for \`.\` operator \`${FunctionName}\``> + : ParserError<`Invalid type for \`.\` operator at \`${Remainder}\``> + : ParserError<'Expected .'> + +/** + * Parses a (possibly double-quoted) identifier. + * Identifiers are sequences of 1 or more letters. + */ +type ParseIdentifier = + ParseLetters extends [infer Name, `${infer Remainder}`] + ? [Name, EatWhitespace] + : ParseQuotedLetters extends [infer Name, `${infer Remainder}`] + ? [Name, EatWhitespace] + : ParserError<`No (possibly double-quoted) identifier at \`${Input}\``> + +/** + * Parse a consecutive sequence of 1 or more letter, where letters are `[0-9a-zA-Z_]`. + */ +type ParseLetters = string extends Input + ? GenericStringError + : ParseLettersHelper extends [`${infer Letters}`, `${infer Remainder}`] + ? Letters extends '' + ? ParserError<`Expected letter at \`${Input}\``> + : [Letters, Remainder] + : ParseLettersHelper + +type ParseLettersHelper = string extends Input + ? GenericStringError + : Input extends `${infer L}${infer Remainder}` + ? L extends Token.Letter + ? ParseLettersHelper + : [Acc, Input] + : [Acc, ''] + +/** + * Parse a consecutive sequence of 1 or more double-quoted letters, + * where letters are `[^"]`. + */ +type ParseQuotedLetters = string extends Input + ? GenericStringError + : Input extends `"${infer Remainder}` + ? ParseQuotedLettersHelper extends [`${infer Letters}`, `${infer Remainder}`] + ? Letters extends '' + ? ParserError<`Expected string at \`${Remainder}\``> + : [Letters, Remainder] + : ParseQuotedLettersHelper + : ParserError<`Not a double-quoted string at \`${Input}\``> + +type ParseQuotedLettersHelper = string extends Input + ? GenericStringError + : Input extends `${infer L}${infer Remainder}` + ? L extends '"' + ? [Acc, Remainder] + : ParseQuotedLettersHelper + : ParserError<`Missing closing double-quote in \`"${Acc}${Input}\``> + +/** + * Trims whitespace from the left of the input. + */ +type EatWhitespace = string extends Input + ? GenericStringError + : Input extends `${Token.Whitespace}${infer Remainder}` + ? EatWhitespace + : Input + +/** + * Creates a new {@link ParserError} if the given input is not already a parser error. + */ +type CreateParserErrorIfRequired = + Input extends ParserError ? Input : ParserError + +/** + * Parser errors. + */ +export type ParserError = { error: true } & Message +type GenericStringError = ParserError<'Received a generic string'> + +export namespace Ast { + export type Node = FieldNode | StarNode | SpreadNode + + export type FieldNode = { + type: 'field' + name: string + alias?: string + hint?: string + innerJoin?: true + castType?: string + jsonPath?: string + aggregateFunction?: Token.AggregateFunction + children?: Node[] + } + + export type StarNode = { + type: 'star' + } + + export type SpreadNode = { + type: 'spread' + target: FieldNode & { children: Node[] } + } +} + +namespace Token { + export type Whitespace = ' ' | '\n' | '\t' + + type LowerAlphabet = + | 'a' + | 'b' + | 'c' + | 'd' + | 'e' + | 'f' + | 'g' + | 'h' + | 'i' + | 'j' + | 'k' + | 'l' + | 'm' + | 'n' + | 'o' + | 'p' + | 'q' + | 'r' + | 's' + | 't' + | 'u' + | 'v' + | 'w' + | 'x' + | 'y' + | 'z' + + type Alphabet = LowerAlphabet | Uppercase + + type Digit = '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | '0' + + export type Letter = Alphabet | Digit | '_' + + export type AggregateFunction = 'count' | 'sum' | 'avg' | 'min' | 'max' +} diff --git a/backend/node_modules/@supabase/postgrest-js/src/select-query-parser/result.ts b/backend/node_modules/@supabase/postgrest-js/src/select-query-parser/result.ts new file mode 100644 index 0000000..22207af --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/src/select-query-parser/result.ts @@ -0,0 +1,524 @@ +import { Ast, ParseQuery } from './parser' +import { + AggregateFunctions, + ExtractFirstProperty, + GenericSchema, + IsNonEmptyArray, + Prettify, + TablesAndViews, + TypeScriptTypes, + ContainsNull, + GenericRelationship, + PostgreSQLTypes, + GenericTable, + ClientServerOptions, +} from './types' +import { + CheckDuplicateEmbededReference, + GetComputedFields, + GetFieldNodeResultName, + IsAny, + IsRelationNullable, + IsStringUnion, + JsonPathToType, + ResolveRelationship, + SelectQueryError, +} from './utils' +import type { SpreadOnManyEnabled } from '../types/feature-flags' + +/** + * Main entry point for constructing the result type of a PostgREST query. + * + * @param Schema - Database schema. + * @param Row - The type of a row in the current table. + * @param RelationName - The name of the current table or view. + * @param Relationships - Relationships of the current table. + * @param Query - The select query string literal to parse. + */ +export type GetResult< + Schema extends GenericSchema, + Row extends Record, + RelationName, + Relationships, + Query extends string, + ClientOptions extends ClientServerOptions, +> = + IsAny extends true + ? ParseQuery extends infer ParsedQuery + ? ParsedQuery extends Ast.Node[] + ? RelationName extends string + ? ProcessNodesWithoutSchema + : any + : ParsedQuery + : any + : Relationships extends null // For .rpc calls the passed relationships will be null in that case, the result will always be the function return type + ? ParseQuery extends infer ParsedQuery + ? ParsedQuery extends Ast.Node[] + ? RPCCallNodes + : ParsedQuery + : Row + : ParseQuery extends infer ParsedQuery + ? ParsedQuery extends Ast.Node[] + ? RelationName extends string + ? Relationships extends GenericRelationship[] + ? ProcessNodes + : SelectQueryError<'Invalid Relationships cannot infer result type'> + : SelectQueryError<'Invalid RelationName cannot infer result type'> + : ParsedQuery + : never + +type ProcessSimpleFieldWithoutSchema = + Field['aggregateFunction'] extends AggregateFunctions + ? { + // An aggregate function will always override the column name id.sum() will become sum + // except if it has been aliased + [K in GetFieldNodeResultName]: Field['castType'] extends PostgreSQLTypes + ? TypeScriptTypes + : number + } + : { + // Aliases override the property name in the result + [K in GetFieldNodeResultName]: Field['castType'] extends PostgreSQLTypes // We apply the detected casted as the result type + ? TypeScriptTypes + : any + } + +type ProcessFieldNodeWithoutSchema = + IsNonEmptyArray extends true + ? { + [K in GetFieldNodeResultName]: Node['children'] extends Ast.Node[] + ? ProcessNodesWithoutSchema[] + : ProcessSimpleFieldWithoutSchema + } + : ProcessSimpleFieldWithoutSchema + +/** + * Processes a single Node without schema and returns the resulting TypeScript type. + */ +type ProcessNodeWithoutSchema = Node extends Ast.StarNode + ? any + : Node extends Ast.SpreadNode + ? Node['target']['children'] extends Ast.StarNode[] + ? any + : Node['target']['children'] extends Ast.FieldNode[] + ? { + [P in Node['target']['children'][number] as GetFieldNodeResultName

]: P['castType'] extends PostgreSQLTypes + ? TypeScriptTypes + : any + } + : any + : Node extends Ast.FieldNode + ? ProcessFieldNodeWithoutSchema + : any + +/** + * Processes nodes when Schema is any, providing basic type inference + */ +type ProcessNodesWithoutSchema< + Nodes extends Ast.Node[], + Acc extends Record = {}, +> = Nodes extends [infer FirstNode, ...infer RestNodes] + ? FirstNode extends Ast.Node + ? RestNodes extends Ast.Node[] + ? ProcessNodeWithoutSchema extends infer FieldResult + ? FieldResult extends Record + ? ProcessNodesWithoutSchema + : FieldResult + : any + : any + : any + : Prettify + +/** + * Processes a single Node from a select chained after a rpc call + * + * @param Row - The type of a row in the current table. + * @param RelationName - The name of the current rpc function + * @param NodeType - The Node to process. + */ +export type ProcessRPCNode< + Row extends Record, + RelationName extends string, + NodeType extends Ast.Node, +> = NodeType['type'] extends Ast.StarNode['type'] // If the selection is * + ? Row + : NodeType['type'] extends Ast.FieldNode['type'] + ? ProcessSimpleField> + : SelectQueryError<'RPC Unsupported node type.'> + +/** + * Process select call that can be chained after an rpc call + */ +export type RPCCallNodes< + Nodes extends Ast.Node[], + RelationName extends string, + Row extends Record, + Acc extends Record = {}, // Acc is now an object +> = Nodes extends [infer FirstNode, ...infer RestNodes] + ? FirstNode extends Ast.Node + ? RestNodes extends Ast.Node[] + ? ProcessRPCNode extends infer FieldResult + ? FieldResult extends Record + ? RPCCallNodes + : FieldResult extends SelectQueryError + ? SelectQueryError + : SelectQueryError<'Could not retrieve a valid record or error value'> + : SelectQueryError<'Processing node failed.'> + : SelectQueryError<'Invalid rest nodes array in RPC call'> + : SelectQueryError<'Invalid first node in RPC call'> + : Prettify + +/** + * Recursively processes an array of Nodes and accumulates the resulting TypeScript type. + * + * @param Schema - Database schema. + * @param Row - The type of a row in the current table. + * @param RelationName - The name of the current table or view. + * @param Relationships - Relationships of the current table. + * @param Nodes - An array of AST nodes to process. + * @param Acc - Accumulator for the constructed type. + */ +export type ProcessNodes< + ClientOptions extends ClientServerOptions, + Schema extends GenericSchema, + Row extends Record, + RelationName extends string, + Relationships extends GenericRelationship[], + Nodes extends Ast.Node[], + Acc extends Record = {}, // Acc is now an object +> = + CheckDuplicateEmbededReference extends false + ? Nodes extends [infer FirstNode, ...infer RestNodes] + ? FirstNode extends Ast.Node + ? RestNodes extends Ast.Node[] + ? ProcessNode< + ClientOptions, + Schema, + Row, + RelationName, + Relationships, + FirstNode + > extends infer FieldResult + ? FieldResult extends Record + ? ProcessNodes< + ClientOptions, + Schema, + Row, + RelationName, + Relationships, + RestNodes, + // TODO: + // This SHOULD be `Omit & FieldResult` since in the case where the key + // is present in the Acc already, the intersection will create bad intersection types + // (eg: `{ a: number } & { a: { property } }` will become `{ a: number & { property } }`) + // but using Omit here explode the inference complexity resulting in "infinite recursion error" from typescript + // very early (see: 'Check that selecting many fields doesn't yield an possibly infinite recursion error') test + // in this case we can't get above ~10 fields before reaching the recursion error + // If someone find a better way to do this, please do it ! + // It'll also allow to fix those two tests: + // - `'join over a 1-M relation with both nullables and non-nullables fields using column name hinting on nested relation'` + // - `'self reference relation via column''` + Acc & FieldResult + > + : FieldResult extends SelectQueryError + ? SelectQueryError + : SelectQueryError<'Could not retrieve a valid record or error value'> + : SelectQueryError<'Processing node failed.'> + : SelectQueryError<'Invalid rest nodes array type in ProcessNodes'> + : SelectQueryError<'Invalid first node type in ProcessNodes'> + : Prettify + : Prettify> + +/** + * Processes a single Node and returns the resulting TypeScript type. + * + * @param Schema - Database schema. + * @param Row - The type of a row in the current table. + * @param RelationName - The name of the current table or view. + * @param Relationships - Relationships of the current table. + * @param NodeType - The Node to process. + */ +export type ProcessNode< + ClientOptions extends ClientServerOptions, + Schema extends GenericSchema, + Row extends Record, + RelationName extends string, + Relationships extends GenericRelationship[], + NodeType extends Ast.Node, +> = + // TODO: figure out why comparing the `type` property is necessary vs. `NodeType extends Ast.StarNode` + NodeType['type'] extends Ast.StarNode['type'] // If the selection is * + ? // If the row has computed field, postgrest will omit them from star selection per default + GetComputedFields extends never + ? // If no computed fields are detected on the row, we can return it as is + Row + : // otherwise we omit all the computed field from the star result return + Omit> + : NodeType['type'] extends Ast.SpreadNode['type'] // If the selection is a ...spread + ? ProcessSpreadNode< + ClientOptions, + Schema, + Row, + RelationName, + Relationships, + Extract + > + : NodeType['type'] extends Ast.FieldNode['type'] + ? ProcessFieldNode< + ClientOptions, + Schema, + Row, + RelationName, + Relationships, + Extract + > + : SelectQueryError<'Unsupported node type.'> + +/** + * Processes a FieldNode and returns the resulting TypeScript type. + * + * @param Schema - Database schema. + * @param Row - The type of a row in the current table. + * @param RelationName - The name of the current table or view. + * @param Relationships - Relationships of the current table. + * @param Field - The FieldNode to process. + */ +type ProcessFieldNode< + ClientOptions extends ClientServerOptions, + Schema extends GenericSchema, + Row extends Record, + RelationName extends string, + Relationships extends GenericRelationship[], + Field extends Ast.FieldNode, +> = Field['children'] extends [] + ? {} + : IsNonEmptyArray extends true // Has embedded resource? + ? ProcessEmbeddedResource + : ProcessSimpleField + +type ResolveJsonPathType< + Value, + Path extends string | undefined, + CastType extends PostgreSQLTypes, +> = Path extends string + ? JsonPathToType extends never + ? // Always fallback if JsonPathToType returns never + TypeScriptTypes + : JsonPathToType extends infer PathResult + ? PathResult extends string + ? // Use the result if it's a string as we know that even with the string accessor ->> it's a valid type + PathResult + : IsStringUnion extends true + ? // Use the result if it's a union of strings + PathResult + : CastType extends 'json' + ? // If the type is not a string, ensure it was accessed with json accessor -> + PathResult + : // Otherwise it means non-string value accessed with string accessor ->> use the TypeScriptTypes result + TypeScriptTypes + : TypeScriptTypes + : // No json path, use regular type casting + TypeScriptTypes + +/** + * Processes a simple field (without embedded resources). + * + * @param Row - The type of a row in the current table. + * @param RelationName - The name of the current table or view. + * @param Field - The FieldNode to process. + */ +type ProcessSimpleField< + Row extends Record, + RelationName extends string, + Field extends Ast.FieldNode, +> = Field['name'] extends keyof Row | 'count' + ? Field['aggregateFunction'] extends AggregateFunctions + ? { + // An aggregate function will always override the column name id.sum() will become sum + // except if it has been aliased + [K in GetFieldNodeResultName]: Field['castType'] extends PostgreSQLTypes + ? TypeScriptTypes + : number + } + : { + // Aliases override the property name in the result + [K in GetFieldNodeResultName]: Field['castType'] extends PostgreSQLTypes + ? ResolveJsonPathType + : Row[Field['name']] + } + : SelectQueryError<`column '${Field['name']}' does not exist on '${RelationName}'.`> + +/** + * Processes an embedded resource (relation). + * + * @param Schema - Database schema. + * @param Row - The type of a row in the current table. + * @param RelationName - The name of the current table or view. + * @param Relationships - Relationships of the current table. + * @param Field - The FieldNode to process. + */ +export type ProcessEmbeddedResource< + ClientOptions extends ClientServerOptions, + Schema extends GenericSchema, + Relationships extends GenericRelationship[], + Field extends Ast.FieldNode, + CurrentTableOrView extends keyof TablesAndViews & string, +> = + ResolveRelationship extends infer Resolved + ? Resolved extends { + referencedTable: Pick + relation: GenericRelationship & { match: 'refrel' | 'col' | 'fkname' | 'func' } + direction: string + } + ? ProcessEmbeddedResourceResult + : // Otherwise the Resolved is a SelectQueryError return it + { [K in GetFieldNodeResultName]: Resolved } + : { + [K in GetFieldNodeResultName]: SelectQueryError<'Failed to resolve relationship.'> & + string + } + +/** + * Helper type to process the result of an embedded resource. + */ +type ProcessEmbeddedResourceResult< + ClientOptions extends ClientServerOptions, + Schema extends GenericSchema, + Resolved extends { + referencedTable: Pick + relation: GenericRelationship & { + match: 'refrel' | 'col' | 'fkname' | 'func' + isNotNullable?: boolean + referencedRelation: string + isSetofReturn?: boolean + } + direction: string + }, + Field extends Ast.FieldNode, + CurrentTableOrView extends keyof TablesAndViews, +> = + ProcessNodes< + ClientOptions, + Schema, + Resolved['referencedTable']['Row'], + // For embeded function selection, the source of truth is the 'referencedRelation' + // coming from the SetofOptions.to parameter + Resolved['relation']['match'] extends 'func' + ? Resolved['relation']['referencedRelation'] + : Field['name'], + Resolved['referencedTable']['Relationships'], + Field['children'] extends undefined + ? [] + : Exclude extends Ast.Node[] + ? Exclude + : [] + > extends infer ProcessedChildren + ? { + [K in GetFieldNodeResultName]: Resolved['direction'] extends 'forward' + ? Field extends { innerJoin: true } + ? Resolved['relation']['isOneToOne'] extends true + ? ProcessedChildren + : ProcessedChildren[] + : Resolved['relation']['isOneToOne'] extends true + ? Resolved['relation']['match'] extends 'func' + ? Resolved['relation']['isNotNullable'] extends true + ? Resolved['relation']['isSetofReturn'] extends true + ? ProcessedChildren + : // TODO: This shouldn't be necessary but is due in an inconsitency in PostgREST v12/13 where if a function + // is declared with RETURNS instead of RETURNS SETOF ROWS 1 + // In case where there is no object matching the relations, the object will be returned with all the properties within it + // set to null, we mimic this buggy behavior for type safety an issue is opened on postgREST here: + // https://github.com/PostgREST/postgrest/issues/4234 + { [P in keyof ProcessedChildren]: ProcessedChildren[P] | null } + : ProcessedChildren | null + : ProcessedChildren | null + : ProcessedChildren[] + : // If the relation is a self-reference it'll always be considered as reverse relationship + Resolved['relation']['referencedRelation'] extends CurrentTableOrView + ? // It can either be a reverse reference via a column inclusion (eg: parent_id(*)) + // in such case the result will be a single object + Resolved['relation']['match'] extends 'col' + ? IsRelationNullable< + TablesAndViews[CurrentTableOrView], + Resolved['relation'] + > extends true + ? ProcessedChildren | null + : ProcessedChildren + : // Or it can be a reference via the reference relation (eg: collections(*)) + // in such case, the result will be an array of all the values (all collection with parent_id being the current id) + ProcessedChildren[] + : // Otherwise if it's a non self-reference reverse relationship it's a single object + IsRelationNullable< + TablesAndViews[CurrentTableOrView], + Resolved['relation'] + > extends true + ? Field extends { innerJoin: true } + ? ProcessedChildren + : ProcessedChildren | null + : ProcessedChildren + } + : { + [K in GetFieldNodeResultName]: SelectQueryError<'Failed to process embedded resource nodes.'> & + string + } + +/** + * Processes a SpreadNode by processing its target node. + * + * @param Schema - Database schema. + * @param Row - The type of a row in the current table. + * @param RelationName - The name of the current table or view. + * @param Relationships - Relationships of the current table. + * @param Spread - The SpreadNode to process. + */ +type ProcessSpreadNode< + ClientOptions extends ClientServerOptions, + Schema extends GenericSchema, + Row extends Record, + RelationName extends string, + Relationships extends GenericRelationship[], + Spread extends Ast.SpreadNode, +> = + ProcessNode< + ClientOptions, + Schema, + Row, + RelationName, + Relationships, + Spread['target'] + > extends infer Result + ? Result extends SelectQueryError + ? SelectQueryError + : ExtractFirstProperty extends unknown[] + ? SpreadOnManyEnabled extends true // Spread over an many-to-many relationship, turn all the result fields into correlated arrays + ? ProcessManyToManySpreadNodeResult + : { + [K in Spread['target']['name']]: SelectQueryError<`"${RelationName}" and "${Spread['target']['name']}" do not form a many-to-one or one-to-one relationship spread not possible`> + } + : ProcessSpreadNodeResult + : never + +/** + * Helper type to process the result of a many-to-many spread node. + * Converts all fields in the spread object into arrays. + */ +type ProcessManyToManySpreadNodeResult = + Result extends Record | null> + ? Result + : ExtractFirstProperty extends infer SpreadedObject + ? SpreadedObject extends Array> + ? { [K in keyof SpreadedObject[number]]: Array } + : SelectQueryError<'An error occurred spreading the many-to-many object'> + : SelectQueryError<'An error occurred spreading the many-to-many object'> + +/** + * Helper type to process the result of a spread node. + */ +type ProcessSpreadNodeResult = + Result extends Record | null> + ? Result + : ExtractFirstProperty extends infer SpreadedObject + ? ContainsNull extends true + ? Exclude<{ [K in keyof SpreadedObject]: SpreadedObject[K] | null }, null> + : Exclude<{ [K in keyof SpreadedObject]: SpreadedObject[K] }, null> + : SelectQueryError<'An error occurred spreading the object'> diff --git a/backend/node_modules/@supabase/postgrest-js/src/select-query-parser/types.ts b/backend/node_modules/@supabase/postgrest-js/src/select-query-parser/types.ts new file mode 100644 index 0000000..7df05df --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/src/select-query-parser/types.ts @@ -0,0 +1,129 @@ +import type { + GenericRelationship, + GenericSchema, + GenericTable, + ClientServerOptions, + GenericSetofOption, + GenericFunction, +} from '../types/common/common' +import type { Prettify } from '../types/types' + +export type { + GenericRelationship, + GenericSchema, + GenericTable, + ClientServerOptions, + GenericSetofOption, + Prettify, + GenericFunction, +} + +export type AggregateWithoutColumnFunctions = 'count' + +export type AggregateWithColumnFunctions = + | 'sum' + | 'avg' + | 'min' + | 'max' + | AggregateWithoutColumnFunctions + +export type AggregateFunctions = AggregateWithColumnFunctions + +export type Json = + | string + | number + | boolean + | null + | { + [key: string]: Json | undefined + } + | Json[] + +type PostgresSQLNumberTypes = 'int2' | 'int4' | 'int8' | 'float4' | 'float8' | 'numeric' + +type PostgresSQLStringTypes = + | 'bytea' + | 'bpchar' + | 'varchar' + | 'date' + | 'text' + | 'citext' + | 'time' + | 'timetz' + | 'timestamp' + | 'timestamptz' + | 'uuid' + | 'vector' + +type SingleValuePostgreSQLTypes = + | PostgresSQLNumberTypes + | PostgresSQLStringTypes + | 'bool' + | 'json' + | 'jsonb' + | 'void' + | 'record' + | string + +type ArrayPostgreSQLTypes = `_${SingleValuePostgreSQLTypes}` + +type TypeScriptSingleValueTypes = T extends 'bool' + ? boolean + : T extends PostgresSQLNumberTypes + ? number + : T extends PostgresSQLStringTypes + ? string + : T extends 'json' | 'jsonb' + ? Json + : T extends 'void' + ? undefined + : T extends 'record' + ? Record + : unknown + +type StripUnderscore = T extends `_${infer U}` ? U : T + +// Represents all possible PostgreSQL types, including array types, allow for custom types with 'string' in union +export type PostgreSQLTypes = SingleValuePostgreSQLTypes | ArrayPostgreSQLTypes + +// Helper type to convert PostgreSQL types to their TypeScript equivalents +export type TypeScriptTypes = T extends ArrayPostgreSQLTypes + ? TypeScriptSingleValueTypes>>[] + : TypeScriptSingleValueTypes + +// Utility types for working with unions +export type UnionToIntersection = (U extends any ? (k: U) => void : never) extends ( + k: infer I +) => void + ? I + : never + +export type LastOf = + UnionToIntersection T : never> extends () => infer R ? R : never + +export type Push = [...T, V] + +// Converts a union type to a tuple type +export type UnionToTuple, N = [T] extends [never] ? true : false> = N extends true + ? [] + : Push>, L> + +export type UnionToArray = UnionToTuple + +// Extracts the type of the first property in an object type +export type ExtractFirstProperty = T extends { [K in keyof T]: infer U } ? U : never + +// Type predicates +export type ContainsNull = null extends T ? true : false + +export type IsNonEmptyArray = + Exclude extends readonly [unknown, ...unknown[]] ? true : false + +// Types for working with database schemas +export type TablesAndViews = Schema['Tables'] & + Exclude + +export type GetTableRelationships< + Schema extends GenericSchema, + Tname extends string, +> = TablesAndViews[Tname] extends { Relationships: infer R } ? R : false diff --git a/backend/node_modules/@supabase/postgrest-js/src/select-query-parser/utils.ts b/backend/node_modules/@supabase/postgrest-js/src/select-query-parser/utils.ts new file mode 100644 index 0000000..b766454 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/src/select-query-parser/utils.ts @@ -0,0 +1,674 @@ +import { Ast } from './parser' +import { + AggregateFunctions, + ContainsNull, + GenericRelationship, + GenericSchema, + GenericTable, + IsNonEmptyArray, + TablesAndViews, + UnionToArray, + GenericFunction, + GenericSetofOption, +} from './types' + +export type IsAny = 0 extends 1 & T ? true : false + +export type SelectQueryError = { error: true } & Message + +/* + ** Because of pg-meta types generation there is some cases where a same relationship can be duplicated + ** if the relation is across schemas and views this ensure that we dedup those relations and treat them + ** as postgrest would. + ** This is no longer the case and has been patched here: https://github.com/supabase/postgres-meta/pull/809 + ** But we still need this for retro-compatibilty with older generated types + ** TODO: Remove this in next major version + */ +export type DeduplicateRelationships = T extends readonly [ + infer First, + ...infer Rest, +] + ? First extends Rest[number] + ? DeduplicateRelationships + : [First, ...DeduplicateRelationships] + : T + +export type GetFieldNodeResultName = Field['alias'] extends string + ? Field['alias'] + : Field['aggregateFunction'] extends AggregateFunctions + ? Field['aggregateFunction'] + : Field['name'] + +type FilterRelationNodes = UnionToArray< + { + [K in keyof Nodes]: Nodes[K] extends Ast.SpreadNode + ? Nodes[K]['target'] + : Nodes[K] extends Ast.FieldNode + ? IsNonEmptyArray extends true + ? Nodes[K] + : never + : never + }[number] +> + +type ResolveRelationships< + Schema extends GenericSchema, + RelationName extends string, + Relationships extends GenericRelationship[], + Nodes extends Ast.FieldNode[], +> = UnionToArray<{ + [K in keyof Nodes]: Nodes[K] extends Ast.FieldNode + ? ResolveRelationship extends infer Relation + ? Relation extends { + relation: { + referencedRelation: string + foreignKeyName: string + match: string + } + from: string + } + ? { + referencedTable: Relation['relation']['referencedRelation'] + fkName: Relation['relation']['foreignKeyName'] + from: Relation['from'] + match: Relation['relation']['match'] + fieldName: GetFieldNodeResultName + } + : Relation + : never + : never +}>[0] + +/** + * Checks if a relation is implicitly referenced twice, requiring disambiguation + */ +type IsDoubleReference = T extends { + referencedTable: infer RT + fieldName: infer FN + match: infer M +} + ? M extends 'col' | 'refrel' + ? U extends { referencedTable: RT; fieldName: FN; match: M } + ? true + : false + : false + : false + +/** + * Compares one element with all other elements in the array to find duplicates + */ +type CheckDuplicates = Arr extends [infer Head, ...infer Tail] + ? IsDoubleReference extends true + ? Head | CheckDuplicates // Return the Head if duplicate + : CheckDuplicates // Otherwise, continue checking + : never + +/** + * Iterates over the elements of the array to find duplicates + */ +type FindDuplicatesWithinDeduplicated = Arr extends [infer Head, ...infer Tail] + ? CheckDuplicates | FindDuplicatesWithinDeduplicated + : never + +type FindDuplicates = FindDuplicatesWithinDeduplicated< + DeduplicateRelationships +> + +export type CheckDuplicateEmbededReference< + Schema extends GenericSchema, + RelationName extends string, + Relationships extends GenericRelationship[], + Nodes extends Ast.Node[], +> = + FilterRelationNodes extends infer RelationsNodes + ? RelationsNodes extends Ast.FieldNode[] + ? ResolveRelationships< + Schema, + RelationName, + Relationships, + RelationsNodes + > extends infer ResolvedRels + ? ResolvedRels extends unknown[] + ? FindDuplicates extends infer Duplicates + ? Duplicates extends never + ? false + : Duplicates extends { fieldName: infer FieldName } + ? FieldName extends string + ? { + [K in FieldName]: SelectQueryError<`table "${RelationName}" specified more than once use hinting for desambiguation`> + } + : false + : false + : false + : false + : false + : false + : false + +/** + * Returns a boolean representing whether there is a foreign key referencing + * a given relation. + */ +type HasFKeyToFRel = Relationships extends [infer R] + ? R extends { referencedRelation: FRelName } + ? true + : false + : Relationships extends [infer R, ...infer Rest] + ? HasFKeyToFRel extends true + ? true + : HasFKeyToFRel + : false +/** + * Checks if there is more than one relation to a given foreign relation name in the Relationships. + */ +type HasMultipleFKeysToFRelDeduplicated = Relationships extends [ + infer R, + ...infer Rest, +] + ? R extends { referencedRelation: FRelName } + ? HasFKeyToFRel extends true + ? true + : HasMultipleFKeysToFRelDeduplicated + : HasMultipleFKeysToFRelDeduplicated + : false + +type HasMultipleFKeysToFRel< + FRelName, + Relationships extends unknown[], +> = HasMultipleFKeysToFRelDeduplicated> + +type CheckRelationshipError< + Schema extends GenericSchema, + Relationships extends GenericRelationship[], + CurrentTableOrView extends keyof TablesAndViews & string, + FoundRelation, +> = + FoundRelation extends SelectQueryError + ? FoundRelation + : // If the relation is a reverse relation with no hint (matching by name) + FoundRelation extends { + relation: { + referencedRelation: infer RelatedRelationName + name: string + } + direction: 'reverse' + } + ? RelatedRelationName extends string + ? // We check if there is possible confusion with other relations with this table + HasMultipleFKeysToFRel extends true + ? // If there is, postgrest will fail at runtime, and require desambiguation via hinting + SelectQueryError<`Could not embed because more than one relationship was found for '${RelatedRelationName}' and '${CurrentTableOrView}' you need to hint the column with ${RelatedRelationName}! ?`> + : FoundRelation + : never + : // Same check for forward relationships, but we must gather the relationships from the found relation + FoundRelation extends { + relation: { + referencedRelation: infer RelatedRelationName + name: string + } + direction: 'forward' + from: infer From + } + ? RelatedRelationName extends string + ? From extends keyof TablesAndViews & string + ? HasMultipleFKeysToFRel< + RelatedRelationName, + TablesAndViews[From]['Relationships'] + > extends true + ? SelectQueryError<`Could not embed because more than one relationship was found for '${From}' and '${RelatedRelationName}' you need to hint the column with ${From}! ?`> + : FoundRelation + : never + : never + : FoundRelation +/** + * Resolves relationships for embedded resources and retrieves the referenced Table + */ +export type ResolveRelationship< + Schema extends GenericSchema, + Relationships extends GenericRelationship[], + Field extends Ast.FieldNode, + CurrentTableOrView extends keyof TablesAndViews & string, +> = + ResolveReverseRelationship< + Schema, + Relationships, + Field, + CurrentTableOrView + > extends infer ReverseRelationship + ? ReverseRelationship extends false + ? CheckRelationshipError< + Schema, + Relationships, + CurrentTableOrView, + ResolveForwardRelationship + > + : CheckRelationshipError + : never + +/** + * Resolves reverse relationships (from children to parent) + */ +type ResolveReverseRelationship< + Schema extends GenericSchema, + Relationships extends GenericRelationship[], + Field extends Ast.FieldNode, + CurrentTableOrView extends keyof TablesAndViews & string, +> = + FindFieldMatchingRelationships extends infer FoundRelation + ? FoundRelation extends never + ? false + : FoundRelation extends { referencedRelation: infer RelatedRelationName } + ? RelatedRelationName extends string + ? RelatedRelationName extends keyof TablesAndViews + ? // If the relation was found via hinting we just return it without any more checks + FoundRelation extends { hint: string } + ? { + referencedTable: TablesAndViews[RelatedRelationName] + relation: FoundRelation + direction: 'reverse' + from: CurrentTableOrView + } + : // If the relation was found via implicit relation naming, we must ensure there is no conflicting matches + HasMultipleFKeysToFRel extends true + ? SelectQueryError<`Could not embed because more than one relationship was found for '${RelatedRelationName}' and '${CurrentTableOrView}' you need to hint the column with ${RelatedRelationName}! ?`> + : { + referencedTable: TablesAndViews[RelatedRelationName] + relation: FoundRelation + direction: 'reverse' + from: CurrentTableOrView + } + : SelectQueryError<`Relation '${RelatedRelationName}' not found in schema.`> + : false + : false + : false + +export type FindMatchingTableRelationships< + Schema extends GenericSchema, + Relationships extends GenericRelationship[], + value extends string, +> = Relationships extends [infer R, ...infer Rest] + ? Rest extends GenericRelationship[] + ? R extends { referencedRelation: infer ReferencedRelation } + ? ReferencedRelation extends keyof Schema['Tables'] + ? R extends { foreignKeyName: value } + ? R & { match: 'fkname' } + : R extends { referencedRelation: value } + ? R & { match: 'refrel' } + : R extends { columns: [value] } + ? R & { match: 'col' } + : FindMatchingTableRelationships + : FindMatchingTableRelationships + : false + : false + : false + +export type FindMatchingViewRelationships< + Schema extends GenericSchema, + Relationships extends GenericRelationship[], + value extends string, +> = Relationships extends [infer R, ...infer Rest] + ? Rest extends GenericRelationship[] + ? R extends { referencedRelation: infer ReferencedRelation } + ? ReferencedRelation extends keyof Schema['Views'] + ? R extends { foreignKeyName: value } + ? R & { match: 'fkname' } + : R extends { referencedRelation: value } + ? R & { match: 'refrel' } + : R extends { columns: [value] } + ? R & { match: 'col' } + : FindMatchingViewRelationships + : FindMatchingViewRelationships + : false + : false + : false + +export type FindMatchingHintTableRelationships< + Schema extends GenericSchema, + Relationships extends GenericRelationship[], + hint extends string, + name extends string, +> = Relationships extends [infer R, ...infer Rest] + ? Rest extends GenericRelationship[] + ? R extends { referencedRelation: infer ReferencedRelation } + ? ReferencedRelation extends name + ? R extends { foreignKeyName: hint } + ? R & { match: 'fkname' } + : R extends { referencedRelation: hint } + ? R & { match: 'refrel' } + : R extends { columns: [hint] } + ? R & { match: 'col' } + : FindMatchingHintTableRelationships + : FindMatchingHintTableRelationships + : false + : false + : false +export type FindMatchingHintViewRelationships< + Schema extends GenericSchema, + Relationships extends GenericRelationship[], + hint extends string, + name extends string, +> = Relationships extends [infer R, ...infer Rest] + ? Rest extends GenericRelationship[] + ? R extends { referencedRelation: infer ReferencedRelation } + ? ReferencedRelation extends name + ? R extends { foreignKeyName: hint } + ? R & { match: 'fkname' } + : R extends { referencedRelation: hint } + ? R & { match: 'refrel' } + : R extends { columns: [hint] } + ? R & { match: 'col' } + : FindMatchingHintViewRelationships + : FindMatchingHintViewRelationships + : false + : false + : false + +type IsColumnsNullable< + Table extends Pick, + Columns extends (keyof Table['Row'])[], +> = Columns extends [infer Column, ...infer Rest] + ? Column extends keyof Table['Row'] + ? ContainsNull extends true + ? true + : IsColumnsNullable + : false + : false + +// Check weither or not a 1-1 relation is nullable by checking against the type of the columns +export type IsRelationNullable< + Table extends GenericTable, + Relation extends GenericRelationship, +> = IsColumnsNullable + +type TableForwardRelationships< + Schema extends GenericSchema, + TName, +> = TName extends keyof TablesAndViews + ? UnionToArray< + RecursivelyFindRelationships> + > extends infer R + ? R extends (GenericRelationship & { from: keyof TablesAndViews })[] + ? R + : [] + : [] + : [] + +type RecursivelyFindRelationships< + Schema extends GenericSchema, + TName, + Keys extends keyof TablesAndViews, +> = Keys extends infer K + ? K extends keyof TablesAndViews + ? FilterRelationships[K]['Relationships'], TName, K> extends never + ? RecursivelyFindRelationships> + : + | FilterRelationships[K]['Relationships'], TName, K> + | RecursivelyFindRelationships> + : false + : false + +type FilterRelationships = R extends readonly (infer Rel)[] + ? Rel extends { referencedRelation: TName } + ? Rel & { from: From } + : never + : never + +export type ResolveForwardRelationship< + Schema extends GenericSchema, + Field extends Ast.FieldNode, + CurrentTableOrView extends keyof TablesAndViews & string, +> = + FindFieldMatchingRelationships< + Schema, + TablesAndViews[Field['name']]['Relationships'], + Ast.FieldNode & { name: CurrentTableOrView; hint: Field['hint'] } + > extends infer FoundByName + ? FoundByName extends GenericRelationship + ? { + referencedTable: TablesAndViews[Field['name']] + relation: FoundByName + direction: 'forward' + from: Field['name'] + type: 'found-by-name' + } + : FindFieldMatchingRelationships< + Schema, + TableForwardRelationships, + Field + > extends infer FoundByMatch + ? FoundByMatch extends GenericRelationship & { + from: keyof TablesAndViews + } + ? { + referencedTable: TablesAndViews[FoundByMatch['from']] + relation: FoundByMatch + direction: 'forward' + from: CurrentTableOrView + type: 'found-by-match' + } + : FindJoinTableRelationship< + Schema, + CurrentTableOrView, + Field['name'] + > extends infer FoundByJoinTable + ? FoundByJoinTable extends GenericRelationship + ? { + referencedTable: TablesAndViews[FoundByJoinTable['referencedRelation']] + relation: FoundByJoinTable & { match: 'refrel' } + direction: 'forward' + from: CurrentTableOrView + type: 'found-by-join-table' + } + : ResolveEmbededFunctionJoinTableRelationship< + Schema, + CurrentTableOrView, + Field['name'] + > extends infer FoundEmbededFunctionJoinTableRelation + ? FoundEmbededFunctionJoinTableRelation extends GenericSetofOption + ? { + referencedTable: TablesAndViews[FoundEmbededFunctionJoinTableRelation['to']] + relation: { + foreignKeyName: `${Field['name']}_${CurrentTableOrView}_${FoundEmbededFunctionJoinTableRelation['to']}_forward` + columns: [] + isOneToOne: FoundEmbededFunctionJoinTableRelation['isOneToOne'] extends true + ? true + : false + referencedColumns: [] + referencedRelation: FoundEmbededFunctionJoinTableRelation['to'] + } & { + match: 'func' + isNotNullable: FoundEmbededFunctionJoinTableRelation['isNotNullable'] extends true + ? true + : FoundEmbededFunctionJoinTableRelation['isSetofReturn'] extends true + ? false + : true + isSetofReturn: FoundEmbededFunctionJoinTableRelation['isSetofReturn'] + } + direction: 'forward' + from: CurrentTableOrView + type: 'found-by-embeded-function' + } + : SelectQueryError<`could not find the relation between ${CurrentTableOrView} and ${Field['name']}`> + : SelectQueryError<`could not find the relation between ${CurrentTableOrView} and ${Field['name']}`> + : SelectQueryError<`could not find the relation between ${CurrentTableOrView} and ${Field['name']}`> + : SelectQueryError<`could not find the relation between ${CurrentTableOrView} and ${Field['name']}`> + : SelectQueryError<`could not find the relation between ${CurrentTableOrView} and ${Field['name']}`> + +/** + * Given a CurrentTableOrView, finds all join tables to this relation. + * For example, if products and categories are linked via product_categories table: + * + * @example + * Given: + * - CurrentTableView = 'products' + * - FieldName = "categories" + * + * It should return this relationship from product_categories: + * { + * foreignKeyName: "product_categories_category_id_fkey", + * columns: ["category_id"], + * isOneToOne: false, + * referencedRelation: "categories", + * referencedColumns: ["id"] + * } + */ +type ResolveJoinTableRelationship< + Schema extends GenericSchema, + CurrentTableOrView extends keyof TablesAndViews & string, + FieldName extends string, +> = { + [TableName in keyof TablesAndViews]: DeduplicateRelationships< + TablesAndViews[TableName]['Relationships'] + > extends readonly (infer Rel)[] + ? Rel extends { referencedRelation: CurrentTableOrView } + ? DeduplicateRelationships< + TablesAndViews[TableName]['Relationships'] + > extends readonly (infer OtherRel)[] + ? OtherRel extends { referencedRelation: FieldName } + ? OtherRel + : never + : never + : never + : never +}[keyof TablesAndViews] + +type ResolveEmbededFunctionJoinTableRelationship< + Schema extends GenericSchema, + CurrentTableOrView extends keyof TablesAndViews & string, + FieldName extends string, +> = + FindMatchingFunctionBySetofFrom< + Schema['Functions'][FieldName], + CurrentTableOrView + > extends infer Fn + ? Fn extends GenericFunction + ? Fn['SetofOptions'] + : false + : false + +export type FindJoinTableRelationship< + Schema extends GenericSchema, + CurrentTableOrView extends keyof TablesAndViews & string, + FieldName extends string, +> = + ResolveJoinTableRelationship extends infer Result + ? [Result] extends [never] + ? false + : Result + : never +/** + * Finds a matching relationship based on the FieldNode's name and optional hint. + */ +export type FindFieldMatchingRelationships< + Schema extends GenericSchema, + Relationships extends GenericRelationship[], + Field extends Ast.FieldNode, +> = Field extends { hint: string } + ? FindMatchingHintTableRelationships< + Schema, + Relationships, + Field['hint'], + Field['name'] + > extends GenericRelationship + ? FindMatchingHintTableRelationships & { + branch: 'found-in-table-via-hint' + hint: Field['hint'] + } + : FindMatchingHintViewRelationships< + Schema, + Relationships, + Field['hint'], + Field['name'] + > extends GenericRelationship + ? FindMatchingHintViewRelationships & { + branch: 'found-in-view-via-hint' + hint: Field['hint'] + } + : SelectQueryError<'Failed to find matching relation via hint'> + : FindMatchingTableRelationships extends GenericRelationship + ? FindMatchingTableRelationships & { + branch: 'found-in-table-via-name' + name: Field['name'] + } + : FindMatchingViewRelationships< + Schema, + Relationships, + Field['name'] + > extends GenericRelationship + ? FindMatchingViewRelationships & { + branch: 'found-in-view-via-name' + name: Field['name'] + } + : SelectQueryError<'Failed to find matching relation via name'> + +export type JsonPathToAccessor = Path extends `${infer P1}->${infer P2}` + ? P2 extends `>${infer Rest}` // Handle ->> operator + ? JsonPathToAccessor<`${P1}.${Rest}`> + : P2 extends string // Handle -> operator + ? JsonPathToAccessor<`${P1}.${P2}`> + : Path + : Path extends `>${infer Rest}` // Clean up any remaining > characters + ? JsonPathToAccessor + : Path extends `${infer P1}::${infer _}` // Handle type casting + ? JsonPathToAccessor + : Path extends `${infer P1}${')' | ','}${infer _}` // Handle closing parenthesis and comma + ? P1 + : Path + +export type JsonPathToType = Path extends '' + ? T + : ContainsNull extends true + ? JsonPathToType, Path> + : Path extends `${infer Key}.${infer Rest}` + ? Key extends keyof T + ? JsonPathToType + : never + : Path extends keyof T + ? T[Path] + : never + +export type IsStringUnion = string extends T + ? false + : T extends string + ? [T] extends [never] + ? false + : true + : false + +type MatchingFunctionBySetofFrom< + Fn extends GenericFunction, + TableName extends string, +> = Fn['SetofOptions'] extends GenericSetofOption + ? TableName extends Fn['SetofOptions']['from'] + ? Fn + : never + : false + +type FindMatchingFunctionBySetofFrom< + FnUnion, + TableName extends string, +> = FnUnion extends infer Fn extends GenericFunction + ? MatchingFunctionBySetofFrom + : false + +type ComputedField< + Schema extends GenericSchema, + RelationName extends keyof TablesAndViews, + FieldName extends keyof TablesAndViews[RelationName]['Row'], +> = FieldName extends keyof Schema['Functions'] + ? Schema['Functions'][FieldName] extends { + Args: { '': TablesAndViews[RelationName]['Row'] } + Returns: any + } + ? FieldName + : never + : never + +// Given a relation name (Table or View) extract all the "computed fields" based on the Row +// object, and the schema functions definitions +export type GetComputedFields< + Schema extends GenericSchema, + RelationName extends keyof TablesAndViews, +> = { + [K in keyof TablesAndViews[RelationName]['Row']]: ComputedField +}[keyof TablesAndViews[RelationName]['Row']] diff --git a/backend/node_modules/@supabase/postgrest-js/src/types/common/common.ts b/backend/node_modules/@supabase/postgrest-js/src/types/common/common.ts new file mode 100644 index 0000000..9ad962e --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/src/types/common/common.ts @@ -0,0 +1,56 @@ +// Types that are shared between supabase-js and postgrest-js + +export type Fetch = typeof fetch + +export type GenericRelationship = { + foreignKeyName: string + columns: string[] + isOneToOne?: boolean + referencedRelation: string + referencedColumns: string[] +} + +export type GenericTable = { + Row: Record + Insert: Record + Update: Record + Relationships: GenericRelationship[] +} + +export type GenericUpdatableView = { + Row: Record + Insert: Record + Update: Record + Relationships: GenericRelationship[] +} + +export type GenericNonUpdatableView = { + Row: Record + Relationships: GenericRelationship[] +} + +export type GenericView = GenericUpdatableView | GenericNonUpdatableView + +export type GenericSetofOption = { + isSetofReturn?: boolean | undefined + isOneToOne?: boolean | undefined + isNotNullable?: boolean | undefined + to: string + from: string +} + +export type GenericFunction = { + Args: Record | never + Returns: unknown + SetofOptions?: GenericSetofOption +} + +export type GenericSchema = { + Tables: Record + Views: Record + Functions: Record +} + +export type ClientServerOptions = { + PostgrestVersion?: string +} diff --git a/backend/node_modules/@supabase/postgrest-js/src/types/common/rpc.ts b/backend/node_modules/@supabase/postgrest-js/src/types/common/rpc.ts new file mode 100644 index 0000000..f9b7892 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/src/types/common/rpc.ts @@ -0,0 +1,148 @@ +import type { GenericFunction, GenericSchema, GenericSetofOption } from './common' + +// Functions matching utils +type IsMatchingArgs< + FnArgs extends GenericFunction['Args'], + PassedArgs extends GenericFunction['Args'], +> = [FnArgs] extends [Record] + ? PassedArgs extends Record + ? true + : false + : keyof PassedArgs extends keyof FnArgs + ? PassedArgs extends FnArgs + ? true + : false + : false + +type MatchingFunctionArgs< + Fn extends GenericFunction, + Args extends GenericFunction['Args'], +> = Fn extends { Args: infer A extends GenericFunction['Args'] } + ? IsMatchingArgs extends true + ? Fn + : never + : false + +type FindMatchingFunctionByArgs< + FnUnion, + Args extends GenericFunction['Args'], +> = FnUnion extends infer Fn extends GenericFunction ? MatchingFunctionArgs : false + +// Types for working with database schemas +type TablesAndViews = Schema['Tables'] & Exclude + +// Utility types for working with unions +type UnionToIntersection = (U extends any ? (k: U) => void : never) extends (k: infer I) => void + ? I + : never + +type LastOf = + UnionToIntersection T : never> extends () => infer R ? R : never + +type IsAny = 0 extends 1 & T ? true : false + +type ExactMatch = [T] extends [S] ? ([S] extends [T] ? true : false) : false + +type ExtractExactFunction = Fns extends infer F + ? F extends GenericFunction + ? ExactMatch extends true + ? F + : never + : never + : never + +type IsNever = [T] extends [never] ? true : false + +type RpcFunctionNotFound = { + Row: any + Result: { + error: true + } & "Couldn't infer function definition matching provided arguments" + RelationName: FnName + Relationships: null +} + +type CrossSchemaError = { + error: true +} & `Function returns SETOF from a different schema ('${TableRef}'). Use .overrideTypes() to specify the return type explicitly.` + +export type GetRpcFunctionFilterBuilderByArgs< + Schema extends GenericSchema, + FnName extends string & keyof Schema['Functions'], + Args, +> = { + 0: Schema['Functions'][FnName] + // If the Args is exactly never (function call without any params) + 1: IsAny extends true + ? any + : IsNever extends true + ? // This is for retro compatibility, if the funcition is defined with an single return and an union of Args + // we fallback to the last function definition matched by name + IsNever> extends true + ? LastOf + : ExtractExactFunction + : Args extends Record + ? LastOf + : // Otherwise, we attempt to match with one of the function definition in the union based + // on the function arguments provided + Args extends GenericFunction['Args'] + ? // This is for retro compatibility, if the funcition is defined with an single return and an union of Args + // we fallback to the last function definition matched by name + IsNever< + LastOf> + > extends true + ? LastOf + : // Otherwise, we use the arguments based function definition narrowing to get the right value + LastOf> + : // If we can't find a matching function by args, we try to find one by function name + ExtractExactFunction extends GenericFunction + ? ExtractExactFunction + : any +}[1] extends infer Fn + ? // If we are dealing with an non-typed client everything is any + IsAny extends true + ? { Row: any; Result: any; RelationName: FnName; Relationships: null } + : // Otherwise, we use the arguments based function definition narrowing to get the right value + Fn extends GenericFunction + ? { + Row: Fn['SetofOptions'] extends GenericSetofOption + ? Fn['SetofOptions']['to'] extends keyof TablesAndViews + ? TablesAndViews[Fn['SetofOptions']['to']]['Row'] + : // Cross-schema fallback: use Returns type when table is not in current schema + Fn['Returns'] extends any[] + ? Fn['Returns'][number] extends Record + ? Fn['Returns'][number] + : CrossSchemaError + : Fn['Returns'] extends Record + ? Fn['Returns'] + : CrossSchemaError + : Fn['Returns'] extends any[] + ? Fn['Returns'][number] extends Record + ? Fn['Returns'][number] + : never + : Fn['Returns'] extends Record + ? Fn['Returns'] + : never + Result: Fn['SetofOptions'] extends GenericSetofOption + ? Fn['SetofOptions']['isSetofReturn'] extends true + ? Fn['SetofOptions']['isOneToOne'] extends true + ? Fn['Returns'][] + : Fn['Returns'] + : Fn['Returns'] + : Fn['Returns'] + RelationName: Fn['SetofOptions'] extends GenericSetofOption + ? Fn['SetofOptions']['to'] + : FnName + Relationships: Fn['SetofOptions'] extends GenericSetofOption + ? Fn['SetofOptions']['to'] extends keyof Schema['Tables'] + ? Schema['Tables'][Fn['SetofOptions']['to']]['Relationships'] + : Fn['SetofOptions']['to'] extends keyof Schema['Views'] + ? Schema['Views'][Fn['SetofOptions']['to']]['Relationships'] + : null + : null + } + : // If we failed to find the function by argument, we still pass with any but also add an overridable + Fn extends false + ? RpcFunctionNotFound + : RpcFunctionNotFound + : RpcFunctionNotFound diff --git a/backend/node_modules/@supabase/postgrest-js/src/types/feature-flags.ts b/backend/node_modules/@supabase/postgrest-js/src/types/feature-flags.ts new file mode 100644 index 0000000..5f5ea06 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/src/types/feature-flags.ts @@ -0,0 +1,17 @@ +type IsPostgrest13 = + PostgrestVersion extends `13${string}` ? true : false +type IsPostgrest14 = + PostgrestVersion extends `14${string}` ? true : false + +type IsPostgrestVersionGreaterThan12 = + IsPostgrest13 extends true + ? true + : IsPostgrest14 extends true + ? true + : false + +export type MaxAffectedEnabled = + IsPostgrestVersionGreaterThan12 extends true ? true : false + +export type SpreadOnManyEnabled = + IsPostgrestVersionGreaterThan12 extends true ? true : false diff --git a/backend/node_modules/@supabase/postgrest-js/src/types/types.ts b/backend/node_modules/@supabase/postgrest-js/src/types/types.ts new file mode 100644 index 0000000..29e5454 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/src/types/types.ts @@ -0,0 +1,153 @@ +import PostgrestError from '../PostgrestError' +import { ContainsNull } from '../select-query-parser/types' +import { SelectQueryError } from '../select-query-parser/utils' +import { ClientServerOptions } from './common/common' + +/** + * Response format + * + * {@link https://github.com/supabase/supabase-js/issues/32} + */ +interface PostgrestResponseBase { + status: number + statusText: string +} +export interface PostgrestResponseSuccess extends PostgrestResponseBase { + error: null + data: T + count: number | null +} +export interface PostgrestResponseFailure extends PostgrestResponseBase { + error: PostgrestError + data: null + count: null +} + +// TODO: in v3: +// - remove PostgrestResponse and PostgrestMaybeSingleResponse +// - rename PostgrestSingleResponse to PostgrestResponse +export type PostgrestSingleResponse = PostgrestResponseSuccess | PostgrestResponseFailure +export type PostgrestMaybeSingleResponse = PostgrestSingleResponse +export type PostgrestResponse = PostgrestSingleResponse + +export type DatabaseWithOptions = { + db: Database + options: Options +} + +// https://twitter.com/mattpocockuk/status/1622730173446557697 +export type Prettify = { [K in keyof T]: T[K] } & {} + +// https://github.com/sindresorhus/type-fest +export type SimplifyDeep = ConditionalSimplifyDeep< + Type, + ExcludeType | NonRecursiveType | Set | Map, + object +> +type ConditionalSimplifyDeep< + Type, + ExcludeType = never, + IncludeType = unknown, +> = Type extends ExcludeType + ? Type + : Type extends IncludeType + ? { [TypeKey in keyof Type]: ConditionalSimplifyDeep } + : Type +type NonRecursiveType = BuiltIns | Function | (new (...arguments_: any[]) => unknown) +type BuiltIns = Primitive | void | Date | RegExp +type Primitive = null | undefined | string | number | boolean | symbol | bigint + +export type IsValidResultOverride = + Result extends any[] + ? NewResult extends any[] + ? // Both are arrays - valid + true + : ErrorResult + : NewResult extends any[] + ? ErrorNewResult + : // Neither are arrays - valid + true +/** + * Utility type to check if array types match between Result and NewResult. + * Returns either the valid NewResult type or an error message type. + */ +export type CheckMatchingArrayTypes = + // If the result is a QueryError we allow the user to override anyway + Result extends SelectQueryError + ? NewResult + : IsValidResultOverride< + Result, + NewResult, + { + Error: 'Type mismatch: Cannot cast array result to a single object. Use .overrideTypes> or .returns> (deprecated) for array results or .single() to convert the result to a single object' + }, + { + Error: 'Type mismatch: Cannot cast single object to array type. Remove Array wrapper from return type or make sure you are not using .single() up in the calling chain' + } + > extends infer ValidationResult + ? ValidationResult extends true + ? // Preserve the optionality of the result if the overriden type is an object (case of chaining with `maybeSingle`) + ContainsNull extends true + ? NewResult | null + : NewResult + : // contains the error + ValidationResult + : never + +type Simplify = T extends object ? { [K in keyof T]: T[K] } : T + +// Extract only explicit (non-index-signature) keys. +type ExplicitKeys = { + [K in keyof T]: string extends K ? never : K +}[keyof T] + +type MergeExplicit = { + // We merge all the explicit keys which allows merge and override of types like + // { [key: string]: unknown } and { someSpecificKey: boolean } + [K in ExplicitKeys | ExplicitKeys]: K extends keyof New + ? K extends keyof Row + ? Row[K] extends SelectQueryError + ? New[K] + : // Check if the override is on a embedded relation (array) + New[K] extends any[] + ? Row[K] extends any[] + ? Array, NonNullable>>> + : New[K] + : // Check if both properties are objects omitting a potential null union + IsPlainObject> extends true + ? IsPlainObject> extends true + ? // If they are, use the new override as source of truth for the optionality + ContainsNull extends true + ? // If the override wants to preserve optionality + Simplify, NonNullable>> | null + : // If the override wants to enforce non-null result + Simplify>> + : New[K] // Override with New type if Row isn't an object + : New[K] // Override primitives with New type + : New[K] // Add new properties from New + : K extends keyof Row + ? Row[K] // Keep existing properties not in New + : never +} + +type MergeDeep = Simplify< + MergeExplicit & + // Intersection here is to restore dynamic keys into the merging result + // eg: + // {[key: number]: string} + // or Record + (string extends keyof Row ? { [K: string]: Row[string] } : {}) +> + +// Helper to check if a type is a plain object (not an array) +type IsPlainObject = T extends any[] ? false : T extends object ? true : false + +// Merge the new result with the original (Result) when merge option is true. +// If NewResult is an array, merge each element. +export type MergePartialResult = Options extends { merge: true } + ? Result extends any[] + ? NewResult extends any[] + ? Array>> + : never + : Simplify> + : NewResult diff --git a/backend/node_modules/@supabase/postgrest-js/src/version.ts b/backend/node_modules/@supabase/postgrest-js/src/version.ts new file mode 100644 index 0000000..57a6913 --- /dev/null +++ b/backend/node_modules/@supabase/postgrest-js/src/version.ts @@ -0,0 +1,7 @@ +// Generated automatically during releases by scripts/update-version-files.ts +// This file provides runtime access to the package version for: +// - HTTP request headers (e.g., X-Client-Info header for API requests) +// - Debugging and support (identifying which version is running) +// - Telemetry and logging (version reporting in errors/analytics) +// - Ensuring build artifacts match the published package version +export const version = '2.87.1' diff --git a/backend/node_modules/@supabase/realtime-js/README.md b/backend/node_modules/@supabase/realtime-js/README.md new file mode 100644 index 0000000..386264a --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/README.md @@ -0,0 +1,326 @@ +
+

+ + + + + Supabase Logo + + + +

Supabase Realtime JS SDK

+ +

Send ephemeral messages with Broadcast, track and synchronize state with Presence, and listen to database changes with Postgres Change Data Capture (CDC).

+ +

+ Guides + · + Reference Docs + · + Multiplayer Demo +

+

+ +
+ +[![Build](https://github.com/supabase/supabase-js/workflows/CI/badge.svg)](https://github.com/supabase/supabase-js/actions?query=branch%3Amaster) +[![Package](https://img.shields.io/npm/v/@supabase/realtime-js)](https://www.npmjs.com/package/@supabase/realtime-js) +[![License: MIT](https://img.shields.io/npm/l/@supabase/supabase-js)](#license) +[![pkg.pr.new](https://pkg.pr.new/badge/supabase/realtime-js)](https://pkg.pr.new/~/supabase/realtime-js) + +
+ +# Overview + +This SDK enables you to use the following Supabase Realtime's features: + +- **Broadcast**: send ephemeral messages from client to clients with minimal latency. Use cases include sharing cursor positions between users. +- **Presence**: track and synchronize shared state across clients with the help of CRDTs. Use cases include tracking which users are currently viewing a specific webpage. +- **Postgres Change Data Capture (CDC)**: listen for changes in your PostgreSQL database and send them to clients. + +# Usage + +## Installing the Package + +```bash +npm install @supabase/realtime-js +``` + +## Creating a Channel + +```js +import { RealtimeClient } from '@supabase/realtime-js' + +const client = new RealtimeClient(REALTIME_URL, { + params: { + apikey: API_KEY, + }, +}) + +const channel = client.channel('test-channel', {}) + +channel.subscribe((status, err) => { + if (status === 'SUBSCRIBED') { + console.log('Connected!') + } + + if (status === 'CHANNEL_ERROR') { + console.log(`There was an error subscribing to channel: ${err.message}`) + } + + if (status === 'TIMED_OUT') { + console.log('Realtime server did not respond in time.') + } + + if (status === 'CLOSED') { + console.log('Realtime channel was unexpectedly closed.') + } +}) +``` + +### Notes: + +- `REALTIME_URL` is `'ws://localhost:4000/socket'` when developing locally and `'wss://.supabase.co/realtime/v1'` when connecting to your Supabase project. +- `API_KEY` is a JWT whose claims must contain `exp` and `role` (existing database role). +- Channel name can be any `string`. +- Setting `private` to `true` means that the client will use RLS to determine if the user can connect or not to a given channel. + +## Broadcast + +Your client can send and receive messages based on the `event`. + +```js +// Setup... + +const channel = client.channel('broadcast-test', { broadcast: { ack: false, self: false } }) + +channel.on('broadcast', { event: 'some-event' }, (payload) => console.log(payload)) + +channel.subscribe(async (status) => { + if (status === 'SUBSCRIBED') { + // Send message to other clients listening to 'broadcast-test' channel + await channel.send({ + type: 'broadcast', + event: 'some-event', + payload: { hello: 'world' }, + }) + } +}) +``` + +### Notes: + +- Setting `ack` to `true` means that the `channel.send` promise will resolve once server replies with acknowledgment that it received the broadcast message request. +- Setting `self` to `true` means that the client will receive the broadcast message it sent out. + +### Broadcast Replay + +Broadcast Replay enables **private** channels to access messages that were sent earlier. Only messages published via [Broadcast From the Database](https://supabase.com/docs/guides/realtime/broadcast#trigger-broadcast-messages-from-your-database) are available for replay. + +You can configure replay with the following options: + +- **`since`** (Required): The epoch timestamp in milliseconds, specifying the earliest point from which messages should be retrieved. +- **`limit`** (Optional): The number of messages to return. This must be a positive integer, with a maximum value of 25. + +Example: + +```typescript +const twelveHours = 12 * 60 * 60 * 1000 +const twelveHoursAgo = Date.now() - twelveHours + +const config = { private: true, broadcast: { replay: { since: twelveHoursAgo, limit: 10 } } } + +supabase + .channel('main:room', { config }) + .on('broadcast', { event: 'my_event' }, (payload) => { + if (payload?.meta?.replayed) { + console.log('This message was sent earlier:', payload) + } else { + console.log('This is a new message', payload) + } + // ... + }) + .subscribe() +``` + +## Presence + +Your client can track and sync state that's stored in the channel. + +```js +// Setup... + +const channel = client.channel('presence-test', { + config: { + presence: { + key: '', + }, + }, +}) + +channel.on('presence', { event: 'sync' }, () => { + console.log('Online users: ', channel.presenceState()) +}) + +channel.on('presence', { event: 'join' }, ({ newPresences }) => { + console.log('New users have joined: ', newPresences) +}) + +channel.on('presence', { event: 'leave' }, ({ leftPresences }) => { + console.log('Users have left: ', leftPresences) +}) + +channel.subscribe(async (status) => { + if (status === 'SUBSCRIBED') { + const status = await channel.track({ user_id: 1 }) + console.log(status) + } +}) +``` + +## Postgres CDC + +Receive database changes on the client. + +```js +// Setup... + +const channel = client.channel('db-changes') + +channel.on('postgres_changes', { event: '*', schema: 'public' }, (payload) => { + console.log('All changes in public schema: ', payload) +}) + +channel.on( + 'postgres_changes', + { event: 'INSERT', schema: 'public', table: 'messages' }, + (payload) => { + console.log('All inserts in messages table: ', payload) + } +) + +channel.on( + 'postgres_changes', + { event: 'UPDATE', schema: 'public', table: 'users', filter: 'username=eq.Realtime' }, + (payload) => { + console.log('All updates on users table when username is Realtime: ', payload) + } +) + +channel.subscribe(async (status) => { + if (status === 'SUBSCRIBED') { + console.log('Ready to receive database changes!') + } +}) +``` + +## Get All Channels + +You can see all the channels that your client has instantiatied. + +```js +// Setup... + +client.getChannels() +``` + +## Cleanup + +It is highly recommended that you clean up your channels after you're done with them. + +- Remove a single channel + +```js +// Setup... + +const channel = client.channel('some-channel-to-remove') + +channel.unsubscribe() +client.removeChannel(channel) +``` + +- Remove all channels and close the connection + +```js +// Setup... + +client.removeAllChannels() +client.disconnect() +``` + +## Development + +This package is part of the [Supabase JavaScript monorepo](https://github.com/supabase/supabase-js). To work on this package: + +### Building + +```bash +# Complete build (from monorepo root) +npx nx build realtime-js + +# Build with watch mode for development +npx nx build realtime-js --watch + +# Individual build targets +npx nx build:main realtime-js # CommonJS build (dist/main/) +npx nx build:module realtime-js # ES Modules build (dist/module/) + +# Other useful commands +npx nx clean realtime-js # Clean build artifacts +npx nx lint realtime-js # Run ESLint +npx nx typecheck realtime-js # TypeScript type checking +``` + +#### Build Outputs + +- **CommonJS (`dist/main/`)** - For Node.js environments +- **ES Modules (`dist/module/`)** - For modern bundlers (Webpack, Vite, Rollup) +- **TypeScript definitions (`dist/module/index.d.ts`)** - Type definitions for TypeScript projects + +Note: Unlike some other packages, realtime-js doesn't include a UMD build since it's primarily used in Node.js or bundled applications. + +#### Validating Package Exports + +```bash +# Check if package exports are correctly configured +npx nx check-exports realtime-js +``` + +This command uses ["Are the types wrong?"](https://github.com/arethetypeswrong/arethetypeswrong.github.io) to verify that the package exports work correctly in different environments. Run this before publishing to ensure your package can be imported correctly by all consumers. + +### Testing + +**No Docker or Supabase instance required!** The realtime-js tests use mocked WebSocket connections, so they're completely self-contained. + +```bash +# Run unit tests (from monorepo root) +npx nx test realtime-js + +# Run tests with coverage report +npx nx test:coverage realtime-js + +# Run tests in watch mode during development +npx nx test:watch realtime-js +``` + +#### Test Scripts Explained + +- **test** - Runs all unit tests once using Vitest +- **test:coverage** - Runs tests and generates coverage report with terminal output +- **test:watch** - Runs tests in interactive watch mode for development + +The tests mock WebSocket connections using `mock-socket`, so you can run them anytime without any external dependencies. + +### Contributing + +We welcome contributions! Please see our [Contributing Guide](../../../CONTRIBUTING.md) for details on how to get started. + +For major changes or if you're unsure about something, please open an issue first to discuss your proposed changes. + +## Credits + +This repo draws heavily from [phoenix-js](https://github.com/phoenixframework/phoenix/tree/master/assets/js/phoenix). + +## License + +MIT. diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/RealtimeChannel.d.ts b/backend/node_modules/@supabase/realtime-js/dist/main/RealtimeChannel.d.ts new file mode 100644 index 0000000..f3ddaf7 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/RealtimeChannel.d.ts @@ -0,0 +1,367 @@ +import { CHANNEL_STATES } from './lib/constants'; +import Push from './lib/push'; +import type RealtimeClient from './RealtimeClient'; +import Timer from './lib/timer'; +import RealtimePresence, { REALTIME_PRESENCE_LISTEN_EVENTS } from './RealtimePresence'; +import type { RealtimePresenceJoinPayload, RealtimePresenceLeavePayload, RealtimePresenceState } from './RealtimePresence'; +type ReplayOption = { + since: number; + limit?: number; +}; +export type RealtimeChannelOptions = { + config: { + /** + * self option enables client to receive message it broadcast + * ack option instructs server to acknowledge that broadcast message was received + * replay option instructs server to replay broadcast messages + */ + broadcast?: { + self?: boolean; + ack?: boolean; + replay?: ReplayOption; + }; + /** + * key option is used to track presence payload across clients + */ + presence?: { + key?: string; + enabled?: boolean; + }; + /** + * defines if the channel is private or not and if RLS policies will be used to check data + */ + private?: boolean; + }; +}; +type RealtimeChangesPayloadBase = { + schema: string; + table: string; +}; +type RealtimeBroadcastChangesPayloadBase = RealtimeChangesPayloadBase & { + id: string; +}; +export type RealtimeBroadcastInsertPayload = RealtimeBroadcastChangesPayloadBase & { + operation: `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.INSERT}`; + record: T; + old_record: null; +}; +export type RealtimeBroadcastUpdatePayload = RealtimeBroadcastChangesPayloadBase & { + operation: `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.UPDATE}`; + record: T; + old_record: T; +}; +export type RealtimeBroadcastDeletePayload = RealtimeBroadcastChangesPayloadBase & { + operation: `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE}`; + record: null; + old_record: T; +}; +export type RealtimeBroadcastPayload = RealtimeBroadcastInsertPayload | RealtimeBroadcastUpdatePayload | RealtimeBroadcastDeletePayload; +type RealtimePostgresChangesPayloadBase = { + schema: string; + table: string; + commit_timestamp: string; + errors: string[]; +}; +export type RealtimePostgresInsertPayload = RealtimePostgresChangesPayloadBase & { + eventType: `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.INSERT}`; + new: T; + old: {}; +}; +export type RealtimePostgresUpdatePayload = RealtimePostgresChangesPayloadBase & { + eventType: `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.UPDATE}`; + new: T; + old: Partial; +}; +export type RealtimePostgresDeletePayload = RealtimePostgresChangesPayloadBase & { + eventType: `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE}`; + new: {}; + old: Partial; +}; +export type RealtimePostgresChangesPayload = RealtimePostgresInsertPayload | RealtimePostgresUpdatePayload | RealtimePostgresDeletePayload; +export type RealtimePostgresChangesFilter = { + /** + * The type of database change to listen to. + */ + event: T; + /** + * The database schema to listen to. + */ + schema: string; + /** + * The database table to listen to. + */ + table?: string; + /** + * Receive database changes when filter is matched. + */ + filter?: string; +}; +export type RealtimeChannelSendResponse = 'ok' | 'timed out' | 'error'; +export declare enum REALTIME_POSTGRES_CHANGES_LISTEN_EVENT { + ALL = "*", + INSERT = "INSERT", + UPDATE = "UPDATE", + DELETE = "DELETE" +} +export declare enum REALTIME_LISTEN_TYPES { + BROADCAST = "broadcast", + PRESENCE = "presence", + POSTGRES_CHANGES = "postgres_changes", + SYSTEM = "system" +} +export declare enum REALTIME_SUBSCRIBE_STATES { + SUBSCRIBED = "SUBSCRIBED", + TIMED_OUT = "TIMED_OUT", + CLOSED = "CLOSED", + CHANNEL_ERROR = "CHANNEL_ERROR" +} +export declare const REALTIME_CHANNEL_STATES: typeof CHANNEL_STATES; +/** A channel is the basic building block of Realtime + * and narrows the scope of data flow to subscribed clients. + * You can think of a channel as a chatroom where participants are able to see who's online + * and send and receive messages. + */ +export default class RealtimeChannel { + /** Topic name can be any string. */ + topic: string; + params: RealtimeChannelOptions; + socket: RealtimeClient; + bindings: { + [key: string]: { + type: string; + filter: { + [key: string]: any; + }; + callback: Function; + id?: string; + }[]; + }; + timeout: number; + state: CHANNEL_STATES; + joinedOnce: boolean; + joinPush: Push; + rejoinTimer: Timer; + pushBuffer: Push[]; + presence: RealtimePresence; + broadcastEndpointURL: string; + subTopic: string; + private: boolean; + /** + * Creates a channel that can broadcast messages, sync presence, and listen to Postgres changes. + * + * The topic determines which realtime stream you are subscribing to. Config options let you + * enable acknowledgement for broadcasts, presence tracking, or private channels. + * + * @example + * ```ts + * import RealtimeClient from '@supabase/realtime-js' + * + * const client = new RealtimeClient('https://xyzcompany.supabase.co/realtime/v1', { + * params: { apikey: 'public-anon-key' }, + * }) + * const channel = new RealtimeChannel('realtime:public:messages', { config: {} }, client) + * ``` + */ + constructor( + /** Topic name can be any string. */ + topic: string, params: RealtimeChannelOptions | undefined, socket: RealtimeClient); + /** Subscribe registers your client with the server */ + subscribe(callback?: (status: REALTIME_SUBSCRIBE_STATES, err?: Error) => void, timeout?: number): RealtimeChannel; + /** + * Returns the current presence state for this channel. + * + * The shape is a map keyed by presence key (for example a user id) where each entry contains the + * tracked metadata for that user. + */ + presenceState(): RealtimePresenceState; + /** + * Sends the supplied payload to the presence tracker so other subscribers can see that this + * client is online. Use `untrack` to stop broadcasting presence for the same key. + */ + track(payload: { + [key: string]: any; + }, opts?: { + [key: string]: any; + }): Promise; + /** + * Removes the current presence state for this client. + */ + untrack(opts?: { + [key: string]: any; + }): Promise; + /** + * Creates an event handler that listens to changes. + */ + on(type: `${REALTIME_LISTEN_TYPES.PRESENCE}`, filter: { + event: `${REALTIME_PRESENCE_LISTEN_EVENTS.SYNC}`; + }, callback: () => void): RealtimeChannel; + on(type: `${REALTIME_LISTEN_TYPES.PRESENCE}`, filter: { + event: `${REALTIME_PRESENCE_LISTEN_EVENTS.JOIN}`; + }, callback: (payload: RealtimePresenceJoinPayload) => void): RealtimeChannel; + on(type: `${REALTIME_LISTEN_TYPES.PRESENCE}`, filter: { + event: `${REALTIME_PRESENCE_LISTEN_EVENTS.LEAVE}`; + }, callback: (payload: RealtimePresenceLeavePayload) => void): RealtimeChannel; + on(type: `${REALTIME_LISTEN_TYPES.POSTGRES_CHANGES}`, filter: RealtimePostgresChangesFilter<`${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.ALL}`>, callback: (payload: RealtimePostgresChangesPayload) => void): RealtimeChannel; + on(type: `${REALTIME_LISTEN_TYPES.POSTGRES_CHANGES}`, filter: RealtimePostgresChangesFilter<`${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.INSERT}`>, callback: (payload: RealtimePostgresInsertPayload) => void): RealtimeChannel; + on(type: `${REALTIME_LISTEN_TYPES.POSTGRES_CHANGES}`, filter: RealtimePostgresChangesFilter<`${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.UPDATE}`>, callback: (payload: RealtimePostgresUpdatePayload) => void): RealtimeChannel; + on(type: `${REALTIME_LISTEN_TYPES.POSTGRES_CHANGES}`, filter: RealtimePostgresChangesFilter<`${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE}`>, callback: (payload: RealtimePostgresDeletePayload) => void): RealtimeChannel; + /** + * The following is placed here to display on supabase.com/docs/reference/javascript/subscribe. + * @param type One of "broadcast", "presence", or "postgres_changes". + * @param filter Custom object specific to the Realtime feature detailing which payloads to receive. + * @param callback Function to be invoked when event handler is triggered. + */ + on(type: `${REALTIME_LISTEN_TYPES.BROADCAST}`, filter: { + event: string; + }, callback: (payload: { + type: `${REALTIME_LISTEN_TYPES.BROADCAST}`; + event: string; + meta?: { + replayed?: boolean; + id: string; + }; + [key: string]: any; + }) => void): RealtimeChannel; + on(type: `${REALTIME_LISTEN_TYPES.BROADCAST}`, filter: { + event: string; + }, callback: (payload: { + type: `${REALTIME_LISTEN_TYPES.BROADCAST}`; + event: string; + meta?: { + replayed?: boolean; + id: string; + }; + payload: T; + }) => void): RealtimeChannel; + on>(type: `${REALTIME_LISTEN_TYPES.BROADCAST}`, filter: { + event: REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.ALL; + }, callback: (payload: { + type: `${REALTIME_LISTEN_TYPES.BROADCAST}`; + event: REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.ALL; + payload: RealtimeBroadcastPayload; + }) => void): RealtimeChannel; + on(type: `${REALTIME_LISTEN_TYPES.BROADCAST}`, filter: { + event: REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.INSERT; + }, callback: (payload: { + type: `${REALTIME_LISTEN_TYPES.BROADCAST}`; + event: REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.INSERT; + payload: RealtimeBroadcastInsertPayload; + }) => void): RealtimeChannel; + on(type: `${REALTIME_LISTEN_TYPES.BROADCAST}`, filter: { + event: REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.UPDATE; + }, callback: (payload: { + type: `${REALTIME_LISTEN_TYPES.BROADCAST}`; + event: REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.UPDATE; + payload: RealtimeBroadcastUpdatePayload; + }) => void): RealtimeChannel; + on(type: `${REALTIME_LISTEN_TYPES.BROADCAST}`, filter: { + event: REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE; + }, callback: (payload: { + type: `${REALTIME_LISTEN_TYPES.BROADCAST}`; + event: REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE; + payload: RealtimeBroadcastDeletePayload; + }) => void): RealtimeChannel; + on(type: `${REALTIME_LISTEN_TYPES.SYSTEM}`, filter: {}, callback: (payload: any) => void): RealtimeChannel; + /** + * Sends a broadcast message explicitly via REST API. + * + * This method always uses the REST API endpoint regardless of WebSocket connection state. + * Useful when you want to guarantee REST delivery or when gradually migrating from implicit REST fallback. + * + * @param event The name of the broadcast event + * @param payload Payload to be sent (required) + * @param opts Options including timeout + * @returns Promise resolving to object with success status, and error details if failed + */ + httpSend(event: string, payload: any, opts?: { + timeout?: number; + }): Promise<{ + success: true; + } | { + success: false; + status: number; + error: string; + }>; + /** + * Sends a message into the channel. + * + * @param args Arguments to send to channel + * @param args.type The type of event to send + * @param args.event The name of the event being sent + * @param args.payload Payload to be sent + * @param opts Options to be used during the send process + */ + send(args: { + type: 'broadcast' | 'presence' | 'postgres_changes'; + event: string; + payload?: any; + [key: string]: any; + }, opts?: { + [key: string]: any; + }): Promise; + /** + * Updates the payload that will be sent the next time the channel joins (reconnects). + * Useful for rotating access tokens or updating config without re-creating the channel. + */ + updateJoinPayload(payload: { + [key: string]: any; + }): void; + /** + * Leaves the channel. + * + * Unsubscribes from server events, and instructs channel to terminate on server. + * Triggers onClose() hooks. + * + * To receive leave acknowledgements, use the a `receive` hook to bind to the server ack, ie: + * channel.unsubscribe().receive("ok", () => alert("left!") ) + */ + unsubscribe(timeout?: number): Promise<'ok' | 'timed out' | 'error'>; + /** + * Teardown the channel. + * + * Destroys and stops related timers. + */ + teardown(): void; +} +export {}; +//# sourceMappingURL=RealtimeChannel.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/RealtimeChannel.d.ts.map b/backend/node_modules/@supabase/realtime-js/dist/main/RealtimeChannel.d.ts.map new file mode 100644 index 0000000..e613d7b --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/RealtimeChannel.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"RealtimeChannel.d.ts","sourceRoot":"","sources":["../../src/RealtimeChannel.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,cAAc,EAAwB,MAAM,iBAAiB,CAAA;AACtF,OAAO,IAAI,MAAM,YAAY,CAAA;AAC7B,OAAO,KAAK,cAAc,MAAM,kBAAkB,CAAA;AAClD,OAAO,KAAK,MAAM,aAAa,CAAA;AAC/B,OAAO,gBAAgB,EAAE,EAAE,+BAA+B,EAAE,MAAM,oBAAoB,CAAA;AACtF,OAAO,KAAK,EACV,2BAA2B,EAC3B,4BAA4B,EAC5B,qBAAqB,EACtB,MAAM,oBAAoB,CAAA;AAI3B,KAAK,YAAY,GAAG;IAClB,KAAK,EAAE,MAAM,CAAA;IACb,KAAK,CAAC,EAAE,MAAM,CAAA;CACf,CAAA;AAED,MAAM,MAAM,sBAAsB,GAAG;IACnC,MAAM,EAAE;QACN;;;;WAIG;QACH,SAAS,CAAC,EAAE;YAAE,IAAI,CAAC,EAAE,OAAO,CAAC;YAAC,GAAG,CAAC,EAAE,OAAO,CAAC;YAAC,MAAM,CAAC,EAAE,YAAY,CAAA;SAAE,CAAA;QACpE;;WAEG;QACH,QAAQ,CAAC,EAAE;YAAE,GAAG,CAAC,EAAE,MAAM,CAAC;YAAC,OAAO,CAAC,EAAE,OAAO,CAAA;SAAE,CAAA;QAC9C;;WAEG;QACH,OAAO,CAAC,EAAE,OAAO,CAAA;KAClB,CAAA;CACF,CAAA;AAED,KAAK,0BAA0B,GAAG;IAChC,MAAM,EAAE,MAAM,CAAA;IACd,KAAK,EAAE,MAAM,C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M,GAAG,GAAG,CAAA;KAAE,GAAG,IAAI;IAIxD;;;;;;;;OAQG;IACH,WAAW,CAAC,OAAO,SAAe,GAAG,OAAO,CAAC,IAAI,GAAG,WAAW,GAAG,OAAO,CAAC;IAkC1E;;;;OAIG;IACH,QAAQ;CAqST"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/RealtimeChannel.js b/backend/node_modules/@supabase/realtime-js/dist/main/RealtimeChannel.js new file mode 100644 index 0000000..84df0ae --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/RealtimeChannel.js @@ -0,0 +1,644 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.REALTIME_CHANNEL_STATES = exports.REALTIME_SUBSCRIBE_STATES = exports.REALTIME_LISTEN_TYPES = exports.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = void 0; +const tslib_1 = require("tslib"); +const constants_1 = require("./lib/constants"); +const push_1 = tslib_1.__importDefault(require("./lib/push")); +const timer_1 = tslib_1.__importDefault(require("./lib/timer")); +const RealtimePresence_1 = tslib_1.__importDefault(require("./RealtimePresence")); +const Transformers = tslib_1.__importStar(require("./lib/transformers")); +const transformers_1 = require("./lib/transformers"); +var REALTIME_POSTGRES_CHANGES_LISTEN_EVENT; +(function (REALTIME_POSTGRES_CHANGES_LISTEN_EVENT) { + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["ALL"] = "*"; + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["INSERT"] = "INSERT"; + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["UPDATE"] = "UPDATE"; + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["DELETE"] = "DELETE"; +})(REALTIME_POSTGRES_CHANGES_LISTEN_EVENT || (exports.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = {})); +var REALTIME_LISTEN_TYPES; +(function (REALTIME_LISTEN_TYPES) { + REALTIME_LISTEN_TYPES["BROADCAST"] = "broadcast"; + REALTIME_LISTEN_TYPES["PRESENCE"] = "presence"; + REALTIME_LISTEN_TYPES["POSTGRES_CHANGES"] = "postgres_changes"; + REALTIME_LISTEN_TYPES["SYSTEM"] = "system"; +})(REALTIME_LISTEN_TYPES || (exports.REALTIME_LISTEN_TYPES = REALTIME_LISTEN_TYPES = {})); +var REALTIME_SUBSCRIBE_STATES; +(function (REALTIME_SUBSCRIBE_STATES) { + REALTIME_SUBSCRIBE_STATES["SUBSCRIBED"] = "SUBSCRIBED"; + REALTIME_SUBSCRIBE_STATES["TIMED_OUT"] = "TIMED_OUT"; + REALTIME_SUBSCRIBE_STATES["CLOSED"] = "CLOSED"; + REALTIME_SUBSCRIBE_STATES["CHANNEL_ERROR"] = "CHANNEL_ERROR"; +})(REALTIME_SUBSCRIBE_STATES || (exports.REALTIME_SUBSCRIBE_STATES = REALTIME_SUBSCRIBE_STATES = {})); +exports.REALTIME_CHANNEL_STATES = constants_1.CHANNEL_STATES; +/** A channel is the basic building block of Realtime + * and narrows the scope of data flow to subscribed clients. + * You can think of a channel as a chatroom where participants are able to see who's online + * and send and receive messages. + */ +class RealtimeChannel { + /** + * Creates a channel that can broadcast messages, sync presence, and listen to Postgres changes. + * + * The topic determines which realtime stream you are subscribing to. Config options let you + * enable acknowledgement for broadcasts, presence tracking, or private channels. + * + * @example + * ```ts + * import RealtimeClient from '@supabase/realtime-js' + * + * const client = new RealtimeClient('https://xyzcompany.supabase.co/realtime/v1', { + * params: { apikey: 'public-anon-key' }, + * }) + * const channel = new RealtimeChannel('realtime:public:messages', { config: {} }, client) + * ``` + */ + constructor( + /** Topic name can be any string. */ + topic, params = { config: {} }, socket) { + var _a, _b; + this.topic = topic; + this.params = params; + this.socket = socket; + this.bindings = {}; + this.state = constants_1.CHANNEL_STATES.closed; + this.joinedOnce = false; + this.pushBuffer = []; + this.subTopic = topic.replace(/^realtime:/i, ''); + this.params.config = Object.assign({ + broadcast: { ack: false, self: false }, + presence: { key: '', enabled: false }, + private: false, + }, params.config); + this.timeout = this.socket.timeout; + this.joinPush = new push_1.default(this, constants_1.CHANNEL_EVENTS.join, this.params, this.timeout); + this.rejoinTimer = new timer_1.default(() => this._rejoinUntilConnected(), this.socket.reconnectAfterMs); + this.joinPush.receive('ok', () => { + this.state = constants_1.CHANNEL_STATES.joined; + this.rejoinTimer.reset(); + this.pushBuffer.forEach((pushEvent) => pushEvent.send()); + this.pushBuffer = []; + }); + this._onClose(() => { + this.rejoinTimer.reset(); + this.socket.log('channel', `close ${this.topic} ${this._joinRef()}`); + this.state = constants_1.CHANNEL_STATES.closed; + this.socket._remove(this); + }); + this._onError((reason) => { + if (this._isLeaving() || this._isClosed()) { + return; + } + this.socket.log('channel', `error ${this.topic}`, reason); + this.state = constants_1.CHANNEL_STATES.errored; + this.rejoinTimer.scheduleTimeout(); + }); + this.joinPush.receive('timeout', () => { + if (!this._isJoining()) { + return; + } + this.socket.log('channel', `timeout ${this.topic}`, this.joinPush.timeout); + this.state = constants_1.CHANNEL_STATES.errored; + this.rejoinTimer.scheduleTimeout(); + }); + this.joinPush.receive('error', (reason) => { + if (this._isLeaving() || this._isClosed()) { + return; + } + this.socket.log('channel', `error ${this.topic}`, reason); + this.state = constants_1.CHANNEL_STATES.errored; + this.rejoinTimer.scheduleTimeout(); + }); + this._on(constants_1.CHANNEL_EVENTS.reply, {}, (payload, ref) => { + this._trigger(this._replyEventName(ref), payload); + }); + this.presence = new RealtimePresence_1.default(this); + this.broadcastEndpointURL = (0, transformers_1.httpEndpointURL)(this.socket.endPoint); + this.private = this.params.config.private || false; + if (!this.private && ((_b = (_a = this.params.config) === null || _a === void 0 ? void 0 : _a.broadcast) === null || _b === void 0 ? void 0 : _b.replay)) { + throw `tried to use replay on public channel '${this.topic}'. It must be a private channel.`; + } + } + /** Subscribe registers your client with the server */ + subscribe(callback, timeout = this.timeout) { + var _a, _b, _c; + if (!this.socket.isConnected()) { + this.socket.connect(); + } + if (this.state == constants_1.CHANNEL_STATES.closed) { + const { config: { broadcast, presence, private: isPrivate }, } = this.params; + const postgres_changes = (_b = (_a = this.bindings.postgres_changes) === null || _a === void 0 ? void 0 : _a.map((r) => r.filter)) !== null && _b !== void 0 ? _b : []; + const presence_enabled = (!!this.bindings[REALTIME_LISTEN_TYPES.PRESENCE] && + this.bindings[REALTIME_LISTEN_TYPES.PRESENCE].length > 0) || + ((_c = this.params.config.presence) === null || _c === void 0 ? void 0 : _c.enabled) === true; + const accessTokenPayload = {}; + const config = { + broadcast, + presence: Object.assign(Object.assign({}, presence), { enabled: presence_enabled }), + postgres_changes, + private: isPrivate, + }; + if (this.socket.accessTokenValue) { + accessTokenPayload.access_token = this.socket.accessTokenValue; + } + this._onError((e) => callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR, e)); + this._onClose(() => callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.CLOSED)); + this.updateJoinPayload(Object.assign({ config }, accessTokenPayload)); + this.joinedOnce = true; + this._rejoin(timeout); + this.joinPush + .receive('ok', async ({ postgres_changes }) => { + var _a; + // Only refresh auth if using callback-based tokens + if (!this.socket._isManualToken()) { + this.socket.setAuth(); + } + if (postgres_changes === undefined) { + callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.SUBSCRIBED); + return; + } + else { + const clientPostgresBindings = this.bindings.postgres_changes; + const bindingsLen = (_a = clientPostgresBindings === null || clientPostgresBindings === void 0 ? void 0 : clientPostgresBindings.length) !== null && _a !== void 0 ? _a : 0; + const newPostgresBindings = []; + for (let i = 0; i < bindingsLen; i++) { + const clientPostgresBinding = clientPostgresBindings[i]; + const { filter: { event, schema, table, filter }, } = clientPostgresBinding; + const serverPostgresFilter = postgres_changes && postgres_changes[i]; + if (serverPostgresFilter && + serverPostgresFilter.event === event && + RealtimeChannel.isFilterValueEqual(serverPostgresFilter.schema, schema) && + RealtimeChannel.isFilterValueEqual(serverPostgresFilter.table, table) && + RealtimeChannel.isFilterValueEqual(serverPostgresFilter.filter, filter)) { + newPostgresBindings.push(Object.assign(Object.assign({}, clientPostgresBinding), { id: serverPostgresFilter.id })); + } + else { + this.unsubscribe(); + this.state = constants_1.CHANNEL_STATES.errored; + callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR, new Error('mismatch between server and client bindings for postgres changes')); + return; + } + } + this.bindings.postgres_changes = newPostgresBindings; + callback && callback(REALTIME_SUBSCRIBE_STATES.SUBSCRIBED); + return; + } + }) + .receive('error', (error) => { + this.state = constants_1.CHANNEL_STATES.errored; + callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR, new Error(JSON.stringify(Object.values(error).join(', ') || 'error'))); + return; + }) + .receive('timeout', () => { + callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.TIMED_OUT); + return; + }); + } + return this; + } + /** + * Returns the current presence state for this channel. + * + * The shape is a map keyed by presence key (for example a user id) where each entry contains the + * tracked metadata for that user. + */ + presenceState() { + return this.presence.state; + } + /** + * Sends the supplied payload to the presence tracker so other subscribers can see that this + * client is online. Use `untrack` to stop broadcasting presence for the same key. + */ + async track(payload, opts = {}) { + return await this.send({ + type: 'presence', + event: 'track', + payload, + }, opts.timeout || this.timeout); + } + /** + * Removes the current presence state for this client. + */ + async untrack(opts = {}) { + return await this.send({ + type: 'presence', + event: 'untrack', + }, opts); + } + on(type, filter, callback) { + if (this.state === constants_1.CHANNEL_STATES.joined && type === REALTIME_LISTEN_TYPES.PRESENCE) { + this.socket.log('channel', `resubscribe to ${this.topic} due to change in presence callbacks on joined channel`); + this.unsubscribe().then(async () => await this.subscribe()); + } + return this._on(type, filter, callback); + } + /** + * Sends a broadcast message explicitly via REST API. + * + * This method always uses the REST API endpoint regardless of WebSocket connection state. + * Useful when you want to guarantee REST delivery or when gradually migrating from implicit REST fallback. + * + * @param event The name of the broadcast event + * @param payload Payload to be sent (required) + * @param opts Options including timeout + * @returns Promise resolving to object with success status, and error details if failed + */ + async httpSend(event, payload, opts = {}) { + var _a; + const authorization = this.socket.accessTokenValue + ? `Bearer ${this.socket.accessTokenValue}` + : ''; + if (payload === undefined || payload === null) { + return Promise.reject('Payload is required for httpSend()'); + } + const options = { + method: 'POST', + headers: { + Authorization: authorization, + apikey: this.socket.apiKey ? this.socket.apiKey : '', + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + messages: [ + { + topic: this.subTopic, + event, + payload: payload, + private: this.private, + }, + ], + }), + }; + const response = await this._fetchWithTimeout(this.broadcastEndpointURL, options, (_a = opts.timeout) !== null && _a !== void 0 ? _a : this.timeout); + if (response.status === 202) { + return { success: true }; + } + let errorMessage = response.statusText; + try { + const errorBody = await response.json(); + errorMessage = errorBody.error || errorBody.message || errorMessage; + } + catch (_b) { } + return Promise.reject(new Error(errorMessage)); + } + /** + * Sends a message into the channel. + * + * @param args Arguments to send to channel + * @param args.type The type of event to send + * @param args.event The name of the event being sent + * @param args.payload Payload to be sent + * @param opts Options to be used during the send process + */ + async send(args, opts = {}) { + var _a, _b; + if (!this._canPush() && args.type === 'broadcast') { + console.warn('Realtime send() is automatically falling back to REST API. ' + + 'This behavior will be deprecated in the future. ' + + 'Please use httpSend() explicitly for REST delivery.'); + const { event, payload: endpoint_payload } = args; + const authorization = this.socket.accessTokenValue + ? `Bearer ${this.socket.accessTokenValue}` + : ''; + const options = { + method: 'POST', + headers: { + Authorization: authorization, + apikey: this.socket.apiKey ? this.socket.apiKey : '', + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + messages: [ + { + topic: this.subTopic, + event, + payload: endpoint_payload, + private: this.private, + }, + ], + }), + }; + try { + const response = await this._fetchWithTimeout(this.broadcastEndpointURL, options, (_a = opts.timeout) !== null && _a !== void 0 ? _a : this.timeout); + await ((_b = response.body) === null || _b === void 0 ? void 0 : _b.cancel()); + return response.ok ? 'ok' : 'error'; + } + catch (error) { + if (error.name === 'AbortError') { + return 'timed out'; + } + else { + return 'error'; + } + } + } + else { + return new Promise((resolve) => { + var _a, _b, _c; + const push = this._push(args.type, args, opts.timeout || this.timeout); + if (args.type === 'broadcast' && !((_c = (_b = (_a = this.params) === null || _a === void 0 ? void 0 : _a.config) === null || _b === void 0 ? void 0 : _b.broadcast) === null || _c === void 0 ? void 0 : _c.ack)) { + resolve('ok'); + } + push.receive('ok', () => resolve('ok')); + push.receive('error', () => resolve('error')); + push.receive('timeout', () => resolve('timed out')); + }); + } + } + /** + * Updates the payload that will be sent the next time the channel joins (reconnects). + * Useful for rotating access tokens or updating config without re-creating the channel. + */ + updateJoinPayload(payload) { + this.joinPush.updatePayload(payload); + } + /** + * Leaves the channel. + * + * Unsubscribes from server events, and instructs channel to terminate on server. + * Triggers onClose() hooks. + * + * To receive leave acknowledgements, use the a `receive` hook to bind to the server ack, ie: + * channel.unsubscribe().receive("ok", () => alert("left!") ) + */ + unsubscribe(timeout = this.timeout) { + this.state = constants_1.CHANNEL_STATES.leaving; + const onClose = () => { + this.socket.log('channel', `leave ${this.topic}`); + this._trigger(constants_1.CHANNEL_EVENTS.close, 'leave', this._joinRef()); + }; + this.joinPush.destroy(); + let leavePush = null; + return new Promise((resolve) => { + leavePush = new push_1.default(this, constants_1.CHANNEL_EVENTS.leave, {}, timeout); + leavePush + .receive('ok', () => { + onClose(); + resolve('ok'); + }) + .receive('timeout', () => { + onClose(); + resolve('timed out'); + }) + .receive('error', () => { + resolve('error'); + }); + leavePush.send(); + if (!this._canPush()) { + leavePush.trigger('ok', {}); + } + }).finally(() => { + leavePush === null || leavePush === void 0 ? void 0 : leavePush.destroy(); + }); + } + /** + * Teardown the channel. + * + * Destroys and stops related timers. + */ + teardown() { + this.pushBuffer.forEach((push) => push.destroy()); + this.pushBuffer = []; + this.rejoinTimer.reset(); + this.joinPush.destroy(); + this.state = constants_1.CHANNEL_STATES.closed; + this.bindings = {}; + } + /** @internal */ + async _fetchWithTimeout(url, options, timeout) { + const controller = new AbortController(); + const id = setTimeout(() => controller.abort(), timeout); + const response = await this.socket.fetch(url, Object.assign(Object.assign({}, options), { signal: controller.signal })); + clearTimeout(id); + return response; + } + /** @internal */ + _push(event, payload, timeout = this.timeout) { + if (!this.joinedOnce) { + throw `tried to push '${event}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`; + } + let pushEvent = new push_1.default(this, event, payload, timeout); + if (this._canPush()) { + pushEvent.send(); + } + else { + this._addToPushBuffer(pushEvent); + } + return pushEvent; + } + /** @internal */ + _addToPushBuffer(pushEvent) { + pushEvent.startTimeout(); + this.pushBuffer.push(pushEvent); + // Enforce buffer size limit + if (this.pushBuffer.length > constants_1.MAX_PUSH_BUFFER_SIZE) { + const removedPush = this.pushBuffer.shift(); + if (removedPush) { + removedPush.destroy(); + this.socket.log('channel', `discarded push due to buffer overflow: ${removedPush.event}`, removedPush.payload); + } + } + } + /** + * Overridable message hook + * + * Receives all events for specialized message handling before dispatching to the channel callbacks. + * Must return the payload, modified or unmodified. + * + * @internal + */ + _onMessage(_event, payload, _ref) { + return payload; + } + /** @internal */ + _isMember(topic) { + return this.topic === topic; + } + /** @internal */ + _joinRef() { + return this.joinPush.ref; + } + /** @internal */ + _trigger(type, payload, ref) { + var _a, _b; + const typeLower = type.toLocaleLowerCase(); + const { close, error, leave, join } = constants_1.CHANNEL_EVENTS; + const events = [close, error, leave, join]; + if (ref && events.indexOf(typeLower) >= 0 && ref !== this._joinRef()) { + return; + } + let handledPayload = this._onMessage(typeLower, payload, ref); + if (payload && !handledPayload) { + throw 'channel onMessage callbacks must return the payload, modified or unmodified'; + } + if (['insert', 'update', 'delete'].includes(typeLower)) { + (_a = this.bindings.postgres_changes) === null || _a === void 0 ? void 0 : _a.filter((bind) => { + var _a, _b, _c; + return ((_a = bind.filter) === null || _a === void 0 ? void 0 : _a.event) === '*' || ((_c = (_b = bind.filter) === null || _b === void 0 ? void 0 : _b.event) === null || _c === void 0 ? void 0 : _c.toLocaleLowerCase()) === typeLower; + }).map((bind) => bind.callback(handledPayload, ref)); + } + else { + (_b = this.bindings[typeLower]) === null || _b === void 0 ? void 0 : _b.filter((bind) => { + var _a, _b, _c, _d, _e, _f; + if (['broadcast', 'presence', 'postgres_changes'].includes(typeLower)) { + if ('id' in bind) { + const bindId = bind.id; + const bindEvent = (_a = bind.filter) === null || _a === void 0 ? void 0 : _a.event; + return (bindId && + ((_b = payload.ids) === null || _b === void 0 ? void 0 : _b.includes(bindId)) && + (bindEvent === '*' || + (bindEvent === null || bindEvent === void 0 ? void 0 : bindEvent.toLocaleLowerCase()) === ((_c = payload.data) === null || _c === void 0 ? void 0 : _c.type.toLocaleLowerCase()))); + } + else { + const bindEvent = (_e = (_d = bind === null || bind === void 0 ? void 0 : bind.filter) === null || _d === void 0 ? void 0 : _d.event) === null || _e === void 0 ? void 0 : _e.toLocaleLowerCase(); + return bindEvent === '*' || bindEvent === ((_f = payload === null || payload === void 0 ? void 0 : payload.event) === null || _f === void 0 ? void 0 : _f.toLocaleLowerCase()); + } + } + else { + return bind.type.toLocaleLowerCase() === typeLower; + } + }).map((bind) => { + if (typeof handledPayload === 'object' && 'ids' in handledPayload) { + const postgresChanges = handledPayload.data; + const { schema, table, commit_timestamp, type, errors } = postgresChanges; + const enrichedPayload = { + schema: schema, + table: table, + commit_timestamp: commit_timestamp, + eventType: type, + new: {}, + old: {}, + errors: errors, + }; + handledPayload = Object.assign(Object.assign({}, enrichedPayload), this._getPayloadRecords(postgresChanges)); + } + bind.callback(handledPayload, ref); + }); + } + } + /** @internal */ + _isClosed() { + return this.state === constants_1.CHANNEL_STATES.closed; + } + /** @internal */ + _isJoined() { + return this.state === constants_1.CHANNEL_STATES.joined; + } + /** @internal */ + _isJoining() { + return this.state === constants_1.CHANNEL_STATES.joining; + } + /** @internal */ + _isLeaving() { + return this.state === constants_1.CHANNEL_STATES.leaving; + } + /** @internal */ + _replyEventName(ref) { + return `chan_reply_${ref}`; + } + /** @internal */ + _on(type, filter, callback) { + const typeLower = type.toLocaleLowerCase(); + const binding = { + type: typeLower, + filter: filter, + callback: callback, + }; + if (this.bindings[typeLower]) { + this.bindings[typeLower].push(binding); + } + else { + this.bindings[typeLower] = [binding]; + } + return this; + } + /** @internal */ + _off(type, filter) { + const typeLower = type.toLocaleLowerCase(); + if (this.bindings[typeLower]) { + this.bindings[typeLower] = this.bindings[typeLower].filter((bind) => { + var _a; + return !(((_a = bind.type) === null || _a === void 0 ? void 0 : _a.toLocaleLowerCase()) === typeLower && + RealtimeChannel.isEqual(bind.filter, filter)); + }); + } + return this; + } + /** @internal */ + static isEqual(obj1, obj2) { + if (Object.keys(obj1).length !== Object.keys(obj2).length) { + return false; + } + for (const k in obj1) { + if (obj1[k] !== obj2[k]) { + return false; + } + } + return true; + } + /** + * Compares two optional filter values for equality. + * Treats undefined, null, and empty string as equivalent empty values. + * @internal + */ + static isFilterValueEqual(serverValue, clientValue) { + const normalizedServer = serverValue !== null && serverValue !== void 0 ? serverValue : undefined; + const normalizedClient = clientValue !== null && clientValue !== void 0 ? clientValue : undefined; + return normalizedServer === normalizedClient; + } + /** @internal */ + _rejoinUntilConnected() { + this.rejoinTimer.scheduleTimeout(); + if (this.socket.isConnected()) { + this._rejoin(); + } + } + /** + * Registers a callback that will be executed when the channel closes. + * + * @internal + */ + _onClose(callback) { + this._on(constants_1.CHANNEL_EVENTS.close, {}, callback); + } + /** + * Registers a callback that will be executed when the channel encounteres an error. + * + * @internal + */ + _onError(callback) { + this._on(constants_1.CHANNEL_EVENTS.error, {}, (reason) => callback(reason)); + } + /** + * Returns `true` if the socket is connected and the channel has been joined. + * + * @internal + */ + _canPush() { + return this.socket.isConnected() && this._isJoined(); + } + /** @internal */ + _rejoin(timeout = this.timeout) { + if (this._isLeaving()) { + return; + } + this.socket._leaveOpenTopic(this.topic); + this.state = constants_1.CHANNEL_STATES.joining; + this.joinPush.resend(timeout); + } + /** @internal */ + _getPayloadRecords(payload) { + const records = { + new: {}, + old: {}, + }; + if (payload.type === 'INSERT' || payload.type === 'UPDATE') { + records.new = Transformers.convertChangeData(payload.columns, payload.record); + } + if (payload.type === 'UPDATE' || payload.type === 'DELETE') { + records.old = Transformers.convertChangeData(payload.columns, payload.old_record); + } + return records; + } +} +exports.default = RealtimeChannel; +//# sourceMappingURL=RealtimeChannel.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/RealtimeChannel.js.map b/backend/node_modules/@supabase/realtime-js/dist/main/RealtimeChannel.js.map new file mode 100644 index 0000000..9d7ba74 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/RealtimeChannel.js.map @@ -0,0 +1 @@ +{"version":3,"file":"RealtimeChannel.js","sourceRoot":"","sources":["../../src/RealtimeChannel.ts"],"names":[],"mappings":";;;;AAAA,+CAAsF;AACtF,8DAA6B;AAE7B,gEAA+B;AAC/B,kFAAsF;AAMtF,yEAAkD;AAClD,qDAAoD;AAmHpD,IAAY,sCAKX;AALD,WAAY,sCAAsC;IAChD,mDAAS,CAAA;IACT,2DAAiB,CAAA;IACjB,2DAAiB,CAAA;IACjB,2DAAiB,CAAA;AACnB,CAAC,EALW,sCAAsC,sDAAtC,sCAAsC,QAKjD;AAED,IAAY,qBAKX;AALD,WAAY,qBAAqB;IAC/B,gDAAuB,CAAA;IACvB,8CAAqB,CAAA;IACrB,8DAAqC,CAAA;IACrC,0CAAiB,CAAA;AACnB,CAAC,EALW,qBAAqB,qCAArB,qBAAqB,QAKhC;AAED,IAAY,yBAKX;AALD,WAAY,yBAAyB;IACnC,sDAAyB,CAAA;IACzB,oDAAuB,CAAA;IACvB,8CAAiB,CAAA;IACjB,4DAA+B,CAAA;AACjC,CAAC,EALW,yBAAyB,yCAAzB,yBAAyB,QAKpC;AAEY,QAAA,uBAAuB,GAAG,0BAAc,CAAA;AAWrD;;;;GAIG;AACH,MAAqB,eAAe;IAoBlC;;;;;;;;;;;;;;;OAeG;IACH;IACE,oCAAoC;IAC7B,KAAa,EACb,SAAiC,EAAE,MAAM,EAAE,EAAE,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AAK,QAAQ,IAAI,OAAO,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;YAC3D,OAAO,CAAC,GAAG,GAAG,YAAY,CAAC,iBAAiB,CAAC,OAAO,CAAC,OAAO,EAAE,OAAO,CAAC,UAAU,CAAC,CAAA;QACnF,CAAC;QAED,OAAO,OAAO,CAAA;IAChB,CAAC;CACF;AAn2BD,kCAm2BC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/RealtimeClient.d.ts b/backend/node_modules/@supabase/realtime-js/dist/main/RealtimeClient.d.ts new file mode 100644 index 0000000..350459b --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/RealtimeClient.d.ts @@ -0,0 +1,236 @@ +import { WebSocketLike } from './lib/websocket-factory'; +import { CONNECTION_STATE } from './lib/constants'; +import Serializer from './lib/serializer'; +import Timer from './lib/timer'; +import RealtimeChannel from './RealtimeChannel'; +import type { RealtimeChannelOptions } from './RealtimeChannel'; +type Fetch = typeof fetch; +export type Channel = { + name: string; + inserted_at: string; + updated_at: string; + id: number; +}; +export type LogLevel = 'info' | 'warn' | 'error'; +export type RealtimeMessage = { + topic: string; + event: string; + payload: any; + ref: string; + join_ref?: string; +}; +export type RealtimeRemoveChannelResponse = 'ok' | 'timed out' | 'error'; +export type HeartbeatStatus = 'sent' | 'ok' | 'error' | 'timeout' | 'disconnected'; +/** + * Minimal WebSocket constructor interface that RealtimeClient can work with. + * Supply a compatible implementation (native WebSocket, `ws`, etc) when running outside the browser. + */ +export interface WebSocketLikeConstructor { + new (address: string | URL, subprotocols?: string | string[] | undefined): WebSocketLike; + [key: string]: any; +} +export interface WebSocketLikeError { + error: any; + message: string; + type: string; +} +export type RealtimeClientOptions = { + transport?: WebSocketLikeConstructor; + timeout?: number; + heartbeatIntervalMs?: number; + heartbeatCallback?: (status: HeartbeatStatus) => void; + vsn?: string; + logger?: Function; + encode?: Function; + decode?: Function; + reconnectAfterMs?: Function; + headers?: { + [key: string]: string; + }; + params?: { + [key: string]: any; + }; + log_level?: LogLevel; + logLevel?: LogLevel; + fetch?: Fetch; + worker?: boolean; + workerUrl?: string; + accessToken?: () => Promise; +}; +export default class RealtimeClient { + accessTokenValue: string | null; + apiKey: string | null; + private _manuallySetToken; + channels: RealtimeChannel[]; + endPoint: string; + httpEndpoint: string; + /** @deprecated headers cannot be set on websocket connections */ + headers?: { + [key: string]: string; + }; + params?: { + [key: string]: string; + }; + timeout: number; + transport: WebSocketLikeConstructor | null; + heartbeatIntervalMs: number; + heartbeatTimer: ReturnType | undefined; + pendingHeartbeatRef: string | null; + heartbeatCallback: (status: HeartbeatStatus) => void; + ref: number; + reconnectTimer: Timer | null; + vsn: string; + logger: Function; + logLevel?: LogLevel; + encode: Function; + decode: Function; + reconnectAfterMs: Function; + conn: WebSocketLike | null; + sendBuffer: Function[]; + serializer: Serializer; + stateChangeCallbacks: { + open: Function[]; + close: Function[]; + error: Function[]; + message: Function[]; + }; + fetch: Fetch; + accessToken: (() => Promise) | null; + worker?: boolean; + workerUrl?: string; + workerRef?: Worker; + private _connectionState; + private _wasManualDisconnect; + private _authPromise; + /** + * Initializes the Socket. + * + * @param endPoint The string WebSocket endpoint, ie, "ws://example.com/socket", "wss://example.com", "/socket" (inherited host & protocol) + * @param httpEndpoint The string HTTP endpoint, ie, "https://example.com", "/" (inherited host & protocol) + * @param options.transport The Websocket Transport, for example WebSocket. This can be a custom implementation + * @param options.timeout The default timeout in milliseconds to trigger push timeouts. + * @param options.params The optional params to pass when connecting. + * @param options.headers Deprecated: headers cannot be set on websocket connections and this option will be removed in the future. + * @param options.heartbeatIntervalMs The millisec interval to send a heartbeat message. + * @param options.heartbeatCallback The optional function to handle heartbeat status. + * @param options.logger The optional function for specialized logging, ie: logger: (kind, msg, data) => { console.log(`${kind}: ${msg}`, data) } + * @param options.logLevel Sets the log level for Realtime + * @param options.encode The function to encode outgoing messages. Defaults to JSON: (payload, callback) => callback(JSON.stringify(payload)) + * @param options.decode The function to decode incoming messages. Defaults to Serializer's decode. + * @param options.reconnectAfterMs he optional function that returns the millsec reconnect interval. Defaults to stepped backoff off. + * @param options.worker Use Web Worker to set a side flow. Defaults to false. + * @param options.workerUrl The URL of the worker script. Defaults to https://realtime.supabase.com/worker.js that includes a heartbeat event call to keep the connection alive. + * @example + * ```ts + * import RealtimeClient from '@supabase/realtime-js' + * + * const client = new RealtimeClient('https://xyzcompany.supabase.co/realtime/v1', { + * params: { apikey: 'public-anon-key' }, + * }) + * client.connect() + * ``` + */ + constructor(endPoint: string, options?: RealtimeClientOptions); + /** + * Connects the socket, unless already connected. + */ + connect(): void; + /** + * Returns the URL of the websocket. + * @returns string The URL of the websocket. + */ + endpointURL(): string; + /** + * Disconnects the socket. + * + * @param code A numeric status code to send on disconnect. + * @param reason A custom reason for the disconnect. + */ + disconnect(code?: number, reason?: string): void; + /** + * Returns all created channels + */ + getChannels(): RealtimeChannel[]; + /** + * Unsubscribes and removes a single channel + * @param channel A RealtimeChannel instance + */ + removeChannel(channel: RealtimeChannel): Promise; + /** + * Unsubscribes and removes all channels + */ + removeAllChannels(): Promise; + /** + * Logs the message. + * + * For customized logging, `this.logger` can be overridden. + */ + log(kind: string, msg: string, data?: any): void; + /** + * Returns the current state of the socket. + */ + connectionState(): CONNECTION_STATE; + /** + * Returns `true` is the connection is open. + */ + isConnected(): boolean; + /** + * Returns `true` if the connection is currently connecting. + */ + isConnecting(): boolean; + /** + * Returns `true` if the connection is currently disconnecting. + */ + isDisconnecting(): boolean; + /** + * Creates (or reuses) a {@link RealtimeChannel} for the provided topic. + * + * Topics are automatically prefixed with `realtime:` to match the Realtime service. + * If a channel with the same topic already exists it will be returned instead of creating + * a duplicate connection. + */ + channel(topic: string, params?: RealtimeChannelOptions): RealtimeChannel; + /** + * Push out a message if the socket is connected. + * + * If the socket is not connected, the message gets enqueued within a local buffer, and sent out when a connection is next established. + */ + push(data: RealtimeMessage): void; + /** + * Sets the JWT access token used for channel subscription authorization and Realtime RLS. + * + * If param is null it will use the `accessToken` callback function or the token set on the client. + * + * On callback used, it will set the value of the token internal to the client. + * + * When a token is explicitly provided, it will be preserved across channel operations + * (including removeChannel and resubscribe). The `accessToken` callback will not be + * invoked until `setAuth()` is called without arguments. + * + * @param token A JWT string to override the token set on the client. + * + * @example + * // Use a manual token (preserved across resubscribes, ignores accessToken callback) + * client.realtime.setAuth('my-custom-jwt') + * + * // Switch back to using the accessToken callback + * client.realtime.setAuth() + */ + setAuth(token?: string | null): Promise; + /** + * Sends a heartbeat message if the socket is connected. + */ + sendHeartbeat(): Promise; + /** + * Sets a callback that receives lifecycle events for internal heartbeat messages. + * Useful for instrumenting connection health (e.g. sent/ok/timeout/disconnected). + */ + onHeartbeat(callback: (status: HeartbeatStatus) => void): void; + /** + * Flushes send buffer + */ + flushSendBuffer(): void; + private _workerObjectUrl; +} +export {}; +//# sourceMappingURL=RealtimeClient.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/RealtimeClient.d.ts.map b/backend/node_modules/@supabase/realtime-js/dist/main/RealtimeClient.d.ts.map new file mode 100644 index 0000000..9106696 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/RealtimeClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"RealtimeClient.d.ts","sourceRoot":"","sources":["../../src/RealtimeClient.ts"],"names":[],"mappings":"AAAA,OAAyB,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAA;AAEzE,OAAO,EAEL,gBAAgB,EASjB,MAAM,iBAAiB,CAAA;AAExB,OAAO,UAAU,MAAM,kBAAkB,CAAA;AACzC,OAAO,KAAK,MAAM,aAAa,CAAA;AAG/B,OAAO,eAAe,MAAM,mBAAmB,CAAA;AAC/C,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAA;AAE/D,KAAK,KAAK,GAAG,OAAO,KAAK,CAAA;AAEzB,MAAM,MAAM,OAAO,GAAG;IACpB,IAAI,EAAE,MAAM,CAAA;IACZ,WAAW,EA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6B,CAAC;IAUrF;;OAEG;IACG,iBAAiB,IAAI,OAAO,CAAC,6BAA6B,EAAE,CAAC;IAOnE;;;;OAIG;IACH,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,GAAG;IAIzC;;OAEG;IACH,eAAe,IAAI,gBAAgB;IAanC;;OAEG;IACH,WAAW,IAAI,OAAO;IAItB;;OAEG;IACH,YAAY,IAAI,OAAO;IAIvB;;OAEG;IACH,eAAe,IAAI,OAAO;IAI1B;;;;;;OAMG;IACH,OAAO,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,GAAE,sBAAuC,GAAG,eAAe;IAcxF;;;;OAIG;IACH,IAAI,CAAC,IAAI,EAAE,eAAe,GAAG,IAAI;IAejC;;;;;;;;;;;;;;;;;;;OAmBG;IACG,OAAO,CAAC,KAAK,GAAE,MAAM,GAAG,IAAW,GAAG,OAAO,CAAC,IAAI,CAAC;IAkBzD;;OAEG;IACG,aAAa;IAiDnB;;;OAGG;IACH,WAAW,CAAC,QAAQ,EAAE,CAAC,MAAM,EAAE,eAAe,KAAK,IAAI,GAAG,IAAI;IAG9D;;OAEG;IACH,eAAe;IAoQf,OAAO,CAAC,gBAAgB;CAiMzB"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/RealtimeClient.js b/backend/node_modules/@supabase/realtime-js/dist/main/RealtimeClient.js new file mode 100644 index 0000000..bffbad2 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/RealtimeClient.js @@ -0,0 +1,815 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = require("tslib"); +const websocket_factory_1 = tslib_1.__importDefault(require("./lib/websocket-factory")); +const constants_1 = require("./lib/constants"); +const serializer_1 = tslib_1.__importDefault(require("./lib/serializer")); +const timer_1 = tslib_1.__importDefault(require("./lib/timer")); +const transformers_1 = require("./lib/transformers"); +const RealtimeChannel_1 = tslib_1.__importDefault(require("./RealtimeChannel")); +const noop = () => { }; +// Connection-related constants +const CONNECTION_TIMEOUTS = { + HEARTBEAT_INTERVAL: 25000, + RECONNECT_DELAY: 10, + HEARTBEAT_TIMEOUT_FALLBACK: 100, +}; +const RECONNECT_INTERVALS = [1000, 2000, 5000, 10000]; +const DEFAULT_RECONNECT_FALLBACK = 10000; +const WORKER_SCRIPT = ` + addEventListener("message", (e) => { + if (e.data.event === "start") { + setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); + } + });`; +class RealtimeClient { + /** + * Initializes the Socket. + * + * @param endPoint The string WebSocket endpoint, ie, "ws://example.com/socket", "wss://example.com", "/socket" (inherited host & protocol) + * @param httpEndpoint The string HTTP endpoint, ie, "https://example.com", "/" (inherited host & protocol) + * @param options.transport The Websocket Transport, for example WebSocket. This can be a custom implementation + * @param options.timeout The default timeout in milliseconds to trigger push timeouts. + * @param options.params The optional params to pass when connecting. + * @param options.headers Deprecated: headers cannot be set on websocket connections and this option will be removed in the future. + * @param options.heartbeatIntervalMs The millisec interval to send a heartbeat message. + * @param options.heartbeatCallback The optional function to handle heartbeat status. + * @param options.logger The optional function for specialized logging, ie: logger: (kind, msg, data) => { console.log(`${kind}: ${msg}`, data) } + * @param options.logLevel Sets the log level for Realtime + * @param options.encode The function to encode outgoing messages. Defaults to JSON: (payload, callback) => callback(JSON.stringify(payload)) + * @param options.decode The function to decode incoming messages. Defaults to Serializer's decode. + * @param options.reconnectAfterMs he optional function that returns the millsec reconnect interval. Defaults to stepped backoff off. + * @param options.worker Use Web Worker to set a side flow. Defaults to false. + * @param options.workerUrl The URL of the worker script. Defaults to https://realtime.supabase.com/worker.js that includes a heartbeat event call to keep the connection alive. + * @example + * ```ts + * import RealtimeClient from '@supabase/realtime-js' + * + * const client = new RealtimeClient('https://xyzcompany.supabase.co/realtime/v1', { + * params: { apikey: 'public-anon-key' }, + * }) + * client.connect() + * ``` + */ + constructor(endPoint, options) { + var _a; + this.accessTokenValue = null; + this.apiKey = null; + this._manuallySetToken = false; + this.channels = new Array(); + this.endPoint = ''; + this.httpEndpoint = ''; + /** @deprecated headers cannot be set on websocket connections */ + this.headers = {}; + this.params = {}; + this.timeout = constants_1.DEFAULT_TIMEOUT; + this.transport = null; + this.heartbeatIntervalMs = CONNECTION_TIMEOUTS.HEARTBEAT_INTERVAL; + this.heartbeatTimer = undefined; + this.pendingHeartbeatRef = null; + this.heartbeatCallback = noop; + this.ref = 0; + this.reconnectTimer = null; + this.vsn = constants_1.DEFAULT_VSN; + this.logger = noop; + this.conn = null; + this.sendBuffer = []; + this.serializer = new serializer_1.default(); + this.stateChangeCallbacks = { + open: [], + close: [], + error: [], + message: [], + }; + this.accessToken = null; + this._connectionState = 'disconnected'; + this._wasManualDisconnect = false; + this._authPromise = null; + /** + * Use either custom fetch, if provided, or default fetch to make HTTP requests + * + * @internal + */ + this._resolveFetch = (customFetch) => { + if (customFetch) { + return (...args) => customFetch(...args); + } + return (...args) => fetch(...args); + }; + // Validate required parameters + if (!((_a = options === null || options === void 0 ? void 0 : options.params) === null || _a === void 0 ? void 0 : _a.apikey)) { + throw new Error('API key is required to connect to Realtime'); + } + this.apiKey = options.params.apikey; + // Initialize endpoint URLs + this.endPoint = `${endPoint}/${constants_1.TRANSPORTS.websocket}`; + this.httpEndpoint = (0, transformers_1.httpEndpointURL)(endPoint); + this._initializeOptions(options); + this._setupReconnectionTimer(); + this.fetch = this._resolveFetch(options === null || options === void 0 ? void 0 : options.fetch); + } + /** + * Connects the socket, unless already connected. + */ + connect() { + // Skip if already connecting, disconnecting, or connected + if (this.isConnecting() || + this.isDisconnecting() || + (this.conn !== null && this.isConnected())) { + return; + } + this._setConnectionState('connecting'); + // Trigger auth if needed and not already in progress + // This ensures auth is called for standalone RealtimeClient usage + // while avoiding race conditions with SupabaseClient's immediate setAuth call + if (this.accessToken && !this._authPromise) { + this._setAuthSafely('connect'); + } + // Establish WebSocket connection + if (this.transport) { + // Use custom transport if provided + this.conn = new this.transport(this.endpointURL()); + } + else { + // Try to use native WebSocket + try { + this.conn = websocket_factory_1.default.createWebSocket(this.endpointURL()); + } + catch (error) { + this._setConnectionState('disconnected'); + const errorMessage = error.message; + // Provide helpful error message based on environment + if (errorMessage.includes('Node.js')) { + throw new Error(`${errorMessage}\n\n` + + 'To use Realtime in Node.js, you need to provide a WebSocket implementation:\n\n' + + 'Option 1: Use Node.js 22+ which has native WebSocket support\n' + + 'Option 2: Install and provide the "ws" package:\n\n' + + ' npm install ws\n\n' + + ' import ws from "ws"\n' + + ' const client = new RealtimeClient(url, {\n' + + ' ...options,\n' + + ' transport: ws\n' + + ' })'); + } + throw new Error(`WebSocket not available: ${errorMessage}`); + } + } + this._setupConnectionHandlers(); + } + /** + * Returns the URL of the websocket. + * @returns string The URL of the websocket. + */ + endpointURL() { + return this._appendParams(this.endPoint, Object.assign({}, this.params, { vsn: this.vsn })); + } + /** + * Disconnects the socket. + * + * @param code A numeric status code to send on disconnect. + * @param reason A custom reason for the disconnect. + */ + disconnect(code, reason) { + if (this.isDisconnecting()) { + return; + } + this._setConnectionState('disconnecting', true); + if (this.conn) { + // Setup fallback timer to prevent hanging in disconnecting state + const fallbackTimer = setTimeout(() => { + this._setConnectionState('disconnected'); + }, 100); + this.conn.onclose = () => { + clearTimeout(fallbackTimer); + this._setConnectionState('disconnected'); + }; + // Close the WebSocket connection if close method exists + if (typeof this.conn.close === 'function') { + if (code) { + this.conn.close(code, reason !== null && reason !== void 0 ? reason : ''); + } + else { + this.conn.close(); + } + } + this._teardownConnection(); + } + else { + this._setConnectionState('disconnected'); + } + } + /** + * Returns all created channels + */ + getChannels() { + return this.channels; + } + /** + * Unsubscribes and removes a single channel + * @param channel A RealtimeChannel instance + */ + async removeChannel(channel) { + const status = await channel.unsubscribe(); + if (this.channels.length === 0) { + this.disconnect(); + } + return status; + } + /** + * Unsubscribes and removes all channels + */ + async removeAllChannels() { + const values_1 = await Promise.all(this.channels.map((channel) => channel.unsubscribe())); + this.channels = []; + this.disconnect(); + return values_1; + } + /** + * Logs the message. + * + * For customized logging, `this.logger` can be overridden. + */ + log(kind, msg, data) { + this.logger(kind, msg, data); + } + /** + * Returns the current state of the socket. + */ + connectionState() { + switch (this.conn && this.conn.readyState) { + case constants_1.SOCKET_STATES.connecting: + return constants_1.CONNECTION_STATE.Connecting; + case constants_1.SOCKET_STATES.open: + return constants_1.CONNECTION_STATE.Open; + case constants_1.SOCKET_STATES.closing: + return constants_1.CONNECTION_STATE.Closing; + default: + return constants_1.CONNECTION_STATE.Closed; + } + } + /** + * Returns `true` is the connection is open. + */ + isConnected() { + return this.connectionState() === constants_1.CONNECTION_STATE.Open; + } + /** + * Returns `true` if the connection is currently connecting. + */ + isConnecting() { + return this._connectionState === 'connecting'; + } + /** + * Returns `true` if the connection is currently disconnecting. + */ + isDisconnecting() { + return this._connectionState === 'disconnecting'; + } + /** + * Creates (or reuses) a {@link RealtimeChannel} for the provided topic. + * + * Topics are automatically prefixed with `realtime:` to match the Realtime service. + * If a channel with the same topic already exists it will be returned instead of creating + * a duplicate connection. + */ + channel(topic, params = { config: {} }) { + const realtimeTopic = `realtime:${topic}`; + const exists = this.getChannels().find((c) => c.topic === realtimeTopic); + if (!exists) { + const chan = new RealtimeChannel_1.default(`realtime:${topic}`, params, this); + this.channels.push(chan); + return chan; + } + else { + return exists; + } + } + /** + * Push out a message if the socket is connected. + * + * If the socket is not connected, the message gets enqueued within a local buffer, and sent out when a connection is next established. + */ + push(data) { + const { topic, event, payload, ref } = data; + const callback = () => { + this.encode(data, (result) => { + var _a; + (_a = this.conn) === null || _a === void 0 ? void 0 : _a.send(result); + }); + }; + this.log('push', `${topic} ${event} (${ref})`, payload); + if (this.isConnected()) { + callback(); + } + else { + this.sendBuffer.push(callback); + } + } + /** + * Sets the JWT access token used for channel subscription authorization and Realtime RLS. + * + * If param is null it will use the `accessToken` callback function or the token set on the client. + * + * On callback used, it will set the value of the token internal to the client. + * + * When a token is explicitly provided, it will be preserved across channel operations + * (including removeChannel and resubscribe). The `accessToken` callback will not be + * invoked until `setAuth()` is called without arguments. + * + * @param token A JWT string to override the token set on the client. + * + * @example + * // Use a manual token (preserved across resubscribes, ignores accessToken callback) + * client.realtime.setAuth('my-custom-jwt') + * + * // Switch back to using the accessToken callback + * client.realtime.setAuth() + */ + async setAuth(token = null) { + this._authPromise = this._performAuth(token); + try { + await this._authPromise; + } + finally { + this._authPromise = null; + } + } + /** + * Returns true if the current access token was explicitly set via setAuth(token), + * false if it was obtained via the accessToken callback. + * @internal + */ + _isManualToken() { + return this._manuallySetToken; + } + /** + * Sends a heartbeat message if the socket is connected. + */ + async sendHeartbeat() { + var _a; + if (!this.isConnected()) { + try { + this.heartbeatCallback('disconnected'); + } + catch (e) { + this.log('error', 'error in heartbeat callback', e); + } + return; + } + // Handle heartbeat timeout and force reconnection if needed + if (this.pendingHeartbeatRef) { + this.pendingHeartbeatRef = null; + this.log('transport', 'heartbeat timeout. Attempting to re-establish connection'); + try { + this.heartbeatCallback('timeout'); + } + catch (e) { + this.log('error', 'error in heartbeat callback', e); + } + // Force reconnection after heartbeat timeout + this._wasManualDisconnect = false; + (_a = this.conn) === null || _a === void 0 ? void 0 : _a.close(constants_1.WS_CLOSE_NORMAL, 'heartbeat timeout'); + setTimeout(() => { + var _a; + if (!this.isConnected()) { + (_a = this.reconnectTimer) === null || _a === void 0 ? void 0 : _a.scheduleTimeout(); + } + }, CONNECTION_TIMEOUTS.HEARTBEAT_TIMEOUT_FALLBACK); + return; + } + // Send heartbeat message to server + this.pendingHeartbeatRef = this._makeRef(); + this.push({ + topic: 'phoenix', + event: 'heartbeat', + payload: {}, + ref: this.pendingHeartbeatRef, + }); + try { + this.heartbeatCallback('sent'); + } + catch (e) { + this.log('error', 'error in heartbeat callback', e); + } + this._setAuthSafely('heartbeat'); + } + /** + * Sets a callback that receives lifecycle events for internal heartbeat messages. + * Useful for instrumenting connection health (e.g. sent/ok/timeout/disconnected). + */ + onHeartbeat(callback) { + this.heartbeatCallback = callback; + } + /** + * Flushes send buffer + */ + flushSendBuffer() { + if (this.isConnected() && this.sendBuffer.length > 0) { + this.sendBuffer.forEach((callback) => callback()); + this.sendBuffer = []; + } + } + /** + * Return the next message ref, accounting for overflows + * + * @internal + */ + _makeRef() { + let newRef = this.ref + 1; + if (newRef === this.ref) { + this.ref = 0; + } + else { + this.ref = newRef; + } + return this.ref.toString(); + } + /** + * Unsubscribe from channels with the specified topic. + * + * @internal + */ + _leaveOpenTopic(topic) { + let dupChannel = this.channels.find((c) => c.topic === topic && (c._isJoined() || c._isJoining())); + if (dupChannel) { + this.log('transport', `leaving duplicate topic "${topic}"`); + dupChannel.unsubscribe(); + } + } + /** + * Removes a subscription from the socket. + * + * @param channel An open subscription. + * + * @internal + */ + _remove(channel) { + this.channels = this.channels.filter((c) => c.topic !== channel.topic); + } + /** @internal */ + _onConnMessage(rawMessage) { + this.decode(rawMessage.data, (msg) => { + // Handle heartbeat responses + if (msg.topic === 'phoenix' && msg.event === 'phx_reply') { + try { + this.heartbeatCallback(msg.payload.status === 'ok' ? 'ok' : 'error'); + } + catch (e) { + this.log('error', 'error in heartbeat callback', e); + } + } + // Handle pending heartbeat reference cleanup + if (msg.ref && msg.ref === this.pendingHeartbeatRef) { + this.pendingHeartbeatRef = null; + } + // Log incoming message + const { topic, event, payload, ref } = msg; + const refString = ref ? `(${ref})` : ''; + const status = payload.status || ''; + this.log('receive', `${status} ${topic} ${event} ${refString}`.trim(), payload); + // Route message to appropriate channels + this.channels + .filter((channel) => channel._isMember(topic)) + .forEach((channel) => channel._trigger(event, payload, ref)); + this._triggerStateCallbacks('message', msg); + }); + } + /** + * Clear specific timer + * @internal + */ + _clearTimer(timer) { + var _a; + if (timer === 'heartbeat' && this.heartbeatTimer) { + clearInterval(this.heartbeatTimer); + this.heartbeatTimer = undefined; + } + else if (timer === 'reconnect') { + (_a = this.reconnectTimer) === null || _a === void 0 ? void 0 : _a.reset(); + } + } + /** + * Clear all timers + * @internal + */ + _clearAllTimers() { + this._clearTimer('heartbeat'); + this._clearTimer('reconnect'); + } + /** + * Setup connection handlers for WebSocket events + * @internal + */ + _setupConnectionHandlers() { + if (!this.conn) + return; + // Set binary type if supported (browsers and most WebSocket implementations) + if ('binaryType' in this.conn) { + ; + this.conn.binaryType = 'arraybuffer'; + } + this.conn.onopen = () => this._onConnOpen(); + this.conn.onerror = (error) => this._onConnError(error); + this.conn.onmessage = (event) => this._onConnMessage(event); + this.conn.onclose = (event) => this._onConnClose(event); + } + /** + * Teardown connection and cleanup resources + * @internal + */ + _teardownConnection() { + if (this.conn) { + if (this.conn.readyState === constants_1.SOCKET_STATES.open || + this.conn.readyState === constants_1.SOCKET_STATES.connecting) { + try { + this.conn.close(); + } + catch (e) { + this.log('error', 'Error closing connection', e); + } + } + this.conn.onopen = null; + this.conn.onerror = null; + this.conn.onmessage = null; + this.conn.onclose = null; + this.conn = null; + } + this._clearAllTimers(); + this.channels.forEach((channel) => channel.teardown()); + } + /** @internal */ + _onConnOpen() { + this._setConnectionState('connected'); + this.log('transport', `connected to ${this.endpointURL()}`); + // Wait for any pending auth operations before flushing send buffer + // This ensures channel join messages include the correct access token + const authPromise = this._authPromise || + (this.accessToken && !this.accessTokenValue ? this.setAuth() : Promise.resolve()); + authPromise + .then(() => { + this.flushSendBuffer(); + }) + .catch((e) => { + this.log('error', 'error waiting for auth on connect', e); + // Proceed anyway to avoid hanging connections + this.flushSendBuffer(); + }); + this._clearTimer('reconnect'); + if (!this.worker) { + this._startHeartbeat(); + } + else { + if (!this.workerRef) { + this._startWorkerHeartbeat(); + } + } + this._triggerStateCallbacks('open'); + } + /** @internal */ + _startHeartbeat() { + this.heartbeatTimer && clearInterval(this.heartbeatTimer); + this.heartbeatTimer = setInterval(() => this.sendHeartbeat(), this.heartbeatIntervalMs); + } + /** @internal */ + _startWorkerHeartbeat() { + if (this.workerUrl) { + this.log('worker', `starting worker for from ${this.workerUrl}`); + } + else { + this.log('worker', `starting default worker`); + } + const objectUrl = this._workerObjectUrl(this.workerUrl); + this.workerRef = new Worker(objectUrl); + this.workerRef.onerror = (error) => { + this.log('worker', 'worker error', error.message); + this.workerRef.terminate(); + }; + this.workerRef.onmessage = (event) => { + if (event.data.event === 'keepAlive') { + this.sendHeartbeat(); + } + }; + this.workerRef.postMessage({ + event: 'start', + interval: this.heartbeatIntervalMs, + }); + } + /** @internal */ + _onConnClose(event) { + var _a; + this._setConnectionState('disconnected'); + this.log('transport', 'close', event); + this._triggerChanError(); + this._clearTimer('heartbeat'); + // Only schedule reconnection if it wasn't a manual disconnect + if (!this._wasManualDisconnect) { + (_a = this.reconnectTimer) === null || _a === void 0 ? void 0 : _a.scheduleTimeout(); + } + this._triggerStateCallbacks('close', event); + } + /** @internal */ + _onConnError(error) { + this._setConnectionState('disconnected'); + this.log('transport', `${error}`); + this._triggerChanError(); + this._triggerStateCallbacks('error', error); + } + /** @internal */ + _triggerChanError() { + this.channels.forEach((channel) => channel._trigger(constants_1.CHANNEL_EVENTS.error)); + } + /** @internal */ + _appendParams(url, params) { + if (Object.keys(params).length === 0) { + return url; + } + const prefix = url.match(/\?/) ? '&' : '?'; + const query = new URLSearchParams(params); + return `${url}${prefix}${query}`; + } + _workerObjectUrl(url) { + let result_url; + if (url) { + result_url = url; + } + else { + const blob = new Blob([WORKER_SCRIPT], { type: 'application/javascript' }); + result_url = URL.createObjectURL(blob); + } + return result_url; + } + /** + * Set connection state with proper state management + * @internal + */ + _setConnectionState(state, manual = false) { + this._connectionState = state; + if (state === 'connecting') { + this._wasManualDisconnect = false; + } + else if (state === 'disconnecting') { + this._wasManualDisconnect = manual; + } + } + /** + * Perform the actual auth operation + * @internal + */ + async _performAuth(token = null) { + let tokenToSend; + let isManualToken = false; + if (token) { + tokenToSend = token; + // Track if this is a manually-provided token + isManualToken = true; + } + else if (this.accessToken) { + // Call the accessToken callback to get fresh token + try { + tokenToSend = await this.accessToken(); + } + catch (e) { + this.log('error', 'Error fetching access token from callback', e); + // Fall back to cached value if callback fails + tokenToSend = this.accessTokenValue; + } + } + else { + tokenToSend = this.accessTokenValue; + } + // Track whether this token was manually set or fetched via callback + if (isManualToken) { + this._manuallySetToken = true; + } + else if (this.accessToken) { + // If we used the callback, clear the manual flag + this._manuallySetToken = false; + } + if (this.accessTokenValue != tokenToSend) { + this.accessTokenValue = tokenToSend; + this.channels.forEach((channel) => { + const payload = { + access_token: tokenToSend, + version: constants_1.DEFAULT_VERSION, + }; + tokenToSend && channel.updateJoinPayload(payload); + if (channel.joinedOnce && channel._isJoined()) { + channel._push(constants_1.CHANNEL_EVENTS.access_token, { + access_token: tokenToSend, + }); + } + }); + } + } + /** + * Wait for any in-flight auth operations to complete + * @internal + */ + async _waitForAuthIfNeeded() { + if (this._authPromise) { + await this._authPromise; + } + } + /** + * Safely call setAuth with standardized error handling + * @internal + */ + _setAuthSafely(context = 'general') { + // Only refresh auth if using callback-based tokens + if (!this._isManualToken()) { + this.setAuth().catch((e) => { + this.log('error', `Error setting auth in ${context}`, e); + }); + } + } + /** + * Trigger state change callbacks with proper error handling + * @internal + */ + _triggerStateCallbacks(event, data) { + try { + this.stateChangeCallbacks[event].forEach((callback) => { + try { + callback(data); + } + catch (e) { + this.log('error', `error in ${event} callback`, e); + } + }); + } + catch (e) { + this.log('error', `error triggering ${event} callbacks`, e); + } + } + /** + * Setup reconnection timer with proper configuration + * @internal + */ + _setupReconnectionTimer() { + this.reconnectTimer = new timer_1.default(async () => { + setTimeout(async () => { + await this._waitForAuthIfNeeded(); + if (!this.isConnected()) { + this.connect(); + } + }, CONNECTION_TIMEOUTS.RECONNECT_DELAY); + }, this.reconnectAfterMs); + } + /** + * Initialize client options with defaults + * @internal + */ + _initializeOptions(options) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m; + // Set defaults + this.transport = (_a = options === null || options === void 0 ? void 0 : options.transport) !== null && _a !== void 0 ? _a : null; + this.timeout = (_b = options === null || options === void 0 ? void 0 : options.timeout) !== null && _b !== void 0 ? _b : constants_1.DEFAULT_TIMEOUT; + this.heartbeatIntervalMs = + (_c = options === null || options === void 0 ? void 0 : options.heartbeatIntervalMs) !== null && _c !== void 0 ? _c : CONNECTION_TIMEOUTS.HEARTBEAT_INTERVAL; + this.worker = (_d = options === null || options === void 0 ? void 0 : options.worker) !== null && _d !== void 0 ? _d : false; + this.accessToken = (_e = options === null || options === void 0 ? void 0 : options.accessToken) !== null && _e !== void 0 ? _e : null; + this.heartbeatCallback = (_f = options === null || options === void 0 ? void 0 : options.heartbeatCallback) !== null && _f !== void 0 ? _f : noop; + this.vsn = (_g = options === null || options === void 0 ? void 0 : options.vsn) !== null && _g !== void 0 ? _g : constants_1.DEFAULT_VSN; + // Handle special cases + if (options === null || options === void 0 ? void 0 : options.params) + this.params = options.params; + if (options === null || options === void 0 ? void 0 : options.logger) + this.logger = options.logger; + if ((options === null || options === void 0 ? void 0 : options.logLevel) || (options === null || options === void 0 ? void 0 : options.log_level)) { + this.logLevel = options.logLevel || options.log_level; + this.params = Object.assign(Object.assign({}, this.params), { log_level: this.logLevel }); + } + // Set up functions with defaults + this.reconnectAfterMs = + (_h = options === null || options === void 0 ? void 0 : options.reconnectAfterMs) !== null && _h !== void 0 ? _h : ((tries) => { + return RECONNECT_INTERVALS[tries - 1] || DEFAULT_RECONNECT_FALLBACK; + }); + switch (this.vsn) { + case constants_1.VSN_1_0_0: + this.encode = + (_j = options === null || options === void 0 ? void 0 : options.encode) !== null && _j !== void 0 ? _j : ((payload, callback) => { + return callback(JSON.stringify(payload)); + }); + this.decode = + (_k = options === null || options === void 0 ? void 0 : options.decode) !== null && _k !== void 0 ? _k : ((payload, callback) => { + return callback(JSON.parse(payload)); + }); + break; + case constants_1.VSN_2_0_0: + this.encode = (_l = options === null || options === void 0 ? void 0 : options.encode) !== null && _l !== void 0 ? _l : this.serializer.encode.bind(this.serializer); + this.decode = (_m = options === null || options === void 0 ? void 0 : options.decode) !== null && _m !== void 0 ? _m : this.serializer.decode.bind(this.serializer); + break; + default: + throw new Error(`Unsupported serializer version: ${this.vsn}`); + } + // Handle worker setup + if (this.worker) { + if (typeof window !== 'undefined' && !window.Worker) { + throw new Error('Web Worker is not supported'); + } + this.workerUrl = options === null || options === void 0 ? void 0 : options.workerUrl; + } + } +} +exports.default = RealtimeClient; +//# sourceMappingURL=RealtimeClient.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/RealtimeClient.js.map b/backend/node_modules/@supabase/realtime-js/dist/main/RealtimeClient.js.map new file mode 100644 index 0000000..b749da8 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/RealtimeClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"RealtimeClient.js","sourceRoot":"","sources":["../../src/RealtimeClient.ts"],"names":[],"mappings":";;;AAAA,wFAAyE;AAEzE,+CAWwB;AAExB,0EAAyC;AACzC,gEAA+B;AAE/B,qDAAoD;AACpD,gFAA+C;AAwB/C,MAAM,IAAI,GAAG,GAAG,EAAE,GAAE,CAAC,CAAA;AAIrB,+BAA+B;AAC/B,MAAM,mBAAmB,GAAG;IAC1B,kBAAkB,EAAE,KAAK;IACzB,eAAe,EAAE,EAAE;IACnB,0BAA0B,EAAE,GAAG;CACvB,CAAA;AAEV,MAAM,mBAAmB,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,CAAU,CAAA;AAC9D,MAAM,0BAA0B,GAAG,KAAK,CAAA;AAuCxC,MAAM,aAAa,GAAG;;;;;MAKhB,CAAA;AAEN,MAAqB,cAAc;IA+CjC;;;;;;;;;;;;;;;;;;;;;;;;;;;OA2BG;IACH,YAAY,QAAgB,EAAE,OAA+B;;QA1E7D,qBAAgB,GAAkB,IAAI,CAAA;QACtC,WAAM,GAAkB,IAAI,CAAA;QACpB,sBAAiB,GAAY,KAAK,CAAA;QAC1C,aAAQ,GAAsB,IAAI,KAAK,EAAE,CAAA;QACzC,aAAQ,GAAW,EAAE,CAAA;QACrB,iBAAY,GAAW,EAAE,CAAA;QACzB,iEAAiE;QACjE,YAAO,GAA+B,E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ase/realtime-js/dist/main/RealtimePresence.d.ts b/backend/node_modules/@supabase/realtime-js/dist/main/RealtimePresence.d.ts new file mode 100644 index 0000000..583618b --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/RealtimePresence.d.ts @@ -0,0 +1,76 @@ +import type { PresenceOpts, PresenceOnJoinCallback, PresenceOnLeaveCallback } from 'phoenix'; +import type RealtimeChannel from './RealtimeChannel'; +type Presence = { + presence_ref: string; +} & T; +export type RealtimePresenceState = { + [key: string]: Presence[]; +}; +export type RealtimePresenceJoinPayload = { + event: `${REALTIME_PRESENCE_LISTEN_EVENTS.JOIN}`; + key: string; + currentPresences: Presence[]; + newPresences: Presence[]; +}; +export type RealtimePresenceLeavePayload = { + event: `${REALTIME_PRESENCE_LISTEN_EVENTS.LEAVE}`; + key: string; + currentPresences: Presence[]; + leftPresences: Presence[]; +}; +export declare enum REALTIME_PRESENCE_LISTEN_EVENTS { + SYNC = "sync", + JOIN = "join", + LEAVE = "leave" +} +type RawPresenceState = { + [key: string]: { + metas: { + phx_ref?: string; + phx_ref_prev?: string; + [key: string]: any; + }[]; + }; +}; +type RawPresenceDiff = { + joins: RawPresenceState; + leaves: RawPresenceState; +}; +export default class RealtimePresence { + channel: RealtimeChannel; + state: RealtimePresenceState; + pendingDiffs: RawPresenceDiff[]; + joinRef: string | null; + enabled: boolean; + caller: { + onJoin: PresenceOnJoinCallback; + onLeave: PresenceOnLeaveCallback; + onSync: () => void; + }; + /** + * Creates a Presence helper that keeps the local presence state in sync with the server. + * + * @param channel - The realtime channel to bind to. + * @param opts - Optional custom event names, e.g. `{ events: { state: 'state', diff: 'diff' } }`. + * + * @example + * ```ts + * const presence = new RealtimePresence(channel) + * + * channel.on('presence', ({ event, key }) => { + * console.log(`Presence ${event} on ${key}`) + * }) + * ``` + */ + constructor(channel: RealtimeChannel, opts?: PresenceOpts); +} +export {}; +//# sourceMappingURL=RealtimePresence.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/RealtimePresence.d.ts.map b/backend/node_modules/@supabase/realtime-js/dist/main/RealtimePresence.d.ts.map new file mode 100644 index 0000000..93f61dd --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/RealtimePresence.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"RealtimePresence.d.ts","sourceRoot":"","sources":["../../src/RealtimePresence.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,YAAY,EAAE,sBAAsB,EAAE,uBAAuB,EAAE,MAAM,SAAS,CAAA;AAC5F,OAAO,KAAK,eAAe,MAAM,mBAAmB,CAAA;AAEpD,KAAK,QAAQ,CAAC,CAAC,SAAS;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;CAAE,GAAG,EAAE,IAAI;IACrD,YAAY,EAAE,MAAM,CAAA;CACrB,GAAG,CAAC,CAAA;AAEL,MAAM,MAAM,qBAAqB,CAAC,CAAC,SAAS;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;CAAE,GAAG,EAAE,IAAI;IACzE,CAAC,GAAG,EAAE,MAAM,GAAG,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAA;CAC7B,CAAA;AAED,MAAM,MAAM,2BAA2B,CAAC,CAAC,SAAS;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;CAAE,IAAI;IAC1E,KAAK,EAAE,GAAG,+BAA+B,CAAC,IAAI,EAAE,CAAA;IAChD,GAAG,EAAE,MAAM,CAAA;IACX,gBAAgB,EAAE,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAA;IAC/B,YAAY,EAAE,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAA;CAC5B,CAAA;AAED,MAAM,MAAM,4BAA4B,CAAC,CAAC,SAAS;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;CAAE,IAAI;IAC3E,KAAK,EAAE,GAAG,+BAA+B,CAAC,KAAK,EAAE,CAAA;IACjD,GAAG,EAAE,MAAM,CAAA;IACX,gBAAgB,EAAE,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAA;IAC/B,aAAa,EAAE,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAA;CAC7B,CAAA;AAED,oBAAY,+BAA+B;IACzC,IAAI,SAAS;IACb,IAAI,SAAS;IACb,KAAK,UAAU;CAChB;AAOD,KAAK,gBAAgB,GAAG;IACtB,CAAC,GAAG,EAAE,MAAM,GAAG;QACb,KAAK,EAAE;YACL,OAAO,CAAC,EAAE,MAAM,CAAA;YAChB,YAAY,CAAC,EAAE,MAAM,CAAA;YACrB,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;SACnB,EAAE,CAAA;KACJ,CAAA;CACF,CAAA;AAED,KAAK,eAAe,GAAG;IACrB,KAAK,EAAE,gBAAgB,CAAA;IACvB,MAAM,EAAE,gBAAgB,CAAA;CACzB,CAAA;AAID,MAAM,CAAC,OAAO,OAAO,gBAAgB;IA+B1B,OAAO,EAAE,eAAe;IA9BjC,KAAK,EAAE,qBAAqB,CAAK;IACjC,YAAY,EAAE,eAAe,EAAE,CAAK;IACpC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAO;IAC7B,OAAO,EAAE,OAAO,CAAQ;IACxB,MAAM,EAAE;QACN,MAAM,EAAE,sBAAsB,CAAA;QAC9B,OAAO,EAAE,uBAAuB,CAAA;QAChC,MAAM,EAAE,MAAM,IAAI,CAAA;KACnB,CAIA;IAED;;;;;;;;;;;;;;OAcG;gBAEM,OAAO,EAAE,eAAe,EAC/B,IAAI,CAAC,EAAE,YAAY;CA+PtB"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/RealtimePresence.js b/backend/node_modules/@supabase/realtime-js/dist/main/RealtimePresence.js new file mode 100644 index 0000000..7704610 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/RealtimePresence.js @@ -0,0 +1,237 @@ +"use strict"; +/* + This file draws heavily from https://github.com/phoenixframework/phoenix/blob/d344ec0a732ab4ee204215b31de69cf4be72e3bf/assets/js/phoenix/presence.js + License: https://github.com/phoenixframework/phoenix/blob/d344ec0a732ab4ee204215b31de69cf4be72e3bf/LICENSE.md +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.REALTIME_PRESENCE_LISTEN_EVENTS = void 0; +var REALTIME_PRESENCE_LISTEN_EVENTS; +(function (REALTIME_PRESENCE_LISTEN_EVENTS) { + REALTIME_PRESENCE_LISTEN_EVENTS["SYNC"] = "sync"; + REALTIME_PRESENCE_LISTEN_EVENTS["JOIN"] = "join"; + REALTIME_PRESENCE_LISTEN_EVENTS["LEAVE"] = "leave"; +})(REALTIME_PRESENCE_LISTEN_EVENTS || (exports.REALTIME_PRESENCE_LISTEN_EVENTS = REALTIME_PRESENCE_LISTEN_EVENTS = {})); +class RealtimePresence { + /** + * Creates a Presence helper that keeps the local presence state in sync with the server. + * + * @param channel - The realtime channel to bind to. + * @param opts - Optional custom event names, e.g. `{ events: { state: 'state', diff: 'diff' } }`. + * + * @example + * ```ts + * const presence = new RealtimePresence(channel) + * + * channel.on('presence', ({ event, key }) => { + * console.log(`Presence ${event} on ${key}`) + * }) + * ``` + */ + constructor(channel, opts) { + this.channel = channel; + this.state = {}; + this.pendingDiffs = []; + this.joinRef = null; + this.enabled = false; + this.caller = { + onJoin: () => { }, + onLeave: () => { }, + onSync: () => { }, + }; + const events = (opts === null || opts === void 0 ? void 0 : opts.events) || { + state: 'presence_state', + diff: 'presence_diff', + }; + this.channel._on(events.state, {}, (newState) => { + const { onJoin, onLeave, onSync } = this.caller; + this.joinRef = this.channel._joinRef(); + this.state = RealtimePresence.syncState(this.state, newState, onJoin, onLeave); + this.pendingDiffs.forEach((diff) => { + this.state = RealtimePresence.syncDiff(this.state, diff, onJoin, onLeave); + }); + this.pendingDiffs = []; + onSync(); + }); + this.channel._on(events.diff, {}, (diff) => { + const { onJoin, onLeave, onSync } = this.caller; + if (this.inPendingSyncState()) { + this.pendingDiffs.push(diff); + } + else { + this.state = RealtimePresence.syncDiff(this.state, diff, onJoin, onLeave); + onSync(); + } + }); + this.onJoin((key, currentPresences, newPresences) => { + this.channel._trigger('presence', { + event: 'join', + key, + currentPresences, + newPresences, + }); + }); + this.onLeave((key, currentPresences, leftPresences) => { + this.channel._trigger('presence', { + event: 'leave', + key, + currentPresences, + leftPresences, + }); + }); + this.onSync(() => { + this.channel._trigger('presence', { event: 'sync' }); + }); + } + /** + * Used to sync the list of presences on the server with the + * client's state. + * + * An optional `onJoin` and `onLeave` callback can be provided to + * react to changes in the client's local presences across + * disconnects and reconnects with the server. + * + * @internal + */ + static syncState(currentState, newState, onJoin, onLeave) { + const state = this.cloneDeep(currentState); + const transformedState = this.transformState(newState); + const joins = {}; + const leaves = {}; + this.map(state, (key, presences) => { + if (!transformedState[key]) { + leaves[key] = presences; + } + }); + this.map(transformedState, (key, newPresences) => { + const currentPresences = state[key]; + if (currentPresences) { + const newPresenceRefs = newPresences.map((m) => m.presence_ref); + const curPresenceRefs = currentPresences.map((m) => m.presence_ref); + const joinedPresences = newPresences.filter((m) => curPresenceRefs.indexOf(m.presence_ref) < 0); + const leftPresences = currentPresences.filter((m) => newPresenceRefs.indexOf(m.presence_ref) < 0); + if (joinedPresences.length > 0) { + joins[key] = joinedPresences; + } + if (leftPresences.length > 0) { + leaves[key] = leftPresences; + } + } + else { + joins[key] = newPresences; + } + }); + return this.syncDiff(state, { joins, leaves }, onJoin, onLeave); + } + /** + * Used to sync a diff of presence join and leave events from the + * server, as they happen. + * + * Like `syncState`, `syncDiff` accepts optional `onJoin` and + * `onLeave` callbacks to react to a user joining or leaving from a + * device. + * + * @internal + */ + static syncDiff(state, diff, onJoin, onLeave) { + const { joins, leaves } = { + joins: this.transformState(diff.joins), + leaves: this.transformState(diff.leaves), + }; + if (!onJoin) { + onJoin = () => { }; + } + if (!onLeave) { + onLeave = () => { }; + } + this.map(joins, (key, newPresences) => { + var _a; + const currentPresences = (_a = state[key]) !== null && _a !== void 0 ? _a : []; + state[key] = this.cloneDeep(newPresences); + if (currentPresences.length > 0) { + const joinedPresenceRefs = state[key].map((m) => m.presence_ref); + const curPresences = currentPresences.filter((m) => joinedPresenceRefs.indexOf(m.presence_ref) < 0); + state[key].unshift(...curPresences); + } + onJoin(key, currentPresences, newPresences); + }); + this.map(leaves, (key, leftPresences) => { + let currentPresences = state[key]; + if (!currentPresences) + return; + const presenceRefsToRemove = leftPresences.map((m) => m.presence_ref); + currentPresences = currentPresences.filter((m) => presenceRefsToRemove.indexOf(m.presence_ref) < 0); + state[key] = currentPresences; + onLeave(key, currentPresences, leftPresences); + if (currentPresences.length === 0) + delete state[key]; + }); + return state; + } + /** @internal */ + static map(obj, func) { + return Object.getOwnPropertyNames(obj).map((key) => func(key, obj[key])); + } + /** + * Remove 'metas' key + * Change 'phx_ref' to 'presence_ref' + * Remove 'phx_ref' and 'phx_ref_prev' + * + * @example + * // returns { + * abc123: [ + * { presence_ref: '2', user_id: 1 }, + * { presence_ref: '3', user_id: 2 } + * ] + * } + * RealtimePresence.transformState({ + * abc123: { + * metas: [ + * { phx_ref: '2', phx_ref_prev: '1' user_id: 1 }, + * { phx_ref: '3', user_id: 2 } + * ] + * } + * }) + * + * @internal + */ + static transformState(state) { + state = this.cloneDeep(state); + return Object.getOwnPropertyNames(state).reduce((newState, key) => { + const presences = state[key]; + if ('metas' in presences) { + newState[key] = presences.metas.map((presence) => { + presence['presence_ref'] = presence['phx_ref']; + delete presence['phx_ref']; + delete presence['phx_ref_prev']; + return presence; + }); + } + else { + newState[key] = presences; + } + return newState; + }, {}); + } + /** @internal */ + static cloneDeep(obj) { + return JSON.parse(JSON.stringify(obj)); + } + /** @internal */ + onJoin(callback) { + this.caller.onJoin = callback; + } + /** @internal */ + onLeave(callback) { + this.caller.onLeave = callback; + } + /** @internal */ + onSync(callback) { + this.caller.onSync = callback; + } + /** @internal */ + inPendingSyncState() { + return !this.joinRef || this.joinRef !== this.channel._joinRef(); + } +} +exports.default = RealtimePresence; +//# sourceMappingURL=RealtimePresence.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/RealtimePresence.js.map b/backend/node_modules/@supabase/realtime-js/dist/main/RealtimePresence.js.map new file mode 100644 index 0000000..cae9876 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/RealtimePresence.js.map @@ -0,0 +1 @@ +{"version":3,"file":"RealtimePresence.js","sourceRoot":"","sources":["../../src/RealtimePresence.ts"],"names":[],"mappings":";AAAA;;;EAGE;;;AA2BF,IAAY,+BAIX;AAJD,WAAY,+BAA+B;IACzC,gDAAa,CAAA;IACb,gDAAa,CAAA;IACb,kDAAe,CAAA;AACjB,CAAC,EAJW,+BAA+B,+CAA/B,+BAA+B,QAI1C;AAwBD,MAAqB,gBAAgB;IAenC;;;;;;;;;;;;;;OAcG;IACH,YACS,OAAwB,EAC/B,IAAmB;QADZ,YAAO,GAAP,OAAO,CAAiB;QA9BjC,UAAK,GAA0B,EAAE,CAAA;QACjC,iBAAY,GAAsB,EAAE,CAAA;QACpC,YAAO,GAAkB,IAAI,CAAA;QAC7B,YAAO,GAAY,KAAK,CAAA;QACxB,WAAM,GAIF;YACF,MAAM,EAAE,GAAG,EAAE,GAAE,CAAC;YAChB,OAAO,EAAE,GAAG,EAAE,GAAE,CAAC;YACjB,MAAM,EAAE,GAAG,EAAE,GAAE,CAAC;SACjB,CAAA;QAqBC,MAAM,MAAM,GAAG,CAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,MAAM,KAAI;YAC7B,KAAK,EAAE,gBAAgB;YACvB,IAAI,EAAE,eAAe;SACtB,CAAA;QAED,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,EAAE,EAAE,CAAC,QAA0B,EAAE,EAAE;YAChE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC,MAAM,CAAA;YAE/C,IAAI,CAAC,OAAO,GAAG,IA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BACjB,CAAC,CAAe,CAAA;YAClB,CAAC;iBAAM,CAAC;gBACN,QAAQ,CAAC,GAAG,CAAC,GAAG,SAAS,CAAA;YAC3B,CAAC;YAED,OAAO,QAAQ,CAAA;QACjB,CAAC,EAAE,EAA2B,CAAC,CAAA;IACjC,CAAC;IAED,gBAAgB;IACR,MAAM,CAAC,SAAS,CAAC,GAA2B;QAClD,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAA;IACxC,CAAC;IAED,gBAAgB;IACR,MAAM,CAAC,QAAgC;QAC7C,IAAI,CAAC,MAAM,CAAC,MAAM,GAAG,QAAQ,CAAA;IAC/B,CAAC;IAED,gBAAgB;IACR,OAAO,CAAC,QAAiC;QAC/C,IAAI,CAAC,MAAM,CAAC,OAAO,GAAG,QAAQ,CAAA;IAChC,CAAC;IAED,gBAAgB;IACR,MAAM,CAAC,QAAoB;QACjC,IAAI,CAAC,MAAM,CAAC,MAAM,GAAG,QAAQ,CAAA;IAC/B,CAAC;IAED,gBAAgB;IACR,kBAAkB;QACxB,OAAO,CAAC,IAAI,CAAC,OAAO,IAAI,IAAI,CAAC,OAAO,KAAK,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAA;IAClE,CAAC;CACF;AA/RD,mCA+RC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/index.d.ts b/backend/node_modules/@supabase/realtime-js/dist/main/index.d.ts new file mode 100644 index 0000000..b7dbd1c --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/index.d.ts @@ -0,0 +1,6 @@ +import RealtimeClient, { RealtimeClientOptions, RealtimeMessage, RealtimeRemoveChannelResponse, WebSocketLikeConstructor } from './RealtimeClient'; +import RealtimeChannel, { RealtimeChannelOptions, RealtimeChannelSendResponse, RealtimePostgresChangesFilter, RealtimePostgresChangesPayload, RealtimePostgresInsertPayload, RealtimePostgresUpdatePayload, RealtimePostgresDeletePayload, REALTIME_LISTEN_TYPES, REALTIME_POSTGRES_CHANGES_LISTEN_EVENT, REALTIME_SUBSCRIBE_STATES, REALTIME_CHANNEL_STATES } from './RealtimeChannel'; +import RealtimePresence, { RealtimePresenceState, RealtimePresenceJoinPayload, RealtimePresenceLeavePayload, REALTIME_PRESENCE_LISTEN_EVENTS } from './RealtimePresence'; +import WebSocketFactory, { WebSocketLike } from './lib/websocket-factory'; +export { RealtimePresence, RealtimeChannel, RealtimeChannelOptions, RealtimeChannelSendResponse, RealtimeClient, RealtimeClientOptions, RealtimeMessage, RealtimePostgresChangesFilter, RealtimePostgresChangesPayload, RealtimePostgresInsertPayload, RealtimePostgresUpdatePayload, RealtimePostgresDeletePayload, RealtimePresenceJoinPayload, RealtimePresenceLeavePayload, RealtimePresenceState, RealtimeRemoveChannelResponse, REALTIME_LISTEN_TYPES, REALTIME_POSTGRES_CHANGES_LISTEN_EVENT, REALTIME_PRESENCE_LISTEN_EVENTS, REALTIME_SUBSCRIBE_STATES, REALTIME_CHANNEL_STATES, WebSocketFactory, WebSocketLike, WebSocketLikeConstructor, }; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/index.d.ts.map b/backend/node_modules/@supabase/realtime-js/dist/main/index.d.ts.map new file mode 100644 index 0000000..4e16838 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,EAAE,EACrB,qBAAqB,EACrB,eAAe,EACf,6BAA6B,EAC7B,wBAAwB,EACzB,MAAM,kBAAkB,CAAA;AACzB,OAAO,eAAe,EAAE,EACtB,sBAAsB,EACtB,2BAA2B,EAC3B,6BAA6B,EAC7B,8BAA8B,EAC9B,6BAA6B,EAC7B,6BAA6B,EAC7B,6BAA6B,EAC7B,qBAAqB,EACrB,sCAAsC,EACtC,yBAAyB,EACzB,uBAAuB,EACxB,MAAM,mBAAmB,CAAA;AAC1B,OAAO,gBAAgB,EAAE,EACvB,qBAAqB,EACrB,2BAA2B,EAC3B,4BAA4B,EAC5B,+BAA+B,EAChC,MAAM,oBAAoB,CAAA;AAC3B,OAAO,gBAAgB,EAAE,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAA;AAEzE,OAAO,EACL,gBAAgB,EAChB,eAAe,EACf,sBAAsB,EACtB,2BAA2B,EAC3B,cAAc,EACd,qBAAqB,EACrB,eAAe,EACf,6BAA6B,EAC7B,8BAA8B,EAC9B,6BAA6B,EAC7B,6BAA6B,EAC7B,6BAA6B,EAC7B,2BAA2B,EAC3B,4BAA4B,EAC5B,qBAAqB,EACrB,6BAA6B,EAC7B,qBAAqB,EACrB,sCAAsC,EACtC,+BAA+B,EAC/B,yBAAyB,EACzB,uBAAuB,EACvB,gBAAgB,EAChB,aAAa,EACb,wBAAwB,GACzB,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/index.js b/backend/node_modules/@supabase/realtime-js/dist/main/index.js new file mode 100644 index 0000000..3f3912c --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/index.js @@ -0,0 +1,18 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WebSocketFactory = exports.REALTIME_CHANNEL_STATES = exports.REALTIME_SUBSCRIBE_STATES = exports.REALTIME_PRESENCE_LISTEN_EVENTS = exports.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = exports.REALTIME_LISTEN_TYPES = exports.RealtimeClient = exports.RealtimeChannel = exports.RealtimePresence = void 0; +const tslib_1 = require("tslib"); +const RealtimeClient_1 = tslib_1.__importDefault(require("./RealtimeClient")); +exports.RealtimeClient = RealtimeClient_1.default; +const RealtimeChannel_1 = tslib_1.__importStar(require("./RealtimeChannel")); +exports.RealtimeChannel = RealtimeChannel_1.default; +Object.defineProperty(exports, "REALTIME_LISTEN_TYPES", { enumerable: true, get: function () { return RealtimeChannel_1.REALTIME_LISTEN_TYPES; } }); +Object.defineProperty(exports, "REALTIME_POSTGRES_CHANGES_LISTEN_EVENT", { enumerable: true, get: function () { return RealtimeChannel_1.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT; } }); +Object.defineProperty(exports, "REALTIME_SUBSCRIBE_STATES", { enumerable: true, get: function () { return RealtimeChannel_1.REALTIME_SUBSCRIBE_STATES; } }); +Object.defineProperty(exports, "REALTIME_CHANNEL_STATES", { enumerable: true, get: function () { return RealtimeChannel_1.REALTIME_CHANNEL_STATES; } }); +const RealtimePresence_1 = tslib_1.__importStar(require("./RealtimePresence")); +exports.RealtimePresence = RealtimePresence_1.default; +Object.defineProperty(exports, "REALTIME_PRESENCE_LISTEN_EVENTS", { enumerable: true, get: function () { return RealtimePresence_1.REALTIME_PRESENCE_LISTEN_EVENTS; } }); +const websocket_factory_1 = tslib_1.__importDefault(require("./lib/websocket-factory")); +exports.WebSocketFactory = websocket_factory_1.default; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/index.js.map b/backend/node_modules/@supabase/realtime-js/dist/main/index.js.map new file mode 100644 index 0000000..2804a3f --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;AAAA,8EAKyB;AA2BvB,yBAhCK,wBAAc,CAgCL;AA1BhB,6EAY0B;AAWxB,0BAvBK,yBAAe,CAuBL;AAef,sGA9BA,uCAAqB,OA8BA;AACrB,uHA9BA,wDAAsC,OA8BA;AAEtC,0GA/BA,2CAAyB,OA+BA;AACzB,wGA/BA,yCAAuB,OA+BA;AA7BzB,+EAK2B;AAIzB,2BATK,0BAAgB,CASL;AAkBhB,gHAvBA,kDAA+B,OAuBA;AArBjC,wFAAyE;AAwBvE,2BAxBK,2BAAgB,CAwBL"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/lib/constants.d.ts b/backend/node_modules/@supabase/realtime-js/dist/main/lib/constants.d.ts new file mode 100644 index 0000000..73410d4 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/lib/constants.d.ts @@ -0,0 +1,39 @@ +export declare const DEFAULT_VERSION = "realtime-js/2.87.1"; +export declare const VSN_1_0_0: string; +export declare const VSN_2_0_0: string; +export declare const DEFAULT_VSN: string; +export declare const VERSION = "2.87.1"; +export declare const DEFAULT_TIMEOUT = 10000; +export declare const WS_CLOSE_NORMAL = 1000; +export declare const MAX_PUSH_BUFFER_SIZE = 100; +export declare enum SOCKET_STATES { + connecting = 0, + open = 1, + closing = 2, + closed = 3 +} +export declare enum CHANNEL_STATES { + closed = "closed", + errored = "errored", + joined = "joined", + joining = "joining", + leaving = "leaving" +} +export declare enum CHANNEL_EVENTS { + close = "phx_close", + error = "phx_error", + join = "phx_join", + reply = "phx_reply", + leave = "phx_leave", + access_token = "access_token" +} +export declare enum TRANSPORTS { + websocket = "websocket" +} +export declare enum CONNECTION_STATE { + Connecting = "connecting", + Open = "open", + Closing = "closing", + Closed = "closed" +} +//# sourceMappingURL=constants.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/lib/constants.d.ts.map b/backend/node_modules/@supabase/realtime-js/dist/main/lib/constants.d.ts.map new file mode 100644 index 0000000..1e277aa --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/lib/constants.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,eAAe,uBAA2B,CAAA;AAEvD,eAAO,MAAM,SAAS,EAAE,MAAgB,CAAA;AACxC,eAAO,MAAM,SAAS,EAAE,MAAgB,CAAA;AACxC,eAAO,MAAM,WAAW,EAAE,MAAkB,CAAA;AAE5C,eAAO,MAAM,OAAO,WAAU,CAAA;AAE9B,eAAO,MAAM,eAAe,QAAQ,CAAA;AAEpC,eAAO,MAAM,eAAe,OAAO,CAAA;AACnC,eAAO,MAAM,oBAAoB,MAAM,CAAA;AAEvC,oBAAY,aAAa;IACvB,UAAU,IAAI;IACd,IAAI,IAAI;IACR,OAAO,IAAI;IACX,MAAM,IAAI;CACX;AAED,oBAAY,cAAc;IACxB,MAAM,WAAW;IACjB,OAAO,YAAY;IACnB,MAAM,WAAW;IACjB,OAAO,YAAY;IACnB,OAAO,YAAY;CACpB;AAED,oBAAY,cAAc;IACxB,KAAK,cAAc;IACnB,KAAK,cAAc;IACnB,IAAI,aAAa;IACjB,KAAK,cAAc;IACnB,KAAK,cAAc;IACnB,YAAY,iBAAiB;CAC9B;AAED,oBAAY,UAAU;IACpB,SAAS,cAAc;CACxB;AAED,oBAAY,gBAAgB;IAC1B,UAAU,eAAe;IACzB,IAAI,SAAS;IACb,OAAO,YAAY;IACnB,MAAM,WAAW;CAClB"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/lib/constants.js b/backend/node_modules/@supabase/realtime-js/dist/main/lib/constants.js new file mode 100644 index 0000000..d165a30 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/lib/constants.js @@ -0,0 +1,48 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CONNECTION_STATE = exports.TRANSPORTS = exports.CHANNEL_EVENTS = exports.CHANNEL_STATES = exports.SOCKET_STATES = exports.MAX_PUSH_BUFFER_SIZE = exports.WS_CLOSE_NORMAL = exports.DEFAULT_TIMEOUT = exports.VERSION = exports.DEFAULT_VSN = exports.VSN_2_0_0 = exports.VSN_1_0_0 = exports.DEFAULT_VERSION = void 0; +const version_1 = require("./version"); +exports.DEFAULT_VERSION = `realtime-js/${version_1.version}`; +exports.VSN_1_0_0 = '1.0.0'; +exports.VSN_2_0_0 = '2.0.0'; +exports.DEFAULT_VSN = exports.VSN_1_0_0; +exports.VERSION = version_1.version; +exports.DEFAULT_TIMEOUT = 10000; +exports.WS_CLOSE_NORMAL = 1000; +exports.MAX_PUSH_BUFFER_SIZE = 100; +var SOCKET_STATES; +(function (SOCKET_STATES) { + SOCKET_STATES[SOCKET_STATES["connecting"] = 0] = "connecting"; + SOCKET_STATES[SOCKET_STATES["open"] = 1] = "open"; + SOCKET_STATES[SOCKET_STATES["closing"] = 2] = "closing"; + SOCKET_STATES[SOCKET_STATES["closed"] = 3] = "closed"; +})(SOCKET_STATES || (exports.SOCKET_STATES = SOCKET_STATES = {})); +var CHANNEL_STATES; +(function (CHANNEL_STATES) { + CHANNEL_STATES["closed"] = "closed"; + CHANNEL_STATES["errored"] = "errored"; + CHANNEL_STATES["joined"] = "joined"; + CHANNEL_STATES["joining"] = "joining"; + CHANNEL_STATES["leaving"] = "leaving"; +})(CHANNEL_STATES || (exports.CHANNEL_STATES = CHANNEL_STATES = {})); +var CHANNEL_EVENTS; +(function (CHANNEL_EVENTS) { + CHANNEL_EVENTS["close"] = "phx_close"; + CHANNEL_EVENTS["error"] = "phx_error"; + CHANNEL_EVENTS["join"] = "phx_join"; + CHANNEL_EVENTS["reply"] = "phx_reply"; + CHANNEL_EVENTS["leave"] = "phx_leave"; + CHANNEL_EVENTS["access_token"] = "access_token"; +})(CHANNEL_EVENTS || (exports.CHANNEL_EVENTS = CHANNEL_EVENTS = {})); +var TRANSPORTS; +(function (TRANSPORTS) { + TRANSPORTS["websocket"] = "websocket"; +})(TRANSPORTS || (exports.TRANSPORTS = TRANSPORTS = {})); +var CONNECTION_STATE; +(function (CONNECTION_STATE) { + CONNECTION_STATE["Connecting"] = "connecting"; + CONNECTION_STATE["Open"] = "open"; + CONNECTION_STATE["Closing"] = "closing"; + CONNECTION_STATE["Closed"] = "closed"; +})(CONNECTION_STATE || (exports.CONNECTION_STATE = CONNECTION_STATE = {})); +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/lib/constants.js.map b/backend/node_modules/@supabase/realtime-js/dist/main/lib/constants.js.map new file mode 100644 index 0000000..a530e7d --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/lib/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":";;;AAAA,uCAAmC;AAEtB,QAAA,eAAe,GAAG,eAAe,iBAAO,EAAE,CAAA;AAE1C,QAAA,SAAS,GAAW,OAAO,CAAA;AAC3B,QAAA,SAAS,GAAW,OAAO,CAAA;AAC3B,QAAA,WAAW,GAAW,iBAAS,CAAA;AAE/B,QAAA,OAAO,GAAG,iBAAO,CAAA;AAEjB,QAAA,eAAe,GAAG,KAAK,CAAA;AAEvB,QAAA,eAAe,GAAG,IAAI,CAAA;AACtB,QAAA,oBAAoB,GAAG,GAAG,CAAA;AAEvC,IAAY,aAKX;AALD,WAAY,aAAa;IACvB,6DAAc,CAAA;IACd,iDAAQ,CAAA;IACR,uDAAW,CAAA;IACX,qDAAU,CAAA;AACZ,CAAC,EALW,aAAa,6BAAb,aAAa,QAKxB;AAED,IAAY,cAMX;AAND,WAAY,cAAc;IACxB,mCAAiB,CAAA;IACjB,qCAAmB,CAAA;IACnB,mCAAiB,CAAA;IACjB,qCAAmB,CAAA;IACnB,qCAAmB,CAAA;AACrB,CAAC,EANW,cAAc,8BAAd,cAAc,QAMzB;AAED,IAAY,cAOX;AAPD,WAAY,cAAc;IACxB,qCAAmB,CAAA;IACnB,qCAAmB,CAAA;IACnB,mCAAiB,CAAA;IACjB,qCAAmB,CAAA;IACnB,qCAAmB,CAAA;IACnB,+CAA6B,CAAA;AAC/B,CAAC,EAPW,cAAc,8BAAd,cAAc,QAOzB;AAED,IAAY,UAEX;AAFD,WAAY,UAAU;IACpB,qCAAuB,CAAA;AACzB,CAAC,EAFW,UAAU,0BAAV,UAAU,QAErB;AAED,IAAY,gBAKX;AALD,WAAY,gBAAgB;IAC1B,6CAAyB,CAAA;IACzB,iCAAa,CAAA;IACb,uCAAmB,CAAA;IACnB,qCAAiB,CAAA;AACnB,CAAC,EALW,gBAAgB,gCAAhB,gBAAgB,QAK3B"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/lib/push.d.ts b/backend/node_modules/@supabase/realtime-js/dist/main/lib/push.d.ts new file mode 100644 index 0000000..604c4f7 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/lib/push.d.ts @@ -0,0 +1,48 @@ +import type RealtimeChannel from '../RealtimeChannel'; +export default class Push { + channel: RealtimeChannel; + event: string; + payload: { + [key: string]: any; + }; + timeout: number; + sent: boolean; + timeoutTimer: number | undefined; + ref: string; + receivedResp: { + status: string; + response: { + [key: string]: any; + }; + } | null; + recHooks: { + status: string; + callback: Function; + }[]; + refEvent: string | null; + /** + * Initializes the Push + * + * @param channel The Channel + * @param event The event, for example `"phx_join"` + * @param payload The payload, for example `{user_id: 123}` + * @param timeout The push timeout in milliseconds + */ + constructor(channel: RealtimeChannel, event: string, payload?: { + [key: string]: any; + }, timeout?: number); + resend(timeout: number): void; + send(): void; + updatePayload(payload: { + [key: string]: any; + }): void; + receive(status: string, callback: Function): this; + startTimeout(): void; + trigger(status: string, response: any): void; + destroy(): void; + private _cancelRefEvent; + private _cancelTimeout; + private _matchReceive; + private _hasReceived; +} +//# sourceMappingURL=push.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/lib/push.d.ts.map b/backend/node_modules/@supabase/realtime-js/dist/main/lib/push.d.ts.map new file mode 100644 index 0000000..9b612a0 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/lib/push.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"push.d.ts","sourceRoot":"","sources":["../../../src/lib/push.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,eAAe,MAAM,oBAAoB,CAAA;AAErD,MAAM,CAAC,OAAO,OAAO,IAAI;IAuBd,OAAO,EAAE,eAAe;IACxB,KAAK,EAAE,MAAM;IACb,OAAO,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KAAE;IAC/B,OAAO,EAAE,MAAM;IAzBxB,IAAI,EAAE,OAAO,CAAQ;IACrB,YAAY,EAAE,MAAM,GAAG,SAAS,CAAY;IAC5C,GAAG,EAAE,MAAM,CAAK;IAChB,YAAY,EAAE;QACZ,MAAM,EAAE,MAAM,CAAA;QACd,QAAQ,EAAE;YAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;SAAE,CAAA;KACjC,GAAG,IAAI,CAAO;IACf,QAAQ,EAAE;QACR,MAAM,EAAE,MAAM,CAAA;QACd,QAAQ,EAAE,QAAQ,CAAA;KACnB,EAAE,CAAK;IACR,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAO;IAE9B;;;;;;;OAOG;gBAEM,OAAO,EAAE,eAAe,EACxB,KAAK,EAAE,MAAM,EACb,OAAO,GAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KAAO,EACpC,OAAO,GAAE,MAAwB;IAG1C,MAAM,CAAC,OAAO,EAAE,MAAM;IAUtB,IAAI;IAeJ,aAAa,CAAC,OAAO,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KAAE,GAAG,IAAI;IAIpD,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ;IAS1C,YAAY;IAqBZ,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG;IAIrC,OAAO;IAKP,OAAO,CAAC,eAAe;IAQvB,OAAO,CAAC,cAAc;IAKtB,OAAO,CAAC,aAAa;IAIrB,OAAO,CAAC,YAAY;CAGrB"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/lib/push.js b/backend/node_modules/@supabase/realtime-js/dist/main/lib/push.js new file mode 100644 index 0000000..2e75c32 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/lib/push.js @@ -0,0 +1,102 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const constants_1 = require("../lib/constants"); +class Push { + /** + * Initializes the Push + * + * @param channel The Channel + * @param event The event, for example `"phx_join"` + * @param payload The payload, for example `{user_id: 123}` + * @param timeout The push timeout in milliseconds + */ + constructor(channel, event, payload = {}, timeout = constants_1.DEFAULT_TIMEOUT) { + this.channel = channel; + this.event = event; + this.payload = payload; + this.timeout = timeout; + this.sent = false; + this.timeoutTimer = undefined; + this.ref = ''; + this.receivedResp = null; + this.recHooks = []; + this.refEvent = null; + } + resend(timeout) { + this.timeout = timeout; + this._cancelRefEvent(); + this.ref = ''; + this.refEvent = null; + this.receivedResp = null; + this.sent = false; + this.send(); + } + send() { + if (this._hasReceived('timeout')) { + return; + } + this.startTimeout(); + this.sent = true; + this.channel.socket.push({ + topic: this.channel.topic, + event: this.event, + payload: this.payload, + ref: this.ref, + join_ref: this.channel._joinRef(), + }); + } + updatePayload(payload) { + this.payload = Object.assign(Object.assign({}, this.payload), payload); + } + receive(status, callback) { + var _a; + if (this._hasReceived(status)) { + callback((_a = this.receivedResp) === null || _a === void 0 ? void 0 : _a.response); + } + this.recHooks.push({ status, callback }); + return this; + } + startTimeout() { + if (this.timeoutTimer) { + return; + } + this.ref = this.channel.socket._makeRef(); + this.refEvent = this.channel._replyEventName(this.ref); + const callback = (payload) => { + this._cancelRefEvent(); + this._cancelTimeout(); + this.receivedResp = payload; + this._matchReceive(payload); + }; + this.channel._on(this.refEvent, {}, callback); + this.timeoutTimer = setTimeout(() => { + this.trigger('timeout', {}); + }, this.timeout); + } + trigger(status, response) { + if (this.refEvent) + this.channel._trigger(this.refEvent, { status, response }); + } + destroy() { + this._cancelRefEvent(); + this._cancelTimeout(); + } + _cancelRefEvent() { + if (!this.refEvent) { + return; + } + this.channel._off(this.refEvent, {}); + } + _cancelTimeout() { + clearTimeout(this.timeoutTimer); + this.timeoutTimer = undefined; + } + _matchReceive({ status, response }) { + this.recHooks.filter((h) => h.status === status).forEach((h) => h.callback(response)); + } + _hasReceived(status) { + return this.receivedResp && this.receivedResp.status === status; + } +} +exports.default = Push; +//# sourceMappingURL=push.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/lib/push.js.map b/backend/node_modules/@supabase/realtime-js/dist/main/lib/push.js.map new file mode 100644 index 0000000..dd6350b --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/lib/push.js.map @@ -0,0 +1 @@ +{"version":3,"file":"push.js","sourceRoot":"","sources":["../../../src/lib/push.ts"],"names":[],"mappings":";;AAAA,gDAAkD;AAGlD,MAAqB,IAAI;IAcvB;;;;;;;OAOG;IACH,YACS,OAAwB,EACxB,KAAa,EACb,UAAkC,EAAE,EACpC,UAAkB,2BAAe;QAHjC,YAAO,GAAP,OAAO,CAAiB;QACxB,UAAK,GAAL,KAAK,CAAQ;QACb,YAAO,GAAP,OAAO,CAA6B;QACpC,YAAO,GAAP,OAAO,CAA0B;QAzB1C,SAAI,GAAY,KAAK,CAAA;QACrB,iBAAY,GAAuB,SAAS,CAAA;QAC5C,QAAG,GAAW,EAAE,CAAA;QAChB,iBAAY,GAGD,IAAI,CAAA;QACf,aAAQ,GAGF,EAAE,CAAA;QACR,aAAQ,GAAkB,IAAI,CAAA;IAe3B,CAAC;IAEJ,MAAM,CAAC,OAAe;QACpB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;QACtB,IAAI,CAAC,eAAe,EAAE,CAAA;QACtB,IAAI,CAAC,GAAG,GAAG,EAAE,CAAA;QACb,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAA;QACpB,IAAI,CAAC,YAAY,GAAG,IAAI,CAAA;QACxB,IAAI,CAAC,IAAI,GAAG,KAAK,CAAA;QACjB,IAAI,CAAC,IAAI,EAAE,CAAA;IACb,CAAC;IAED,IAAI;QACF,IAAI,IAAI,CAAC,YAAY,CAAC,SAAS,CAAC,EAAE,CAAC;YACjC,OAAM;QACR,CAAC;QACD,IAAI,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,YAAY,CAAC,MAAM,KAAK,MAAM,CAAA;IACjE,CAAC;CACF;AArHD,uBAqHC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/lib/serializer.d.ts b/backend/node_modules/@supabase/realtime-js/dist/main/lib/serializer.d.ts new file mode 100644 index 0000000..39fbd2a --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/lib/serializer.d.ts @@ -0,0 +1,33 @@ +export type Msg = { + join_ref?: string | null; + ref?: string | null; + topic: string; + event: string; + payload: T; +}; +export default class Serializer { + HEADER_LENGTH: number; + USER_BROADCAST_PUSH_META_LENGTH: number; + KINDS: { + userBroadcastPush: number; + userBroadcast: number; + }; + BINARY_ENCODING: number; + JSON_ENCODING: number; + BROADCAST_EVENT: string; + allowedMetadataKeys: string[]; + constructor(allowedMetadataKeys?: string[] | null); + encode(msg: Msg<{ + [key: string]: any; + }>, callback: (result: ArrayBuffer | string) => any): any; + private _binaryEncodeUserBroadcastPush; + private _encodeBinaryUserBroadcastPush; + private _encodeJsonUserBroadcastPush; + private _encodeUserBroadcastPush; + decode(rawPayload: ArrayBuffer | string, callback: Function): any; + private _binaryDecode; + private _decodeUserBroadcast; + private _isArrayBuffer; + private _pick; +} +//# sourceMappingURL=serializer.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/lib/serializer.d.ts.map b/backend/node_modules/@supabase/realtime-js/dist/main/lib/serializer.d.ts.map new file mode 100644 index 0000000..0bb397b --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/lib/serializer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"serializer.d.ts","sourceRoot":"","sources":["../../../src/lib/serializer.ts"],"names":[],"mappings":"AAEA,MAAM,MAAM,GAAG,CAAC,CAAC,IAAI;IACnB,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACxB,GAAG,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACnB,KAAK,EAAE,MAAM,CAAA;IACb,KAAK,EAAE,MAAM,CAAA;IACb,OAAO,EAAE,CAAC,CAAA;CACX,CAAA;AAED,MAAM,CAAC,OAAO,OAAO,UAAU;IAC7B,aAAa,SAAI;IACjB,+BAA+B,SAAI;IACnC,KAAK;;;MAA6C;IAClD,eAAe,SAAI;IACnB,aAAa,SAAI;IACjB,eAAe,SAAc;IAE7B,mBAAmB,EAAE,MAAM,EAAE,CAAK;gBAEtB,mBAAmB,CAAC,EAAE,MAAM,EAAE,GAAG,IAAI;IAIjD,MAAM,CAAC,GAAG,EAAE,GAAG,CAAC;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KAAE,CAAC,EAAE,QAAQ,EAAE,CAAC,MAAM,EAAE,WAAW,GAAG,MAAM,KAAK,GAAG;IAexF,OAAO,CAAC,8BAA8B;IAQtC,OAAO,CAAC,8BAA8B;IAKtC,OAAO,CAAC,4BAA4B;IAOpC,OAAO,CAAC,wBAAwB;IAkEhC,MAAM,CAAC,UAAU,EAAE,WAAW,GAAG,MAAM,EAAE,QAAQ,EAAE,QAAQ;IAe3D,OAAO,CAAC,aAAa;IAUrB,OAAO,CAAC,oBAAoB;IA0C5B,OAAO,CAAC,cAAc;IAItB,OAAO,CAAC,KAAK;CAMd"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/lib/serializer.js b/backend/node_modules/@supabase/realtime-js/dist/main/lib/serializer.js new file mode 100644 index 0000000..24d6a5e --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/lib/serializer.js @@ -0,0 +1,155 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +class Serializer { + constructor(allowedMetadataKeys) { + this.HEADER_LENGTH = 1; + this.USER_BROADCAST_PUSH_META_LENGTH = 6; + this.KINDS = { userBroadcastPush: 3, userBroadcast: 4 }; + this.BINARY_ENCODING = 0; + this.JSON_ENCODING = 1; + this.BROADCAST_EVENT = 'broadcast'; + this.allowedMetadataKeys = []; + this.allowedMetadataKeys = allowedMetadataKeys !== null && allowedMetadataKeys !== void 0 ? allowedMetadataKeys : []; + } + encode(msg, callback) { + if (msg.event === this.BROADCAST_EVENT && + !(msg.payload instanceof ArrayBuffer) && + typeof msg.payload.event === 'string') { + return callback(this._binaryEncodeUserBroadcastPush(msg)); + } + let payload = [msg.join_ref, msg.ref, msg.topic, msg.event, msg.payload]; + return callback(JSON.stringify(payload)); + } + _binaryEncodeUserBroadcastPush(message) { + var _a; + if (this._isArrayBuffer((_a = message.payload) === null || _a === void 0 ? void 0 : _a.payload)) { + return this._encodeBinaryUserBroadcastPush(message); + } + else { + return this._encodeJsonUserBroadcastPush(message); + } + } + _encodeBinaryUserBroadcastPush(message) { + var _a, _b; + const userPayload = (_b = (_a = message.payload) === null || _a === void 0 ? void 0 : _a.payload) !== null && _b !== void 0 ? _b : new ArrayBuffer(0); + return this._encodeUserBroadcastPush(message, this.BINARY_ENCODING, userPayload); + } + _encodeJsonUserBroadcastPush(message) { + var _a, _b; + const userPayload = (_b = (_a = message.payload) === null || _a === void 0 ? void 0 : _a.payload) !== null && _b !== void 0 ? _b : {}; + const encoder = new TextEncoder(); + const encodedUserPayload = encoder.encode(JSON.stringify(userPayload)).buffer; + return this._encodeUserBroadcastPush(message, this.JSON_ENCODING, encodedUserPayload); + } + _encodeUserBroadcastPush(message, encodingType, encodedPayload) { + var _a, _b; + const topic = message.topic; + const ref = (_a = message.ref) !== null && _a !== void 0 ? _a : ''; + const joinRef = (_b = message.join_ref) !== null && _b !== void 0 ? _b : ''; + const userEvent = message.payload.event; + // Filter metadata based on allowed keys + const rest = this.allowedMetadataKeys + ? this._pick(message.payload, this.allowedMetadataKeys) + : {}; + const metadata = Object.keys(rest).length === 0 ? '' : JSON.stringify(rest); + // Validate lengths don't exceed uint8 max value (255) + if (joinRef.length > 255) { + throw new Error(`joinRef length ${joinRef.length} exceeds maximum of 255`); + } + if (ref.length > 255) { + throw new Error(`ref length ${ref.length} exceeds maximum of 255`); + } + if (topic.length > 255) { + throw new Error(`topic length ${topic.length} exceeds maximum of 255`); + } + if (userEvent.length > 255) { + throw new Error(`userEvent length ${userEvent.length} exceeds maximum of 255`); + } + if (metadata.length > 255) { + throw new Error(`metadata length ${metadata.length} exceeds maximum of 255`); + } + const metaLength = this.USER_BROADCAST_PUSH_META_LENGTH + + joinRef.length + + ref.length + + topic.length + + userEvent.length + + metadata.length; + const header = new ArrayBuffer(this.HEADER_LENGTH + metaLength); + let view = new DataView(header); + let offset = 0; + view.setUint8(offset++, this.KINDS.userBroadcastPush); // kind + view.setUint8(offset++, joinRef.length); + view.setUint8(offset++, ref.length); + view.setUint8(offset++, topic.length); + view.setUint8(offset++, userEvent.length); + view.setUint8(offset++, metadata.length); + view.setUint8(offset++, encodingType); + Array.from(joinRef, (char) => view.setUint8(offset++, char.charCodeAt(0))); + Array.from(ref, (char) => view.setUint8(offset++, char.charCodeAt(0))); + Array.from(topic, (char) => view.setUint8(offset++, char.charCodeAt(0))); + Array.from(userEvent, (char) => view.setUint8(offset++, char.charCodeAt(0))); + Array.from(metadata, (char) => view.setUint8(offset++, char.charCodeAt(0))); + var combined = new Uint8Array(header.byteLength + encodedPayload.byteLength); + combined.set(new Uint8Array(header), 0); + combined.set(new Uint8Array(encodedPayload), header.byteLength); + return combined.buffer; + } + decode(rawPayload, callback) { + if (this._isArrayBuffer(rawPayload)) { + let result = this._binaryDecode(rawPayload); + return callback(result); + } + if (typeof rawPayload === 'string') { + const jsonPayload = JSON.parse(rawPayload); + const [join_ref, ref, topic, event, payload] = jsonPayload; + return callback({ join_ref, ref, topic, event, payload }); + } + return callback({}); + } + _binaryDecode(buffer) { + const view = new DataView(buffer); + const kind = view.getUint8(0); + const decoder = new TextDecoder(); + switch (kind) { + case this.KINDS.userBroadcast: + return this._decodeUserBroadcast(buffer, view, decoder); + } + } + _decodeUserBroadcast(buffer, view, decoder) { + const topicSize = view.getUint8(1); + const userEventSize = view.getUint8(2); + const metadataSize = view.getUint8(3); + const payloadEncoding = view.getUint8(4); + let offset = this.HEADER_LENGTH + 4; + const topic = decoder.decode(buffer.slice(offset, offset + topicSize)); + offset = offset + topicSize; + const userEvent = decoder.decode(buffer.slice(offset, offset + userEventSize)); + offset = offset + userEventSize; + const metadata = decoder.decode(buffer.slice(offset, offset + metadataSize)); + offset = offset + metadataSize; + const payload = buffer.slice(offset, buffer.byteLength); + const parsedPayload = payloadEncoding === this.JSON_ENCODING ? JSON.parse(decoder.decode(payload)) : payload; + const data = { + type: this.BROADCAST_EVENT, + event: userEvent, + payload: parsedPayload, + }; + // Metadata is optional and always JSON encoded + if (metadataSize > 0) { + data['meta'] = JSON.parse(metadata); + } + return { join_ref: null, ref: null, topic: topic, event: this.BROADCAST_EVENT, payload: data }; + } + _isArrayBuffer(buffer) { + var _a; + return buffer instanceof ArrayBuffer || ((_a = buffer === null || buffer === void 0 ? void 0 : buffer.constructor) === null || _a === void 0 ? void 0 : _a.name) === 'ArrayBuffer'; + } + _pick(obj, keys) { + if (!obj || typeof obj !== 'object') { + return {}; + } + return Object.fromEntries(Object.entries(obj).filter(([key]) => keys.includes(key))); + } +} +exports.default = Serializer; +//# sourceMappingURL=serializer.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/lib/serializer.js.map b/backend/node_modules/@supabase/realtime-js/dist/main/lib/serializer.js.map new file mode 100644 index 0000000..cd95e1a --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/lib/serializer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"serializer.js","sourceRoot":"","sources":["../../../src/lib/serializer.ts"],"names":[],"mappings":";;AAUA,MAAqB,UAAU;IAU7B,YAAY,mBAAqC;QATjD,kBAAa,GAAG,CAAC,CAAA;QACjB,oCAA+B,GAAG,CAAC,CAAA;QACnC,UAAK,GAAG,EAAE,iBAAiB,EAAE,CAAC,EAAE,aAAa,EAAE,CAAC,EAAE,CAAA;QAClD,oBAAe,GAAG,CAAC,CAAA;QACnB,kBAAa,GAAG,CA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AC/C,IAAI,YAAY,GAAG,CAAC,EAAE,CAAC;YACrB,IAAI,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAA;QACrC,CAAC;QAED,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,CAAC,eAAe,EAAE,OAAO,EAAE,IAAI,EAAE,CAAA;IAChG,CAAC;IAEO,cAAc,CAAC,MAAW;;QAChC,OAAO,MAAM,YAAY,WAAW,IAAI,CAAA,MAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,WAAW,0CAAE,IAAI,MAAK,aAAa,CAAA;IACrF,CAAC;IAEO,KAAK,CAAC,GAA2C,EAAE,IAAc;QACvE,IAAI,CAAC,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE,CAAC;YACpC,OAAO,EAAE,CAAA;QACX,CAAC;QACD,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAA;IACtF,CAAC;CACF;AAhMD,6BAgMC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/lib/timer.d.ts b/backend/node_modules/@supabase/realtime-js/dist/main/lib/timer.d.ts new file mode 100644 index 0000000..d5df4a6 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/lib/timer.d.ts @@ -0,0 +1,22 @@ +/** + * Creates a timer that accepts a `timerCalc` function to perform calculated timeout retries, such as exponential backoff. + * + * @example + * let reconnectTimer = new Timer(() => this.connect(), function(tries){ + * return [1000, 5000, 10000][tries - 1] || 10000 + * }) + * reconnectTimer.scheduleTimeout() // fires after 1000 + * reconnectTimer.scheduleTimeout() // fires after 5000 + * reconnectTimer.reset() + * reconnectTimer.scheduleTimeout() // fires after 1000 + */ +export default class Timer { + callback: Function; + timerCalc: Function; + timer: number | undefined; + tries: number; + constructor(callback: Function, timerCalc: Function); + reset(): void; + scheduleTimeout(): void; +} +//# sourceMappingURL=timer.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/lib/timer.d.ts.map b/backend/node_modules/@supabase/realtime-js/dist/main/lib/timer.d.ts.map new file mode 100644 index 0000000..3cee271 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/lib/timer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"timer.d.ts","sourceRoot":"","sources":["../../../src/lib/timer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,OAAO,OAAO,KAAK;IAKf,QAAQ,EAAE,QAAQ;IAClB,SAAS,EAAE,QAAQ;IAL5B,KAAK,EAAE,MAAM,GAAG,SAAS,CAAY;IACrC,KAAK,EAAE,MAAM,CAAI;gBAGR,QAAQ,EAAE,QAAQ,EAClB,SAAS,EAAE,QAAQ;IAM5B,KAAK;IAOL,eAAe;CAWhB"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/lib/timer.js b/backend/node_modules/@supabase/realtime-js/dist/main/lib/timer.js new file mode 100644 index 0000000..d6b34ae --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/lib/timer.js @@ -0,0 +1,39 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * Creates a timer that accepts a `timerCalc` function to perform calculated timeout retries, such as exponential backoff. + * + * @example + * let reconnectTimer = new Timer(() => this.connect(), function(tries){ + * return [1000, 5000, 10000][tries - 1] || 10000 + * }) + * reconnectTimer.scheduleTimeout() // fires after 1000 + * reconnectTimer.scheduleTimeout() // fires after 5000 + * reconnectTimer.reset() + * reconnectTimer.scheduleTimeout() // fires after 1000 + */ +class Timer { + constructor(callback, timerCalc) { + this.callback = callback; + this.timerCalc = timerCalc; + this.timer = undefined; + this.tries = 0; + this.callback = callback; + this.timerCalc = timerCalc; + } + reset() { + this.tries = 0; + clearTimeout(this.timer); + this.timer = undefined; + } + // Cancels any previous scheduleTimeout and schedules callback + scheduleTimeout() { + clearTimeout(this.timer); + this.timer = setTimeout(() => { + this.tries = this.tries + 1; + this.callback(); + }, this.timerCalc(this.tries + 1)); + } +} +exports.default = Timer; +//# sourceMappingURL=timer.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/lib/timer.js.map b/backend/node_modules/@supabase/realtime-js/dist/main/lib/timer.js.map new file mode 100644 index 0000000..80e89b8 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/lib/timer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"timer.js","sourceRoot":"","sources":["../../../src/lib/timer.ts"],"names":[],"mappings":";;AAAA;;;;;;;;;;;GAWG;AACH,MAAqB,KAAK;IAIxB,YACS,QAAkB,EAClB,SAAmB;QADnB,aAAQ,GAAR,QAAQ,CAAU;QAClB,cAAS,GAAT,SAAS,CAAU;QAL5B,UAAK,GAAuB,SAAS,CAAA;QACrC,UAAK,GAAW,CAAC,CAAA;QAMf,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;QACxB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAA;IAC5B,CAAC;IAED,KAAK;QACH,IAAI,CAAC,KAAK,GAAG,CAAC,CAAA;QACd,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;QACxB,IAAI,CAAC,KAAK,GAAG,SAAS,CAAA;IACxB,CAAC;IAED,8DAA8D;IAC9D,eAAe;QACb,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;QAExB,IAAI,CAAC,KAAK,GAAQ,UAAU,CAC1B,GAAG,EAAE;YACH,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,GAAG,CAAC,CAAA;YAC3B,IAAI,CAAC,QAAQ,EAAE,CAAA;QACjB,CAAC,EACD,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,KAAK,GAAG,CAAC,CAAC,CAC/B,CAAA;IACH,CAAC;CACF;AA9BD,wBA8BC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/lib/transformers.d.ts b/backend/node_modules/@supabase/realtime-js/dist/main/lib/transformers.d.ts new file mode 100644 index 0000000..d52adaf --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/lib/transformers.d.ts @@ -0,0 +1,109 @@ +/** + * Helpers to convert the change Payload into native JS types. + */ +export declare enum PostgresTypes { + abstime = "abstime", + bool = "bool", + date = "date", + daterange = "daterange", + float4 = "float4", + float8 = "float8", + int2 = "int2", + int4 = "int4", + int4range = "int4range", + int8 = "int8", + int8range = "int8range", + json = "json", + jsonb = "jsonb", + money = "money", + numeric = "numeric", + oid = "oid", + reltime = "reltime", + text = "text", + time = "time", + timestamp = "timestamp", + timestamptz = "timestamptz", + timetz = "timetz", + tsrange = "tsrange", + tstzrange = "tstzrange" +} +type Columns = { + name: string; + type: string; + flags?: string[]; + type_modifier?: number; +}[]; +type BaseValue = null | string | number | boolean; +type RecordValue = BaseValue | BaseValue[]; +type Record = { + [key: string]: RecordValue; +}; +/** + * Takes an array of columns and an object of string values then converts each string value + * to its mapped type. + * + * @param {{name: String, type: String}[]} columns + * @param {Object} record + * @param {Object} options The map of various options that can be applied to the mapper + * @param {Array} options.skipTypes The array of types that should not be converted + * + * @example convertChangeData([{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age:'33'}, {}) + * //=>{ first_name: 'Paul', age: 33 } + */ +export declare const convertChangeData: (columns: Columns, record: Record | null, options?: { + skipTypes?: string[]; +}) => Record; +/** + * Converts the value of an individual column. + * + * @param {String} columnName The column that you want to convert + * @param {{name: String, type: String}[]} columns All of the columns + * @param {Object} record The map of string values + * @param {Array} skipTypes An array of types that should not be converted + * @return {object} Useless information + * + * @example convertColumn('age', [{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age: '33'}, []) + * //=> 33 + * @example convertColumn('age', [{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age: '33'}, ['int4']) + * //=> "33" + */ +export declare const convertColumn: (columnName: string, columns: Columns, record: Record, skipTypes: string[]) => RecordValue; +/** + * If the value of the cell is `null`, returns null. + * Otherwise converts the string value to the correct type. + * @param {String} type A postgres column type + * @param {String} value The cell value + * + * @example convertCell('bool', 't') + * //=> true + * @example convertCell('int8', '10') + * //=> 10 + * @example convertCell('_int4', '{1,2,3,4}') + * //=> [1,2,3,4] + */ +export declare const convertCell: (type: string, value: RecordValue) => RecordValue; +export declare const toBoolean: (value: RecordValue) => RecordValue; +export declare const toNumber: (value: RecordValue) => RecordValue; +export declare const toJson: (value: RecordValue) => RecordValue; +/** + * Converts a Postgres Array into a native JS array + * + * @example toArray('{}', 'int4') + * //=> [] + * @example toArray('{"[2021-01-01,2021-12-31)","(2021-01-01,2021-12-32]"}', 'daterange') + * //=> ['[2021-01-01,2021-12-31)', '(2021-01-01,2021-12-32]'] + * @example toArray([1,2,3,4], 'int4') + * //=> [1,2,3,4] + */ +export declare const toArray: (value: RecordValue, type: string) => RecordValue; +/** + * Fixes timestamp to be ISO-8601. Swaps the space between the date and time for a 'T' + * See https://github.com/supabase/supabase/issues/18 + * + * @example toTimestampString('2019-09-10 00:00:00') + * //=> '2019-09-10T00:00:00' + */ +export declare const toTimestampString: (value: RecordValue) => RecordValue; +export declare const httpEndpointURL: (socketUrl: string) => string; +export {}; +//# sourceMappingURL=transformers.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/lib/transformers.d.ts.map b/backend/node_modules/@supabase/realtime-js/dist/main/lib/transformers.d.ts.map new file mode 100644 index 0000000..0804f76 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/lib/transformers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"transformers.d.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;;;;;;;;;;GAYG;AACH,eAAO,MAAM,WAAW,GAAI,MAAM,MAAM,EAAE,OAAO,WAAW,KAAG,WA0C9D,CAAA;AAKD,eAAO,MAAM,SAAS,GAAI,OAAO,WAAW,KAAG,WAS9C,CAAA;AACD,eAAO,MAAM,QAAQ,GAAI,OAAO,WAAW,KAAG,WAQ7C,CAAA;AACD,eAAO,MAAM,MAAM,GAAI,OAAO,WAAW,KAAG,WAU3C,CAAA;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,OAAO,GAAI,OAAO,WAAW,EAAE,MAAM,MAAM,KAAG,WA0B1D,CAAA;AAED;;;;;;GAMG;AACH,eAAO,MAAM,iBAAiB,GAAI,OAAO,WAAW,KAAG,WAMtD,CAAA;AAED,eAAO,MAAM,eAAe,GAAI,WAAW,MAAM,KAAG,MAkBnD,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/lib/transformers.js b/backend/node_modules/@supabase/realtime-js/dist/main/lib/transformers.js new file mode 100644 index 0000000..344f13e --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/lib/transformers.js @@ -0,0 +1,242 @@ +"use strict"; +/** + * Helpers to convert the change Payload into native JS types. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.httpEndpointURL = exports.toTimestampString = exports.toArray = exports.toJson = exports.toNumber = exports.toBoolean = exports.convertCell = exports.convertColumn = exports.convertChangeData = exports.PostgresTypes = void 0; +// Adapted from epgsql (src/epgsql_binary.erl), this module licensed under +// 3-clause BSD found here: https://raw.githubusercontent.com/epgsql/epgsql/devel/LICENSE +var PostgresTypes; +(function (PostgresTypes) { + PostgresTypes["abstime"] = "abstime"; + PostgresTypes["bool"] = "bool"; + PostgresTypes["date"] = "date"; + PostgresTypes["daterange"] = "daterange"; + PostgresTypes["float4"] = "float4"; + PostgresTypes["float8"] = "float8"; + PostgresTypes["int2"] = "int2"; + PostgresTypes["int4"] = "int4"; + PostgresTypes["int4range"] = "int4range"; + PostgresTypes["int8"] = "int8"; + PostgresTypes["int8range"] = "int8range"; + PostgresTypes["json"] = "json"; + PostgresTypes["jsonb"] = "jsonb"; + PostgresTypes["money"] = "money"; + PostgresTypes["numeric"] = "numeric"; + PostgresTypes["oid"] = "oid"; + PostgresTypes["reltime"] = "reltime"; + PostgresTypes["text"] = "text"; + PostgresTypes["time"] = "time"; + PostgresTypes["timestamp"] = "timestamp"; + PostgresTypes["timestamptz"] = "timestamptz"; + PostgresTypes["timetz"] = "timetz"; + PostgresTypes["tsrange"] = "tsrange"; + PostgresTypes["tstzrange"] = "tstzrange"; +})(PostgresTypes || (exports.PostgresTypes = PostgresTypes = {})); +/** + * Takes an array of columns and an object of string values then converts each string value + * to its mapped type. + * + * @param {{name: String, type: String}[]} columns + * @param {Object} record + * @param {Object} options The map of various options that can be applied to the mapper + * @param {Array} options.skipTypes The array of types that should not be converted + * + * @example convertChangeData([{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age:'33'}, {}) + * //=>{ first_name: 'Paul', age: 33 } + */ +const convertChangeData = (columns, record, options = {}) => { + var _a; + const skipTypes = (_a = options.skipTypes) !== null && _a !== void 0 ? _a : []; + if (!record) { + return {}; + } + return Object.keys(record).reduce((acc, rec_key) => { + acc[rec_key] = (0, exports.convertColumn)(rec_key, columns, record, skipTypes); + return acc; + }, {}); +}; +exports.convertChangeData = convertChangeData; +/** + * Converts the value of an individual column. + * + * @param {String} columnName The column that you want to convert + * @param {{name: String, type: String}[]} columns All of the columns + * @param {Object} record The map of string values + * @param {Array} skipTypes An array of types that should not be converted + * @return {object} Useless information + * + * @example convertColumn('age', [{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age: '33'}, []) + * //=> 33 + * @example convertColumn('age', [{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age: '33'}, ['int4']) + * //=> "33" + */ +const convertColumn = (columnName, columns, record, skipTypes) => { + const column = columns.find((x) => x.name === columnName); + const colType = column === null || column === void 0 ? void 0 : column.type; + const value = record[columnName]; + if (colType && !skipTypes.includes(colType)) { + return (0, exports.convertCell)(colType, value); + } + return noop(value); +}; +exports.convertColumn = convertColumn; +/** + * If the value of the cell is `null`, returns null. + * Otherwise converts the string value to the correct type. + * @param {String} type A postgres column type + * @param {String} value The cell value + * + * @example convertCell('bool', 't') + * //=> true + * @example convertCell('int8', '10') + * //=> 10 + * @example convertCell('_int4', '{1,2,3,4}') + * //=> [1,2,3,4] + */ +const convertCell = (type, value) => { + // if data type is an array + if (type.charAt(0) === '_') { + const dataType = type.slice(1, type.length); + return (0, exports.toArray)(value, dataType); + } + // If not null, convert to correct type. + switch (type) { + case PostgresTypes.bool: + return (0, exports.toBoolean)(value); + case PostgresTypes.float4: + case PostgresTypes.float8: + case PostgresTypes.int2: + case PostgresTypes.int4: + case PostgresTypes.int8: + case PostgresTypes.numeric: + case PostgresTypes.oid: + return (0, exports.toNumber)(value); + case PostgresTypes.json: + case PostgresTypes.jsonb: + return (0, exports.toJson)(value); + case PostgresTypes.timestamp: + return (0, exports.toTimestampString)(value); // Format to be consistent with PostgREST + case PostgresTypes.abstime: // To allow users to cast it based on Timezone + case PostgresTypes.date: // To allow users to cast it based on Timezone + case PostgresTypes.daterange: + case PostgresTypes.int4range: + case PostgresTypes.int8range: + case PostgresTypes.money: + case PostgresTypes.reltime: // To allow users to cast it based on Timezone + case PostgresTypes.text: + case PostgresTypes.time: // To allow users to cast it based on Timezone + case PostgresTypes.timestamptz: // To allow users to cast it based on Timezone + case PostgresTypes.timetz: // To allow users to cast it based on Timezone + case PostgresTypes.tsrange: + case PostgresTypes.tstzrange: + return noop(value); + default: + // Return the value for remaining types + return noop(value); + } +}; +exports.convertCell = convertCell; +const noop = (value) => { + return value; +}; +const toBoolean = (value) => { + switch (value) { + case 't': + return true; + case 'f': + return false; + default: + return value; + } +}; +exports.toBoolean = toBoolean; +const toNumber = (value) => { + if (typeof value === 'string') { + const parsedValue = parseFloat(value); + if (!Number.isNaN(parsedValue)) { + return parsedValue; + } + } + return value; +}; +exports.toNumber = toNumber; +const toJson = (value) => { + if (typeof value === 'string') { + try { + return JSON.parse(value); + } + catch (error) { + console.log(`JSON parse error: ${error}`); + return value; + } + } + return value; +}; +exports.toJson = toJson; +/** + * Converts a Postgres Array into a native JS array + * + * @example toArray('{}', 'int4') + * //=> [] + * @example toArray('{"[2021-01-01,2021-12-31)","(2021-01-01,2021-12-32]"}', 'daterange') + * //=> ['[2021-01-01,2021-12-31)', '(2021-01-01,2021-12-32]'] + * @example toArray([1,2,3,4], 'int4') + * //=> [1,2,3,4] + */ +const toArray = (value, type) => { + if (typeof value !== 'string') { + return value; + } + const lastIdx = value.length - 1; + const closeBrace = value[lastIdx]; + const openBrace = value[0]; + // Confirm value is a Postgres array by checking curly brackets + if (openBrace === '{' && closeBrace === '}') { + let arr; + const valTrim = value.slice(1, lastIdx); + // TODO: find a better solution to separate Postgres array data + try { + arr = JSON.parse('[' + valTrim + ']'); + } + catch (_) { + // WARNING: splitting on comma does not cover all edge cases + arr = valTrim ? valTrim.split(',') : []; + } + return arr.map((val) => (0, exports.convertCell)(type, val)); + } + return value; +}; +exports.toArray = toArray; +/** + * Fixes timestamp to be ISO-8601. Swaps the space between the date and time for a 'T' + * See https://github.com/supabase/supabase/issues/18 + * + * @example toTimestampString('2019-09-10 00:00:00') + * //=> '2019-09-10T00:00:00' + */ +const toTimestampString = (value) => { + if (typeof value === 'string') { + return value.replace(' ', 'T'); + } + return value; +}; +exports.toTimestampString = toTimestampString; +const httpEndpointURL = (socketUrl) => { + const wsUrl = new URL(socketUrl); + wsUrl.protocol = wsUrl.protocol.replace(/^ws/i, 'http'); + wsUrl.pathname = wsUrl.pathname + .replace(/\/+$/, '') // remove all trailing slashes + .replace(/\/socket\/websocket$/i, '') // remove the socket/websocket path + .replace(/\/socket$/i, '') // remove the socket path + .replace(/\/websocket$/i, ''); // remove the websocket path + if (wsUrl.pathname === '' || wsUrl.pathname === '/') { + wsUrl.pathname = '/api/broadcast'; + } + else { + wsUrl.pathname = wsUrl.pathname + '/api/broadcast'; + } + return wsUrl.href; +}; +exports.httpEndpointURL = httpEndpointURL; +//# sourceMappingURL=transformers.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/lib/transformers.js.map b/backend/node_modules/@supabase/realtime-js/dist/main/lib/transformers.js.map new file mode 100644 index 0000000..5303883 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/lib/transformers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"transformers.js","sourceRoot":"","sources":["../../../src/lib/transformers.ts"],"names":[],"mappings":";AAAA;;GAEG;;;AAEH,0EAA0E;AAC1E,yFAAyF;AAEzF,IAAY,aAyBX;AAzBD,WAAY,aAAa;IACvB,oCAAmB,CAAA;IACnB,8BAAa,CAAA;IACb,8BAAa,CAAA;IACb,wCAAuB,CAAA;IACvB,kCAAiB,CAAA;IACjB,kCAAiB,CAAA;IACjB,8BAAa,CAAA;IACb,8BAAa,CAAA;IACb,wCAAuB,CAAA;IACvB,8BAAa,CAAA;IACb,wCAAuB,CAAA;IACvB,8BAAa,CAAA;IACb,gCAAe,CAAA;IACf,gCAAe,CAAA;IACf,oCAAmB,CAAA;IACnB,4BAAW,CAAA;IACX,oCAAmB,CAAA;IACnB,8BAAa,CAAA;IACb,8BAAa,CAAA;IACb,wCAAuB,CAAA;IACvB,4CAA2B,CAAA;IAC3B,kCAAiB,CAAA;IACjB,oCAAmB,CAAA;IACnB,wCAAuB,CAAA;AACzB,CAAC,EAzBW,aAAa,6BAAb,aAAa,QAyBxB;AAgBD;;;;;;;;;;;GAWG;AACI,MAAM,iBAAiB,GAAG,CAC/B,OAAgB,EAChB,MAAqB,EACrB,UAAoC,EAAE,EAC9B,EAAE;;IACV,MAAM,SAAS,GAAG,MAAA,OAAO,CAAC,SAAS,mCAAI,EAAE,CAAA;IAEzC,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,OAAO,E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A;AANY,QAAA,iBAAiB,qBAM7B;AAEM,MAAM,eAAe,GAAG,CAAC,SAAiB,EAAU,EAAE;IAC3D,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,SAAS,CAAC,CAAA;IAEhC,KAAK,CAAC,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC,OAAO,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAEvD,KAAK,CAAC,QAAQ,GAAG,KAAK,CAAC,QAAQ;SAC5B,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,8BAA8B;SAClD,OAAO,CAAC,uBAAuB,EAAE,EAAE,CAAC,CAAC,mCAAmC;SACxE,OAAO,CAAC,YAAY,EAAE,EAAE,CAAC,CAAC,yBAAyB;SACnD,OAAO,CAAC,eAAe,EAAE,EAAE,CAAC,CAAA,CAAC,4BAA4B;IAE5D,IAAI,KAAK,CAAC,QAAQ,KAAK,EAAE,IAAI,KAAK,CAAC,QAAQ,KAAK,GAAG,EAAE,CAAC;QACpD,KAAK,CAAC,QAAQ,GAAG,gBAAgB,CAAA;IACnC,CAAC;SAAM,CAAC;QACN,KAAK,CAAC,QAAQ,GAAG,KAAK,CAAC,QAAQ,GAAG,gBAAgB,CAAA;IACpD,CAAC;IAED,OAAO,KAAK,CAAC,IAAI,CAAA;AACnB,CAAC,CAAA;AAlBY,QAAA,eAAe,mBAkB3B"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/lib/version.d.ts b/backend/node_modules/@supabase/realtime-js/dist/main/lib/version.d.ts new file mode 100644 index 0000000..da11aac --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/lib/version.d.ts @@ -0,0 +1,2 @@ +export declare const version = "2.87.1"; +//# sourceMappingURL=version.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/lib/version.d.ts.map b/backend/node_modules/@supabase/realtime-js/dist/main/lib/version.d.ts.map new file mode 100644 index 0000000..a4c2b72 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/lib/version.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,OAAO,WAAW,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/lib/version.js b/backend/node_modules/@supabase/realtime-js/dist/main/lib/version.js new file mode 100644 index 0000000..31bcb0a --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/lib/version.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.version = void 0; +// Generated automatically during releases by scripts/update-version-files.ts +// This file provides runtime access to the package version for: +// - HTTP request headers (e.g., X-Client-Info header for API requests) +// - Debugging and support (identifying which version is running) +// - Telemetry and logging (version reporting in errors/analytics) +// - Ensuring build artifacts match the published package version +exports.version = '2.87.1'; +//# sourceMappingURL=version.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/lib/version.js.map b/backend/node_modules/@supabase/realtime-js/dist/main/lib/version.js.map new file mode 100644 index 0000000..e9f984c --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/lib/version.js.map @@ -0,0 +1 @@ +{"version":3,"file":"version.js","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":";;;AAAA,6EAA6E;AAC7E,gEAAgE;AAChE,uEAAuE;AACvE,iEAAiE;AACjE,kEAAkE;AAClE,iEAAiE;AACpD,QAAA,OAAO,GAAG,QAAQ,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/lib/websocket-factory.d.ts b/backend/node_modules/@supabase/realtime-js/dist/main/lib/websocket-factory.d.ts new file mode 100644 index 0000000..3a19990 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/lib/websocket-factory.d.ts @@ -0,0 +1,81 @@ +export interface WebSocketLike { + readonly CONNECTING: number; + readonly OPEN: number; + readonly CLOSING: number; + readonly CLOSED: number; + readonly readyState: number; + readonly url: string; + readonly protocol: string; + /** + * Closes the socket, optionally providing a close code and reason. + */ + close(code?: number, reason?: string): void; + /** + * Sends data through the socket using the underlying implementation. + */ + send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void; + onopen: ((this: any, ev: Event) => any) | null; + onmessage: ((this: any, ev: MessageEvent) => any) | null; + onclose: ((this: any, ev: CloseEvent) => any) | null; + onerror: ((this: any, ev: Event) => any) | null; + /** + * Registers an event listener on the socket (compatible with browser WebSocket API). + */ + addEventListener(type: string, listener: EventListener): void; + /** + * Removes a previously registered event listener. + */ + removeEventListener(type: string, listener: EventListener): void; + binaryType?: string; + bufferedAmount?: number; + extensions?: string; + dispatchEvent?: (event: Event) => boolean; +} +export interface WebSocketEnvironment { + type: 'native' | 'ws' | 'cloudflare' | 'unsupported'; + constructor?: any; + error?: string; + workaround?: string; +} +/** + * Utilities for creating WebSocket instances across runtimes. + */ +export declare class WebSocketFactory { + /** + * Static-only utility – prevent instantiation. + */ + private constructor(); + private static detectEnvironment; + /** + * Returns the best available WebSocket constructor for the current runtime. + * + * @example + * ```ts + * const WS = WebSocketFactory.getWebSocketConstructor() + * const socket = new WS('wss://realtime.supabase.co/socket') + * ``` + */ + static getWebSocketConstructor(): typeof WebSocket; + /** + * Creates a WebSocket using the detected constructor. + * + * @example + * ```ts + * const socket = WebSocketFactory.createWebSocket('wss://realtime.supabase.co/socket') + * ``` + */ + static createWebSocket(url: string | URL, protocols?: string | string[]): WebSocketLike; + /** + * Detects whether the runtime can establish WebSocket connections. + * + * @example + * ```ts + * if (!WebSocketFactory.isWebSocketSupported()) { + * console.warn('Falling back to long polling') + * } + * ``` + */ + static isWebSocketSupported(): boolean; +} +export default WebSocketFactory; +//# sourceMappingURL=websocket-factory.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/lib/websocket-factory.d.ts.map b/backend/node_modules/@supabase/realtime-js/dist/main/lib/websocket-factory.d.ts.map new file mode 100644 index 0000000..b045f0b --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/lib/websocket-factory.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"websocket-factory.d.ts","sourceRoot":"","sources":["../../../src/lib/websocket-factory.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAA;IAC3B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;IACxB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAA;IAC3B,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAA;IACpB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAA;IAEzB;;OAEG;IACH,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IAC3C;;OAEG;IACH,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,eAAe,GAAG,IAAI,GAAG,eAAe,GAAG,IAAI,CAAA;IAEnE,MAAM,EAAE,CAAC,CAAC,IAAI,EAAE,GAAG,EAAE,EAAE,EAAE,KAAK,KAAK,GAAG,CAAC,GAAG,IAAI,CAAA;IAC9C,SAAS,EAAE,CAAC,CAAC,IAAI,EAAE,GAAG,EAAE,EAAE,EAAE,YAAY,KAAK,GAAG,CAAC,GAAG,IAAI,CAAA;IACxD,OAAO,EAAE,CAAC,CAAC,IAAI,EAAE,GAAG,EAAE,EAAE,EAAE,UAAU,KAAK,GAAG,CAAC,GAAG,IAAI,CAAA;IACpD,OAAO,EAAE,CAAC,CAAC,IAAI,EAAE,GAAG,EAAE,EAAE,EAAE,KAAK,KAAK,GAAG,CAAC,GAAG,IAAI,CAAA;IAE/C;;OAEG;IACH,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,aAAa,GAAG,IAAI,CAAA;IAC7D;;OAEG;IACH,mBAAmB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,aAAa,GAAG,IAAI,CAAA;IAGhE,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,aAAa,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,OAAO,CAAA;CAC1C;AAED,MAAM,WAAW,oBAAoB;IACnC,IAAI,EAAE,QAAQ,GAAG,IAAI,GAAG,YAAY,GAAG,aAAa,CAAA;IACpD,WAAW,CAAC,EAAE,GAAG,CAAA;IACjB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,UAAU,CAAC,EAAE,MAAM,CAAA;CACpB;AAED;;GAEG;AACH,qBAAa,gBAAgB;IAC3B;;OAEG;IACH,OAAO;IACP,OAAO,CAAC,MAAM,CAAC,iBAAiB;IAkFhC;;;;;;;;OAQG;WACW,uBAAuB,IAAI,OAAO,SAAS;IAYzD;;;;;;;OAOG;WACW,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,aAAa;IAK9F;;;;;;;;;OASG;WACW,oBAAoB,IAAI,OAAO;CAQ9C;AAED,eAAe,gBAAgB,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/lib/websocket-factory.js b/backend/node_modules/@supabase/realtime-js/dist/main/lib/websocket-factory.js new file mode 100644 index 0000000..34f4bda --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/lib/websocket-factory.js @@ -0,0 +1,130 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WebSocketFactory = void 0; +/** + * Utilities for creating WebSocket instances across runtimes. + */ +class WebSocketFactory { + /** + * Static-only utility – prevent instantiation. + */ + constructor() { } + static detectEnvironment() { + var _a; + if (typeof WebSocket !== 'undefined') { + return { type: 'native', constructor: WebSocket }; + } + if (typeof globalThis !== 'undefined' && typeof globalThis.WebSocket !== 'undefined') { + return { type: 'native', constructor: globalThis.WebSocket }; + } + if (typeof global !== 'undefined' && typeof global.WebSocket !== 'undefined') { + return { type: 'native', constructor: global.WebSocket }; + } + if (typeof globalThis !== 'undefined' && + typeof globalThis.WebSocketPair !== 'undefined' && + typeof globalThis.WebSocket === 'undefined') { + return { + type: 'cloudflare', + error: 'Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.', + workaround: 'Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime.', + }; + } + if ((typeof globalThis !== 'undefined' && globalThis.EdgeRuntime) || + (typeof navigator !== 'undefined' && ((_a = navigator.userAgent) === null || _a === void 0 ? void 0 : _a.includes('Vercel-Edge')))) { + return { + type: 'unsupported', + error: 'Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.', + workaround: 'Use serverless functions or a different deployment target for WebSocket functionality.', + }; + } + if (typeof process !== 'undefined') { + // Use dynamic property access to avoid Next.js Edge Runtime static analysis warnings + const processVersions = process['versions']; + if (processVersions && processVersions['node']) { + // Remove 'v' prefix if present and parse the major version + const versionString = processVersions['node']; + const nodeVersion = parseInt(versionString.replace(/^v/, '').split('.')[0]); + // Node.js 22+ should have native WebSocket + if (nodeVersion >= 22) { + // Check if native WebSocket is available (should be in Node.js 22+) + if (typeof globalThis.WebSocket !== 'undefined') { + return { type: 'native', constructor: globalThis.WebSocket }; + } + // If not available, user needs to provide it + return { + type: 'unsupported', + error: `Node.js ${nodeVersion} detected but native WebSocket not found.`, + workaround: 'Provide a WebSocket implementation via the transport option.', + }; + } + // Node.js < 22 doesn't have native WebSocket + return { + type: 'unsupported', + error: `Node.js ${nodeVersion} detected without native WebSocket support.`, + workaround: 'For Node.js < 22, install "ws" package and provide it via the transport option:\n' + + 'import ws from "ws"\n' + + 'new RealtimeClient(url, { transport: ws })', + }; + } + } + return { + type: 'unsupported', + error: 'Unknown JavaScript runtime without WebSocket support.', + workaround: "Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation.", + }; + } + /** + * Returns the best available WebSocket constructor for the current runtime. + * + * @example + * ```ts + * const WS = WebSocketFactory.getWebSocketConstructor() + * const socket = new WS('wss://realtime.supabase.co/socket') + * ``` + */ + static getWebSocketConstructor() { + const env = this.detectEnvironment(); + if (env.constructor) { + return env.constructor; + } + let errorMessage = env.error || 'WebSocket not supported in this environment.'; + if (env.workaround) { + errorMessage += `\n\nSuggested solution: ${env.workaround}`; + } + throw new Error(errorMessage); + } + /** + * Creates a WebSocket using the detected constructor. + * + * @example + * ```ts + * const socket = WebSocketFactory.createWebSocket('wss://realtime.supabase.co/socket') + * ``` + */ + static createWebSocket(url, protocols) { + const WS = this.getWebSocketConstructor(); + return new WS(url, protocols); + } + /** + * Detects whether the runtime can establish WebSocket connections. + * + * @example + * ```ts + * if (!WebSocketFactory.isWebSocketSupported()) { + * console.warn('Falling back to long polling') + * } + * ``` + */ + static isWebSocketSupported() { + try { + const env = this.detectEnvironment(); + return env.type === 'native' || env.type === 'ws'; + } + catch (_a) { + return false; + } + } +} +exports.WebSocketFactory = WebSocketFactory; +exports.default = WebSocketFactory; +//# sourceMappingURL=websocket-factory.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/main/lib/websocket-factory.js.map b/backend/node_modules/@supabase/realtime-js/dist/main/lib/websocket-factory.js.map new file mode 100644 index 0000000..17fd9e1 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/main/lib/websocket-factory.js.map @@ -0,0 +1 @@ +{"version":3,"file":"websocket-factory.js","sourceRoot":"","sources":["../../../src/lib/websocket-factory.ts"],"names":[],"mappings":";;;AA8CA;;GAEG;AACH,MAAa,gBAAgB;IAC3B;;OAEG;IACH,gBAAuB,CAAC;IAChB,MAAM,CAAC,iBAAiB;;QAC9B,IAAI,OAAO,S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AU,EAAE,CAAA;QAC7D,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,YAAY,CAAC,CAAA;IAC/B,CAAC;IAED;;;;;;;OAOG;IACI,MAAM,CAAC,eAAe,CAAC,GAAiB,EAAE,SAA6B;QAC5E,MAAM,EAAE,GAAG,IAAI,CAAC,uBAAuB,EAAE,CAAA;QACzC,OAAO,IAAI,EAAE,CAAC,GAAG,EAAE,SAAS,CAAC,CAAA;IAC/B,CAAC;IAED;;;;;;;;;OASG;IACI,MAAM,CAAC,oBAAoB;QAChC,IAAI,CAAC;YACH,MAAM,GAAG,GAAG,IAAI,CAAC,iBAAiB,EAAE,CAAA;YACpC,OAAO,GAAG,CAAC,IAAI,KAAK,QAAQ,IAAI,GAAG,CAAC,IAAI,KAAK,IAAI,CAAA;QACnD,CAAC;QAAC,WAAM,CAAC;YACP,OAAO,KAAK,CAAA;QACd,CAAC;IACH,CAAC;CACF;AA3ID,4CA2IC;AAED,kBAAe,gBAAgB,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/RealtimeChannel.d.ts b/backend/node_modules/@supabase/realtime-js/dist/module/RealtimeChannel.d.ts new file mode 100644 index 0000000..f3ddaf7 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/RealtimeChannel.d.ts @@ -0,0 +1,367 @@ +import { CHANNEL_STATES } from './lib/constants'; +import Push from './lib/push'; +import type RealtimeClient from './RealtimeClient'; +import Timer from './lib/timer'; +import RealtimePresence, { REALTIME_PRESENCE_LISTEN_EVENTS } from './RealtimePresence'; +import type { RealtimePresenceJoinPayload, RealtimePresenceLeavePayload, RealtimePresenceState } from './RealtimePresence'; +type ReplayOption = { + since: number; + limit?: number; +}; +export type RealtimeChannelOptions = { + config: { + /** + * self option enables client to receive message it broadcast + * ack option instructs server to acknowledge that broadcast message was received + * replay option instructs server to replay broadcast messages + */ + broadcast?: { + self?: boolean; + ack?: boolean; + replay?: ReplayOption; + }; + /** + * key option is used to track presence payload across clients + */ + presence?: { + key?: string; + enabled?: boolean; + }; + /** + * defines if the channel is private or not and if RLS policies will be used to check data + */ + private?: boolean; + }; +}; +type RealtimeChangesPayloadBase = { + schema: string; + table: string; +}; +type RealtimeBroadcastChangesPayloadBase = RealtimeChangesPayloadBase & { + id: string; +}; +export type RealtimeBroadcastInsertPayload = RealtimeBroadcastChangesPayloadBase & { + operation: `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.INSERT}`; + record: T; + old_record: null; +}; +export type RealtimeBroadcastUpdatePayload = RealtimeBroadcastChangesPayloadBase & { + operation: `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.UPDATE}`; + record: T; + old_record: T; +}; +export type RealtimeBroadcastDeletePayload = RealtimeBroadcastChangesPayloadBase & { + operation: `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE}`; + record: null; + old_record: T; +}; +export type RealtimeBroadcastPayload = RealtimeBroadcastInsertPayload | RealtimeBroadcastUpdatePayload | RealtimeBroadcastDeletePayload; +type RealtimePostgresChangesPayloadBase = { + schema: string; + table: string; + commit_timestamp: string; + errors: string[]; +}; +export type RealtimePostgresInsertPayload = RealtimePostgresChangesPayloadBase & { + eventType: `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.INSERT}`; + new: T; + old: {}; +}; +export type RealtimePostgresUpdatePayload = RealtimePostgresChangesPayloadBase & { + eventType: `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.UPDATE}`; + new: T; + old: Partial; +}; +export type RealtimePostgresDeletePayload = RealtimePostgresChangesPayloadBase & { + eventType: `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE}`; + new: {}; + old: Partial; +}; +export type RealtimePostgresChangesPayload = RealtimePostgresInsertPayload | RealtimePostgresUpdatePayload | RealtimePostgresDeletePayload; +export type RealtimePostgresChangesFilter = { + /** + * The type of database change to listen to. + */ + event: T; + /** + * The database schema to listen to. + */ + schema: string; + /** + * The database table to listen to. + */ + table?: string; + /** + * Receive database changes when filter is matched. + */ + filter?: string; +}; +export type RealtimeChannelSendResponse = 'ok' | 'timed out' | 'error'; +export declare enum REALTIME_POSTGRES_CHANGES_LISTEN_EVENT { + ALL = "*", + INSERT = "INSERT", + UPDATE = "UPDATE", + DELETE = "DELETE" +} +export declare enum REALTIME_LISTEN_TYPES { + BROADCAST = "broadcast", + PRESENCE = "presence", + POSTGRES_CHANGES = "postgres_changes", + SYSTEM = "system" +} +export declare enum REALTIME_SUBSCRIBE_STATES { + SUBSCRIBED = "SUBSCRIBED", + TIMED_OUT = "TIMED_OUT", + CLOSED = "CLOSED", + CHANNEL_ERROR = "CHANNEL_ERROR" +} +export declare const REALTIME_CHANNEL_STATES: typeof CHANNEL_STATES; +/** A channel is the basic building block of Realtime + * and narrows the scope of data flow to subscribed clients. + * You can think of a channel as a chatroom where participants are able to see who's online + * and send and receive messages. + */ +export default class RealtimeChannel { + /** Topic name can be any string. */ + topic: string; + params: RealtimeChannelOptions; + socket: RealtimeClient; + bindings: { + [key: string]: { + type: string; + filter: { + [key: string]: any; + }; + callback: Function; + id?: string; + }[]; + }; + timeout: number; + state: CHANNEL_STATES; + joinedOnce: boolean; + joinPush: Push; + rejoinTimer: Timer; + pushBuffer: Push[]; + presence: RealtimePresence; + broadcastEndpointURL: string; + subTopic: string; + private: boolean; + /** + * Creates a channel that can broadcast messages, sync presence, and listen to Postgres changes. + * + * The topic determines which realtime stream you are subscribing to. Config options let you + * enable acknowledgement for broadcasts, presence tracking, or private channels. + * + * @example + * ```ts + * import RealtimeClient from '@supabase/realtime-js' + * + * const client = new RealtimeClient('https://xyzcompany.supabase.co/realtime/v1', { + * params: { apikey: 'public-anon-key' }, + * }) + * const channel = new RealtimeChannel('realtime:public:messages', { config: {} }, client) + * ``` + */ + constructor( + /** Topic name can be any string. */ + topic: string, params: RealtimeChannelOptions | undefined, socket: RealtimeClient); + /** Subscribe registers your client with the server */ + subscribe(callback?: (status: REALTIME_SUBSCRIBE_STATES, err?: Error) => void, timeout?: number): RealtimeChannel; + /** + * Returns the current presence state for this channel. + * + * The shape is a map keyed by presence key (for example a user id) where each entry contains the + * tracked metadata for that user. + */ + presenceState(): RealtimePresenceState; + /** + * Sends the supplied payload to the presence tracker so other subscribers can see that this + * client is online. Use `untrack` to stop broadcasting presence for the same key. + */ + track(payload: { + [key: string]: any; + }, opts?: { + [key: string]: any; + }): Promise; + /** + * Removes the current presence state for this client. + */ + untrack(opts?: { + [key: string]: any; + }): Promise; + /** + * Creates an event handler that listens to changes. + */ + on(type: `${REALTIME_LISTEN_TYPES.PRESENCE}`, filter: { + event: `${REALTIME_PRESENCE_LISTEN_EVENTS.SYNC}`; + }, callback: () => void): RealtimeChannel; + on(type: `${REALTIME_LISTEN_TYPES.PRESENCE}`, filter: { + event: `${REALTIME_PRESENCE_LISTEN_EVENTS.JOIN}`; + }, callback: (payload: RealtimePresenceJoinPayload) => void): RealtimeChannel; + on(type: `${REALTIME_LISTEN_TYPES.PRESENCE}`, filter: { + event: `${REALTIME_PRESENCE_LISTEN_EVENTS.LEAVE}`; + }, callback: (payload: RealtimePresenceLeavePayload) => void): RealtimeChannel; + on(type: `${REALTIME_LISTEN_TYPES.POSTGRES_CHANGES}`, filter: RealtimePostgresChangesFilter<`${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.ALL}`>, callback: (payload: RealtimePostgresChangesPayload) => void): RealtimeChannel; + on(type: `${REALTIME_LISTEN_TYPES.POSTGRES_CHANGES}`, filter: RealtimePostgresChangesFilter<`${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.INSERT}`>, callback: (payload: RealtimePostgresInsertPayload) => void): RealtimeChannel; + on(type: `${REALTIME_LISTEN_TYPES.POSTGRES_CHANGES}`, filter: RealtimePostgresChangesFilter<`${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.UPDATE}`>, callback: (payload: RealtimePostgresUpdatePayload) => void): RealtimeChannel; + on(type: `${REALTIME_LISTEN_TYPES.POSTGRES_CHANGES}`, filter: RealtimePostgresChangesFilter<`${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE}`>, callback: (payload: RealtimePostgresDeletePayload) => void): RealtimeChannel; + /** + * The following is placed here to display on supabase.com/docs/reference/javascript/subscribe. + * @param type One of "broadcast", "presence", or "postgres_changes". + * @param filter Custom object specific to the Realtime feature detailing which payloads to receive. + * @param callback Function to be invoked when event handler is triggered. + */ + on(type: `${REALTIME_LISTEN_TYPES.BROADCAST}`, filter: { + event: string; + }, callback: (payload: { + type: `${REALTIME_LISTEN_TYPES.BROADCAST}`; + event: string; + meta?: { + replayed?: boolean; + id: string; + }; + [key: string]: any; + }) => void): RealtimeChannel; + on(type: `${REALTIME_LISTEN_TYPES.BROADCAST}`, filter: { + event: string; + }, callback: (payload: { + type: `${REALTIME_LISTEN_TYPES.BROADCAST}`; + event: string; + meta?: { + replayed?: boolean; + id: string; + }; + payload: T; + }) => void): RealtimeChannel; + on>(type: `${REALTIME_LISTEN_TYPES.BROADCAST}`, filter: { + event: REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.ALL; + }, callback: (payload: { + type: `${REALTIME_LISTEN_TYPES.BROADCAST}`; + event: REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.ALL; + payload: RealtimeBroadcastPayload; + }) => void): RealtimeChannel; + on(type: `${REALTIME_LISTEN_TYPES.BROADCAST}`, filter: { + event: REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.INSERT; + }, callback: (payload: { + type: `${REALTIME_LISTEN_TYPES.BROADCAST}`; + event: REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.INSERT; + payload: RealtimeBroadcastInsertPayload; + }) => void): RealtimeChannel; + on(type: `${REALTIME_LISTEN_TYPES.BROADCAST}`, filter: { + event: REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.UPDATE; + }, callback: (payload: { + type: `${REALTIME_LISTEN_TYPES.BROADCAST}`; + event: REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.UPDATE; + payload: RealtimeBroadcastUpdatePayload; + }) => void): RealtimeChannel; + on(type: `${REALTIME_LISTEN_TYPES.BROADCAST}`, filter: { + event: REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE; + }, callback: (payload: { + type: `${REALTIME_LISTEN_TYPES.BROADCAST}`; + event: REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE; + payload: RealtimeBroadcastDeletePayload; + }) => void): RealtimeChannel; + on(type: `${REALTIME_LISTEN_TYPES.SYSTEM}`, filter: {}, callback: (payload: any) => void): RealtimeChannel; + /** + * Sends a broadcast message explicitly via REST API. + * + * This method always uses the REST API endpoint regardless of WebSocket connection state. + * Useful when you want to guarantee REST delivery or when gradually migrating from implicit REST fallback. + * + * @param event The name of the broadcast event + * @param payload Payload to be sent (required) + * @param opts Options including timeout + * @returns Promise resolving to object with success status, and error details if failed + */ + httpSend(event: string, payload: any, opts?: { + timeout?: number; + }): Promise<{ + success: true; + } | { + success: false; + status: number; + error: string; + }>; + /** + * Sends a message into the channel. + * + * @param args Arguments to send to channel + * @param args.type The type of event to send + * @param args.event The name of the event being sent + * @param args.payload Payload to be sent + * @param opts Options to be used during the send process + */ + send(args: { + type: 'broadcast' | 'presence' | 'postgres_changes'; + event: string; + payload?: any; + [key: string]: any; + }, opts?: { + [key: string]: any; + }): Promise; + /** + * Updates the payload that will be sent the next time the channel joins (reconnects). + * Useful for rotating access tokens or updating config without re-creating the channel. + */ + updateJoinPayload(payload: { + [key: string]: any; + }): void; + /** + * Leaves the channel. + * + * Unsubscribes from server events, and instructs channel to terminate on server. + * Triggers onClose() hooks. + * + * To receive leave acknowledgements, use the a `receive` hook to bind to the server ack, ie: + * channel.unsubscribe().receive("ok", () => alert("left!") ) + */ + unsubscribe(timeout?: number): Promise<'ok' | 'timed out' | 'error'>; + /** + * Teardown the channel. + * + * Destroys and stops related timers. + */ + teardown(): void; +} +export {}; +//# sourceMappingURL=RealtimeChannel.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/RealtimeChannel.d.ts.map b/backend/node_modules/@supabase/realtime-js/dist/module/RealtimeChannel.d.ts.map new file mode 100644 index 0000000..e613d7b --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/RealtimeChannel.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"RealtimeChannel.d.ts","sourceRoot":"","sources":["../../src/RealtimeChannel.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,cAAc,EAAwB,MAAM,iBAAiB,CAAA;AACtF,OAAO,IAAI,MAAM,YAAY,CAAA;AAC7B,OAAO,KAAK,cAAc,MAAM,kBAAkB,CAAA;AAClD,OAAO,KAAK,MAAM,aAAa,CAAA;AAC/B,OAAO,gBAAgB,EAAE,EAAE,+BAA+B,EAAE,MAAM,oBAAoB,CAAA;AACtF,OAAO,KAAK,EACV,2BAA2B,EAC3B,4BAA4B,EAC5B,qBAAqB,EACtB,MAAM,oBAAoB,CAAA;AAI3B,KAAK,YAAY,GAAG;IAClB,KAAK,EAAE,MAAM,CAAA;IACb,KAAK,CAAC,EAAE,MAAM,CAAA;CACf,CAAA;AAED,MAAM,MAAM,sBAAsB,GAAG;IACnC,MAAM,EAAE;QACN;;;;WAIG;QACH,SAAS,CAAC,EAAE;YAAE,IAAI,CAAC,EAAE,OAAO,CAAC;YAAC,GAAG,CAAC,EAAE,OAAO,CAAC;YAAC,MAAM,CAAC,EAAE,YAAY,CAAA;SAAE,CAAA;QACpE;;WAEG;QACH,QAAQ,CAAC,EAAE;YAAE,GAAG,CAAC,EAAE,MAAM,CAAC;YAAC,OAAO,CAAC,EAAE,OAAO,CAAA;SAAE,CAAA;QAC9C;;WAEG;QACH,OAAO,CAAC,EAAE,OAAO,CAAA;KAClB,CAAA;CACF,CAAA;AAED,KAAK,0BAA0B,GAAG;IAChC,MAAM,EAAE,MAAM,CAAA;IACd,KAAK,EAAE,MAAM,CAAA;CACd,CAAA;AAED,KAAK,mCAAmC,GAAG,0BAA0B,GAAG;IACtE,EAAE,EAAE,MAAM,C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O,SAAe,GAAG,OAAO,CAAC,IAAI,GAAG,WAAW,GAAG,OAAO,CAAC;IAkC1E;;;;OAIG;IACH,QAAQ;CAqST"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/RealtimeChannel.js b/backend/node_modules/@supabase/realtime-js/dist/module/RealtimeChannel.js new file mode 100644 index 0000000..909d0da --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/RealtimeChannel.js @@ -0,0 +1,639 @@ +import { CHANNEL_EVENTS, CHANNEL_STATES, MAX_PUSH_BUFFER_SIZE } from './lib/constants'; +import Push from './lib/push'; +import Timer from './lib/timer'; +import RealtimePresence from './RealtimePresence'; +import * as Transformers from './lib/transformers'; +import { httpEndpointURL } from './lib/transformers'; +export var REALTIME_POSTGRES_CHANGES_LISTEN_EVENT; +(function (REALTIME_POSTGRES_CHANGES_LISTEN_EVENT) { + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["ALL"] = "*"; + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["INSERT"] = "INSERT"; + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["UPDATE"] = "UPDATE"; + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["DELETE"] = "DELETE"; +})(REALTIME_POSTGRES_CHANGES_LISTEN_EVENT || (REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = {})); +export var REALTIME_LISTEN_TYPES; +(function (REALTIME_LISTEN_TYPES) { + REALTIME_LISTEN_TYPES["BROADCAST"] = "broadcast"; + REALTIME_LISTEN_TYPES["PRESENCE"] = "presence"; + REALTIME_LISTEN_TYPES["POSTGRES_CHANGES"] = "postgres_changes"; + REALTIME_LISTEN_TYPES["SYSTEM"] = "system"; +})(REALTIME_LISTEN_TYPES || (REALTIME_LISTEN_TYPES = {})); +export var REALTIME_SUBSCRIBE_STATES; +(function (REALTIME_SUBSCRIBE_STATES) { + REALTIME_SUBSCRIBE_STATES["SUBSCRIBED"] = "SUBSCRIBED"; + REALTIME_SUBSCRIBE_STATES["TIMED_OUT"] = "TIMED_OUT"; + REALTIME_SUBSCRIBE_STATES["CLOSED"] = "CLOSED"; + REALTIME_SUBSCRIBE_STATES["CHANNEL_ERROR"] = "CHANNEL_ERROR"; +})(REALTIME_SUBSCRIBE_STATES || (REALTIME_SUBSCRIBE_STATES = {})); +export const REALTIME_CHANNEL_STATES = CHANNEL_STATES; +/** A channel is the basic building block of Realtime + * and narrows the scope of data flow to subscribed clients. + * You can think of a channel as a chatroom where participants are able to see who's online + * and send and receive messages. + */ +export default class RealtimeChannel { + /** + * Creates a channel that can broadcast messages, sync presence, and listen to Postgres changes. + * + * The topic determines which realtime stream you are subscribing to. Config options let you + * enable acknowledgement for broadcasts, presence tracking, or private channels. + * + * @example + * ```ts + * import RealtimeClient from '@supabase/realtime-js' + * + * const client = new RealtimeClient('https://xyzcompany.supabase.co/realtime/v1', { + * params: { apikey: 'public-anon-key' }, + * }) + * const channel = new RealtimeChannel('realtime:public:messages', { config: {} }, client) + * ``` + */ + constructor( + /** Topic name can be any string. */ + topic, params = { config: {} }, socket) { + var _a, _b; + this.topic = topic; + this.params = params; + this.socket = socket; + this.bindings = {}; + this.state = CHANNEL_STATES.closed; + this.joinedOnce = false; + this.pushBuffer = []; + this.subTopic = topic.replace(/^realtime:/i, ''); + this.params.config = Object.assign({ + broadcast: { ack: false, self: false }, + presence: { key: '', enabled: false }, + private: false, + }, params.config); + this.timeout = this.socket.timeout; + this.joinPush = new Push(this, CHANNEL_EVENTS.join, this.params, this.timeout); + this.rejoinTimer = new Timer(() => this._rejoinUntilConnected(), this.socket.reconnectAfterMs); + this.joinPush.receive('ok', () => { + this.state = CHANNEL_STATES.joined; + this.rejoinTimer.reset(); + this.pushBuffer.forEach((pushEvent) => pushEvent.send()); + this.pushBuffer = []; + }); + this._onClose(() => { + this.rejoinTimer.reset(); + this.socket.log('channel', `close ${this.topic} ${this._joinRef()}`); + this.state = CHANNEL_STATES.closed; + this.socket._remove(this); + }); + this._onError((reason) => { + if (this._isLeaving() || this._isClosed()) { + return; + } + this.socket.log('channel', `error ${this.topic}`, reason); + this.state = CHANNEL_STATES.errored; + this.rejoinTimer.scheduleTimeout(); + }); + this.joinPush.receive('timeout', () => { + if (!this._isJoining()) { + return; + } + this.socket.log('channel', `timeout ${this.topic}`, this.joinPush.timeout); + this.state = CHANNEL_STATES.errored; + this.rejoinTimer.scheduleTimeout(); + }); + this.joinPush.receive('error', (reason) => { + if (this._isLeaving() || this._isClosed()) { + return; + } + this.socket.log('channel', `error ${this.topic}`, reason); + this.state = CHANNEL_STATES.errored; + this.rejoinTimer.scheduleTimeout(); + }); + this._on(CHANNEL_EVENTS.reply, {}, (payload, ref) => { + this._trigger(this._replyEventName(ref), payload); + }); + this.presence = new RealtimePresence(this); + this.broadcastEndpointURL = httpEndpointURL(this.socket.endPoint); + this.private = this.params.config.private || false; + if (!this.private && ((_b = (_a = this.params.config) === null || _a === void 0 ? void 0 : _a.broadcast) === null || _b === void 0 ? void 0 : _b.replay)) { + throw `tried to use replay on public channel '${this.topic}'. It must be a private channel.`; + } + } + /** Subscribe registers your client with the server */ + subscribe(callback, timeout = this.timeout) { + var _a, _b, _c; + if (!this.socket.isConnected()) { + this.socket.connect(); + } + if (this.state == CHANNEL_STATES.closed) { + const { config: { broadcast, presence, private: isPrivate }, } = this.params; + const postgres_changes = (_b = (_a = this.bindings.postgres_changes) === null || _a === void 0 ? void 0 : _a.map((r) => r.filter)) !== null && _b !== void 0 ? _b : []; + const presence_enabled = (!!this.bindings[REALTIME_LISTEN_TYPES.PRESENCE] && + this.bindings[REALTIME_LISTEN_TYPES.PRESENCE].length > 0) || + ((_c = this.params.config.presence) === null || _c === void 0 ? void 0 : _c.enabled) === true; + const accessTokenPayload = {}; + const config = { + broadcast, + presence: Object.assign(Object.assign({}, presence), { enabled: presence_enabled }), + postgres_changes, + private: isPrivate, + }; + if (this.socket.accessTokenValue) { + accessTokenPayload.access_token = this.socket.accessTokenValue; + } + this._onError((e) => callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR, e)); + this._onClose(() => callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.CLOSED)); + this.updateJoinPayload(Object.assign({ config }, accessTokenPayload)); + this.joinedOnce = true; + this._rejoin(timeout); + this.joinPush + .receive('ok', async ({ postgres_changes }) => { + var _a; + // Only refresh auth if using callback-based tokens + if (!this.socket._isManualToken()) { + this.socket.setAuth(); + } + if (postgres_changes === undefined) { + callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.SUBSCRIBED); + return; + } + else { + const clientPostgresBindings = this.bindings.postgres_changes; + const bindingsLen = (_a = clientPostgresBindings === null || clientPostgresBindings === void 0 ? void 0 : clientPostgresBindings.length) !== null && _a !== void 0 ? _a : 0; + const newPostgresBindings = []; + for (let i = 0; i < bindingsLen; i++) { + const clientPostgresBinding = clientPostgresBindings[i]; + const { filter: { event, schema, table, filter }, } = clientPostgresBinding; + const serverPostgresFilter = postgres_changes && postgres_changes[i]; + if (serverPostgresFilter && + serverPostgresFilter.event === event && + RealtimeChannel.isFilterValueEqual(serverPostgresFilter.schema, schema) && + RealtimeChannel.isFilterValueEqual(serverPostgresFilter.table, table) && + RealtimeChannel.isFilterValueEqual(serverPostgresFilter.filter, filter)) { + newPostgresBindings.push(Object.assign(Object.assign({}, clientPostgresBinding), { id: serverPostgresFilter.id })); + } + else { + this.unsubscribe(); + this.state = CHANNEL_STATES.errored; + callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR, new Error('mismatch between server and client bindings for postgres changes')); + return; + } + } + this.bindings.postgres_changes = newPostgresBindings; + callback && callback(REALTIME_SUBSCRIBE_STATES.SUBSCRIBED); + return; + } + }) + .receive('error', (error) => { + this.state = CHANNEL_STATES.errored; + callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR, new Error(JSON.stringify(Object.values(error).join(', ') || 'error'))); + return; + }) + .receive('timeout', () => { + callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.TIMED_OUT); + return; + }); + } + return this; + } + /** + * Returns the current presence state for this channel. + * + * The shape is a map keyed by presence key (for example a user id) where each entry contains the + * tracked metadata for that user. + */ + presenceState() { + return this.presence.state; + } + /** + * Sends the supplied payload to the presence tracker so other subscribers can see that this + * client is online. Use `untrack` to stop broadcasting presence for the same key. + */ + async track(payload, opts = {}) { + return await this.send({ + type: 'presence', + event: 'track', + payload, + }, opts.timeout || this.timeout); + } + /** + * Removes the current presence state for this client. + */ + async untrack(opts = {}) { + return await this.send({ + type: 'presence', + event: 'untrack', + }, opts); + } + on(type, filter, callback) { + if (this.state === CHANNEL_STATES.joined && type === REALTIME_LISTEN_TYPES.PRESENCE) { + this.socket.log('channel', `resubscribe to ${this.topic} due to change in presence callbacks on joined channel`); + this.unsubscribe().then(async () => await this.subscribe()); + } + return this._on(type, filter, callback); + } + /** + * Sends a broadcast message explicitly via REST API. + * + * This method always uses the REST API endpoint regardless of WebSocket connection state. + * Useful when you want to guarantee REST delivery or when gradually migrating from implicit REST fallback. + * + * @param event The name of the broadcast event + * @param payload Payload to be sent (required) + * @param opts Options including timeout + * @returns Promise resolving to object with success status, and error details if failed + */ + async httpSend(event, payload, opts = {}) { + var _a; + const authorization = this.socket.accessTokenValue + ? `Bearer ${this.socket.accessTokenValue}` + : ''; + if (payload === undefined || payload === null) { + return Promise.reject('Payload is required for httpSend()'); + } + const options = { + method: 'POST', + headers: { + Authorization: authorization, + apikey: this.socket.apiKey ? this.socket.apiKey : '', + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + messages: [ + { + topic: this.subTopic, + event, + payload: payload, + private: this.private, + }, + ], + }), + }; + const response = await this._fetchWithTimeout(this.broadcastEndpointURL, options, (_a = opts.timeout) !== null && _a !== void 0 ? _a : this.timeout); + if (response.status === 202) { + return { success: true }; + } + let errorMessage = response.statusText; + try { + const errorBody = await response.json(); + errorMessage = errorBody.error || errorBody.message || errorMessage; + } + catch (_b) { } + return Promise.reject(new Error(errorMessage)); + } + /** + * Sends a message into the channel. + * + * @param args Arguments to send to channel + * @param args.type The type of event to send + * @param args.event The name of the event being sent + * @param args.payload Payload to be sent + * @param opts Options to be used during the send process + */ + async send(args, opts = {}) { + var _a, _b; + if (!this._canPush() && args.type === 'broadcast') { + console.warn('Realtime send() is automatically falling back to REST API. ' + + 'This behavior will be deprecated in the future. ' + + 'Please use httpSend() explicitly for REST delivery.'); + const { event, payload: endpoint_payload } = args; + const authorization = this.socket.accessTokenValue + ? `Bearer ${this.socket.accessTokenValue}` + : ''; + const options = { + method: 'POST', + headers: { + Authorization: authorization, + apikey: this.socket.apiKey ? this.socket.apiKey : '', + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + messages: [ + { + topic: this.subTopic, + event, + payload: endpoint_payload, + private: this.private, + }, + ], + }), + }; + try { + const response = await this._fetchWithTimeout(this.broadcastEndpointURL, options, (_a = opts.timeout) !== null && _a !== void 0 ? _a : this.timeout); + await ((_b = response.body) === null || _b === void 0 ? void 0 : _b.cancel()); + return response.ok ? 'ok' : 'error'; + } + catch (error) { + if (error.name === 'AbortError') { + return 'timed out'; + } + else { + return 'error'; + } + } + } + else { + return new Promise((resolve) => { + var _a, _b, _c; + const push = this._push(args.type, args, opts.timeout || this.timeout); + if (args.type === 'broadcast' && !((_c = (_b = (_a = this.params) === null || _a === void 0 ? void 0 : _a.config) === null || _b === void 0 ? void 0 : _b.broadcast) === null || _c === void 0 ? void 0 : _c.ack)) { + resolve('ok'); + } + push.receive('ok', () => resolve('ok')); + push.receive('error', () => resolve('error')); + push.receive('timeout', () => resolve('timed out')); + }); + } + } + /** + * Updates the payload that will be sent the next time the channel joins (reconnects). + * Useful for rotating access tokens or updating config without re-creating the channel. + */ + updateJoinPayload(payload) { + this.joinPush.updatePayload(payload); + } + /** + * Leaves the channel. + * + * Unsubscribes from server events, and instructs channel to terminate on server. + * Triggers onClose() hooks. + * + * To receive leave acknowledgements, use the a `receive` hook to bind to the server ack, ie: + * channel.unsubscribe().receive("ok", () => alert("left!") ) + */ + unsubscribe(timeout = this.timeout) { + this.state = CHANNEL_STATES.leaving; + const onClose = () => { + this.socket.log('channel', `leave ${this.topic}`); + this._trigger(CHANNEL_EVENTS.close, 'leave', this._joinRef()); + }; + this.joinPush.destroy(); + let leavePush = null; + return new Promise((resolve) => { + leavePush = new Push(this, CHANNEL_EVENTS.leave, {}, timeout); + leavePush + .receive('ok', () => { + onClose(); + resolve('ok'); + }) + .receive('timeout', () => { + onClose(); + resolve('timed out'); + }) + .receive('error', () => { + resolve('error'); + }); + leavePush.send(); + if (!this._canPush()) { + leavePush.trigger('ok', {}); + } + }).finally(() => { + leavePush === null || leavePush === void 0 ? void 0 : leavePush.destroy(); + }); + } + /** + * Teardown the channel. + * + * Destroys and stops related timers. + */ + teardown() { + this.pushBuffer.forEach((push) => push.destroy()); + this.pushBuffer = []; + this.rejoinTimer.reset(); + this.joinPush.destroy(); + this.state = CHANNEL_STATES.closed; + this.bindings = {}; + } + /** @internal */ + async _fetchWithTimeout(url, options, timeout) { + const controller = new AbortController(); + const id = setTimeout(() => controller.abort(), timeout); + const response = await this.socket.fetch(url, Object.assign(Object.assign({}, options), { signal: controller.signal })); + clearTimeout(id); + return response; + } + /** @internal */ + _push(event, payload, timeout = this.timeout) { + if (!this.joinedOnce) { + throw `tried to push '${event}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`; + } + let pushEvent = new Push(this, event, payload, timeout); + if (this._canPush()) { + pushEvent.send(); + } + else { + this._addToPushBuffer(pushEvent); + } + return pushEvent; + } + /** @internal */ + _addToPushBuffer(pushEvent) { + pushEvent.startTimeout(); + this.pushBuffer.push(pushEvent); + // Enforce buffer size limit + if (this.pushBuffer.length > MAX_PUSH_BUFFER_SIZE) { + const removedPush = this.pushBuffer.shift(); + if (removedPush) { + removedPush.destroy(); + this.socket.log('channel', `discarded push due to buffer overflow: ${removedPush.event}`, removedPush.payload); + } + } + } + /** + * Overridable message hook + * + * Receives all events for specialized message handling before dispatching to the channel callbacks. + * Must return the payload, modified or unmodified. + * + * @internal + */ + _onMessage(_event, payload, _ref) { + return payload; + } + /** @internal */ + _isMember(topic) { + return this.topic === topic; + } + /** @internal */ + _joinRef() { + return this.joinPush.ref; + } + /** @internal */ + _trigger(type, payload, ref) { + var _a, _b; + const typeLower = type.toLocaleLowerCase(); + const { close, error, leave, join } = CHANNEL_EVENTS; + const events = [close, error, leave, join]; + if (ref && events.indexOf(typeLower) >= 0 && ref !== this._joinRef()) { + return; + } + let handledPayload = this._onMessage(typeLower, payload, ref); + if (payload && !handledPayload) { + throw 'channel onMessage callbacks must return the payload, modified or unmodified'; + } + if (['insert', 'update', 'delete'].includes(typeLower)) { + (_a = this.bindings.postgres_changes) === null || _a === void 0 ? void 0 : _a.filter((bind) => { + var _a, _b, _c; + return ((_a = bind.filter) === null || _a === void 0 ? void 0 : _a.event) === '*' || ((_c = (_b = bind.filter) === null || _b === void 0 ? void 0 : _b.event) === null || _c === void 0 ? void 0 : _c.toLocaleLowerCase()) === typeLower; + }).map((bind) => bind.callback(handledPayload, ref)); + } + else { + (_b = this.bindings[typeLower]) === null || _b === void 0 ? void 0 : _b.filter((bind) => { + var _a, _b, _c, _d, _e, _f; + if (['broadcast', 'presence', 'postgres_changes'].includes(typeLower)) { + if ('id' in bind) { + const bindId = bind.id; + const bindEvent = (_a = bind.filter) === null || _a === void 0 ? void 0 : _a.event; + return (bindId && + ((_b = payload.ids) === null || _b === void 0 ? void 0 : _b.includes(bindId)) && + (bindEvent === '*' || + (bindEvent === null || bindEvent === void 0 ? void 0 : bindEvent.toLocaleLowerCase()) === ((_c = payload.data) === null || _c === void 0 ? void 0 : _c.type.toLocaleLowerCase()))); + } + else { + const bindEvent = (_e = (_d = bind === null || bind === void 0 ? void 0 : bind.filter) === null || _d === void 0 ? void 0 : _d.event) === null || _e === void 0 ? void 0 : _e.toLocaleLowerCase(); + return bindEvent === '*' || bindEvent === ((_f = payload === null || payload === void 0 ? void 0 : payload.event) === null || _f === void 0 ? void 0 : _f.toLocaleLowerCase()); + } + } + else { + return bind.type.toLocaleLowerCase() === typeLower; + } + }).map((bind) => { + if (typeof handledPayload === 'object' && 'ids' in handledPayload) { + const postgresChanges = handledPayload.data; + const { schema, table, commit_timestamp, type, errors } = postgresChanges; + const enrichedPayload = { + schema: schema, + table: table, + commit_timestamp: commit_timestamp, + eventType: type, + new: {}, + old: {}, + errors: errors, + }; + handledPayload = Object.assign(Object.assign({}, enrichedPayload), this._getPayloadRecords(postgresChanges)); + } + bind.callback(handledPayload, ref); + }); + } + } + /** @internal */ + _isClosed() { + return this.state === CHANNEL_STATES.closed; + } + /** @internal */ + _isJoined() { + return this.state === CHANNEL_STATES.joined; + } + /** @internal */ + _isJoining() { + return this.state === CHANNEL_STATES.joining; + } + /** @internal */ + _isLeaving() { + return this.state === CHANNEL_STATES.leaving; + } + /** @internal */ + _replyEventName(ref) { + return `chan_reply_${ref}`; + } + /** @internal */ + _on(type, filter, callback) { + const typeLower = type.toLocaleLowerCase(); + const binding = { + type: typeLower, + filter: filter, + callback: callback, + }; + if (this.bindings[typeLower]) { + this.bindings[typeLower].push(binding); + } + else { + this.bindings[typeLower] = [binding]; + } + return this; + } + /** @internal */ + _off(type, filter) { + const typeLower = type.toLocaleLowerCase(); + if (this.bindings[typeLower]) { + this.bindings[typeLower] = this.bindings[typeLower].filter((bind) => { + var _a; + return !(((_a = bind.type) === null || _a === void 0 ? void 0 : _a.toLocaleLowerCase()) === typeLower && + RealtimeChannel.isEqual(bind.filter, filter)); + }); + } + return this; + } + /** @internal */ + static isEqual(obj1, obj2) { + if (Object.keys(obj1).length !== Object.keys(obj2).length) { + return false; + } + for (const k in obj1) { + if (obj1[k] !== obj2[k]) { + return false; + } + } + return true; + } + /** + * Compares two optional filter values for equality. + * Treats undefined, null, and empty string as equivalent empty values. + * @internal + */ + static isFilterValueEqual(serverValue, clientValue) { + const normalizedServer = serverValue !== null && serverValue !== void 0 ? serverValue : undefined; + const normalizedClient = clientValue !== null && clientValue !== void 0 ? clientValue : undefined; + return normalizedServer === normalizedClient; + } + /** @internal */ + _rejoinUntilConnected() { + this.rejoinTimer.scheduleTimeout(); + if (this.socket.isConnected()) { + this._rejoin(); + } + } + /** + * Registers a callback that will be executed when the channel closes. + * + * @internal + */ + _onClose(callback) { + this._on(CHANNEL_EVENTS.close, {}, callback); + } + /** + * Registers a callback that will be executed when the channel encounteres an error. + * + * @internal + */ + _onError(callback) { + this._on(CHANNEL_EVENTS.error, {}, (reason) => callback(reason)); + } + /** + * Returns `true` if the socket is connected and the channel has been joined. + * + * @internal + */ + _canPush() { + return this.socket.isConnected() && this._isJoined(); + } + /** @internal */ + _rejoin(timeout = this.timeout) { + if (this._isLeaving()) { + return; + } + this.socket._leaveOpenTopic(this.topic); + this.state = CHANNEL_STATES.joining; + this.joinPush.resend(timeout); + } + /** @internal */ + _getPayloadRecords(payload) { + const records = { + new: {}, + old: {}, + }; + if (payload.type === 'INSERT' || payload.type === 'UPDATE') { + records.new = Transformers.convertChangeData(payload.columns, payload.record); + } + if (payload.type === 'UPDATE' || payload.type === 'DELETE') { + records.old = Transformers.convertChangeData(payload.columns, payload.old_record); + } + return records; + } +} +//# sourceMappingURL=RealtimeChannel.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/RealtimeChannel.js.map b/backend/node_modules/@supabase/realtime-js/dist/module/RealtimeChannel.js.map new file mode 100644 index 0000000..b1dc9a9 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/RealtimeChannel.js.map @@ -0,0 +1 @@ +{"version":3,"file":"RealtimeChannel.js","sourceRoot":"","sources":["../../src/RealtimeChannel.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAA;AACtF,OAAO,IAAI,MAAM,YAAY,CAAA;AAE7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AAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAA;IAC1E,CAAC;IAED;;;;OAIG;IACK,QAAQ;QACd,OAAO,IAAI,CAAC,MAAM,CAAC,WAAW,EAAE,IAAI,IAAI,CAAC,SAAS,EAAE,CAAA;IACtD,CAAC;IAED,gBAAgB;IACR,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO;QACpC,IAAI,IAAI,CAAC,UAAU,EAAE,EAAE,CAAC;YACtB,OAAM;QACR,CAAC;QACD,IAAI,CAAC,MAAM,CAAC,eAAe,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;QACvC,IAAI,CAAC,KAAK,GAAG,cAAc,CAAC,OAAO,CAAA;QACnC,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,CAAA;IAC/B,CAAC;IAED,gBAAgB;IACR,kBAAkB,CAAC,OAAY;QACrC,MAAM,OAAO,GAAG;YACd,GAAG,EAAE,EAAE;YACP,GAAG,EAAE,EAAE;SACR,CAAA;QAED,IAAI,OAAO,CAAC,IAAI,KAAK,QAAQ,IAAI,OAAO,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;YAC3D,OAAO,CAAC,GAAG,GAAG,YAAY,CAAC,iBAAiB,CAAC,OAAO,CAAC,OAAO,EAAE,OAAO,CAAC,MAAM,CAAC,CAAA;QAC/E,CAAC;QAED,IAAI,OAAO,CAAC,IAAI,KAAK,QAAQ,IAAI,OAAO,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;YAC3D,OAAO,CAAC,GAAG,GAAG,YAAY,CAAC,iBAAiB,CAAC,OAAO,CAAC,OAAO,EAAE,OAAO,CAAC,UAAU,CAAC,CAAA;QACnF,CAAC;QAED,OAAO,OAAO,CAAA;IAChB,CAAC;CACF"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/RealtimeClient.d.ts b/backend/node_modules/@supabase/realtime-js/dist/module/RealtimeClient.d.ts new file mode 100644 index 0000000..350459b --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/RealtimeClient.d.ts @@ -0,0 +1,236 @@ +import { WebSocketLike } from './lib/websocket-factory'; +import { CONNECTION_STATE } from './lib/constants'; +import Serializer from './lib/serializer'; +import Timer from './lib/timer'; +import RealtimeChannel from './RealtimeChannel'; +import type { RealtimeChannelOptions } from './RealtimeChannel'; +type Fetch = typeof fetch; +export type Channel = { + name: string; + inserted_at: string; + updated_at: string; + id: number; +}; +export type LogLevel = 'info' | 'warn' | 'error'; +export type RealtimeMessage = { + topic: string; + event: string; + payload: any; + ref: string; + join_ref?: string; +}; +export type RealtimeRemoveChannelResponse = 'ok' | 'timed out' | 'error'; +export type HeartbeatStatus = 'sent' | 'ok' | 'error' | 'timeout' | 'disconnected'; +/** + * Minimal WebSocket constructor interface that RealtimeClient can work with. + * Supply a compatible implementation (native WebSocket, `ws`, etc) when running outside the browser. + */ +export interface WebSocketLikeConstructor { + new (address: string | URL, subprotocols?: string | string[] | undefined): WebSocketLike; + [key: string]: any; +} +export interface WebSocketLikeError { + error: any; + message: string; + type: string; +} +export type RealtimeClientOptions = { + transport?: WebSocketLikeConstructor; + timeout?: number; + heartbeatIntervalMs?: number; + heartbeatCallback?: (status: HeartbeatStatus) => void; + vsn?: string; + logger?: Function; + encode?: Function; + decode?: Function; + reconnectAfterMs?: Function; + headers?: { + [key: string]: string; + }; + params?: { + [key: string]: any; + }; + log_level?: LogLevel; + logLevel?: LogLevel; + fetch?: Fetch; + worker?: boolean; + workerUrl?: string; + accessToken?: () => Promise; +}; +export default class RealtimeClient { + accessTokenValue: string | null; + apiKey: string | null; + private _manuallySetToken; + channels: RealtimeChannel[]; + endPoint: string; + httpEndpoint: string; + /** @deprecated headers cannot be set on websocket connections */ + headers?: { + [key: string]: string; + }; + params?: { + [key: string]: string; + }; + timeout: number; + transport: WebSocketLikeConstructor | null; + heartbeatIntervalMs: number; + heartbeatTimer: ReturnType | undefined; + pendingHeartbeatRef: string | null; + heartbeatCallback: (status: HeartbeatStatus) => void; + ref: number; + reconnectTimer: Timer | null; + vsn: string; + logger: Function; + logLevel?: LogLevel; + encode: Function; + decode: Function; + reconnectAfterMs: Function; + conn: WebSocketLike | null; + sendBuffer: Function[]; + serializer: Serializer; + stateChangeCallbacks: { + open: Function[]; + close: Function[]; + error: Function[]; + message: Function[]; + }; + fetch: Fetch; + accessToken: (() => Promise) | null; + worker?: boolean; + workerUrl?: string; + workerRef?: Worker; + private _connectionState; + private _wasManualDisconnect; + private _authPromise; + /** + * Initializes the Socket. + * + * @param endPoint The string WebSocket endpoint, ie, "ws://example.com/socket", "wss://example.com", "/socket" (inherited host & protocol) + * @param httpEndpoint The string HTTP endpoint, ie, "https://example.com", "/" (inherited host & protocol) + * @param options.transport The Websocket Transport, for example WebSocket. This can be a custom implementation + * @param options.timeout The default timeout in milliseconds to trigger push timeouts. + * @param options.params The optional params to pass when connecting. + * @param options.headers Deprecated: headers cannot be set on websocket connections and this option will be removed in the future. + * @param options.heartbeatIntervalMs The millisec interval to send a heartbeat message. + * @param options.heartbeatCallback The optional function to handle heartbeat status. + * @param options.logger The optional function for specialized logging, ie: logger: (kind, msg, data) => { console.log(`${kind}: ${msg}`, data) } + * @param options.logLevel Sets the log level for Realtime + * @param options.encode The function to encode outgoing messages. Defaults to JSON: (payload, callback) => callback(JSON.stringify(payload)) + * @param options.decode The function to decode incoming messages. Defaults to Serializer's decode. + * @param options.reconnectAfterMs he optional function that returns the millsec reconnect interval. Defaults to stepped backoff off. + * @param options.worker Use Web Worker to set a side flow. Defaults to false. + * @param options.workerUrl The URL of the worker script. Defaults to https://realtime.supabase.com/worker.js that includes a heartbeat event call to keep the connection alive. + * @example + * ```ts + * import RealtimeClient from '@supabase/realtime-js' + * + * const client = new RealtimeClient('https://xyzcompany.supabase.co/realtime/v1', { + * params: { apikey: 'public-anon-key' }, + * }) + * client.connect() + * ``` + */ + constructor(endPoint: string, options?: RealtimeClientOptions); + /** + * Connects the socket, unless already connected. + */ + connect(): void; + /** + * Returns the URL of the websocket. + * @returns string The URL of the websocket. + */ + endpointURL(): string; + /** + * Disconnects the socket. + * + * @param code A numeric status code to send on disconnect. + * @param reason A custom reason for the disconnect. + */ + disconnect(code?: number, reason?: string): void; + /** + * Returns all created channels + */ + getChannels(): RealtimeChannel[]; + /** + * Unsubscribes and removes a single channel + * @param channel A RealtimeChannel instance + */ + removeChannel(channel: RealtimeChannel): Promise; + /** + * Unsubscribes and removes all channels + */ + removeAllChannels(): Promise; + /** + * Logs the message. + * + * For customized logging, `this.logger` can be overridden. + */ + log(kind: string, msg: string, data?: any): void; + /** + * Returns the current state of the socket. + */ + connectionState(): CONNECTION_STATE; + /** + * Returns `true` is the connection is open. + */ + isConnected(): boolean; + /** + * Returns `true` if the connection is currently connecting. + */ + isConnecting(): boolean; + /** + * Returns `true` if the connection is currently disconnecting. + */ + isDisconnecting(): boolean; + /** + * Creates (or reuses) a {@link RealtimeChannel} for the provided topic. + * + * Topics are automatically prefixed with `realtime:` to match the Realtime service. + * If a channel with the same topic already exists it will be returned instead of creating + * a duplicate connection. + */ + channel(topic: string, params?: RealtimeChannelOptions): RealtimeChannel; + /** + * Push out a message if the socket is connected. + * + * If the socket is not connected, the message gets enqueued within a local buffer, and sent out when a connection is next established. + */ + push(data: RealtimeMessage): void; + /** + * Sets the JWT access token used for channel subscription authorization and Realtime RLS. + * + * If param is null it will use the `accessToken` callback function or the token set on the client. + * + * On callback used, it will set the value of the token internal to the client. + * + * When a token is explicitly provided, it will be preserved across channel operations + * (including removeChannel and resubscribe). The `accessToken` callback will not be + * invoked until `setAuth()` is called without arguments. + * + * @param token A JWT string to override the token set on the client. + * + * @example + * // Use a manual token (preserved across resubscribes, ignores accessToken callback) + * client.realtime.setAuth('my-custom-jwt') + * + * // Switch back to using the accessToken callback + * client.realtime.setAuth() + */ + setAuth(token?: string | null): Promise; + /** + * Sends a heartbeat message if the socket is connected. + */ + sendHeartbeat(): Promise; + /** + * Sets a callback that receives lifecycle events for internal heartbeat messages. + * Useful for instrumenting connection health (e.g. sent/ok/timeout/disconnected). + */ + onHeartbeat(callback: (status: HeartbeatStatus) => void): void; + /** + * Flushes send buffer + */ + flushSendBuffer(): void; + private _workerObjectUrl; +} +export {}; +//# sourceMappingURL=RealtimeClient.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/RealtimeClient.d.ts.map b/backend/node_modules/@supabase/realtime-js/dist/module/RealtimeClient.d.ts.map new file mode 100644 index 0000000..9106696 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/RealtimeClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"RealtimeClient.d.ts","sourceRoot":"","sources":["../../src/RealtimeClient.ts"],"names":[],"mappings":"AAAA,OAAyB,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAA;AAEzE,OAAO,EAEL,gBAAgB,EASjB,MAAM,iBAAiB,CAAA;AAExB,OAAO,UAAU,MAAM,kBAAkB,CAAA;AACzC,OAAO,KAAK,MAAM,aAAa,CAAA;AAG/B,OAAO,eAAe,MAAM,mBAAmB,CAAA;AAC/C,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAA;AAE/D,KAAK,KAAK,GAAG,OAAO,KAAK,CAAA;AAEzB,MAAM,MAAM,OAAO,GAAG;IACpB,IAAI,EAAE,MAAM,CAAA;IACZ,WAAW,EAAE,MAAM,CAAA;IACnB,UAAU,EAAE,MAAM,CAAA;IAClB,EAAE,EAAE,MAAM,CAAA;CACX,CAAA;AACD,MAAM,MAAM,QAAQ,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,CAAA;AAEhD,MAAM,MAAM,eAAe,GAAG;IAC5B,KAAK,EAAE,MAAM,CAAA;IACb,KAAK,EAAE,MAAM,CAAA;IACb,OAAO,EAAE,GAAG,CAAA;IACZ,GAAG,EAAE,MAAM,CAAA;IACX,QAAQ,CAAC,EAAE,MAAM,CAAA;CAClB,CAAA;AAED,MAAM,MAAM,6BAA6B,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E,MAAM,EAAE,MAAM,GAAE,sBAAuC,GAAG,eAAe;IAcxF;;;;OAIG;IACH,IAAI,CAAC,IAAI,EAAE,eAAe,GAAG,IAAI;IAejC;;;;;;;;;;;;;;;;;;;OAmBG;IACG,OAAO,CAAC,KAAK,GAAE,MAAM,GAAG,IAAW,GAAG,OAAO,CAAC,IAAI,CAAC;IAkBzD;;OAEG;IACG,aAAa;IAiDnB;;;OAGG;IACH,WAAW,CAAC,QAAQ,EAAE,CAAC,MAAM,EAAE,eAAe,KAAK,IAAI,GAAG,IAAI;IAG9D;;OAEG;IACH,eAAe;IAoQf,OAAO,CAAC,gBAAgB;CAiMzB"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/RealtimeClient.js b/backend/node_modules/@supabase/realtime-js/dist/module/RealtimeClient.js new file mode 100644 index 0000000..a29fe55 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/RealtimeClient.js @@ -0,0 +1,811 @@ +import WebSocketFactory from './lib/websocket-factory'; +import { CHANNEL_EVENTS, CONNECTION_STATE, DEFAULT_VERSION, DEFAULT_TIMEOUT, SOCKET_STATES, TRANSPORTS, DEFAULT_VSN, VSN_1_0_0, VSN_2_0_0, WS_CLOSE_NORMAL, } from './lib/constants'; +import Serializer from './lib/serializer'; +import Timer from './lib/timer'; +import { httpEndpointURL } from './lib/transformers'; +import RealtimeChannel from './RealtimeChannel'; +const noop = () => { }; +// Connection-related constants +const CONNECTION_TIMEOUTS = { + HEARTBEAT_INTERVAL: 25000, + RECONNECT_DELAY: 10, + HEARTBEAT_TIMEOUT_FALLBACK: 100, +}; +const RECONNECT_INTERVALS = [1000, 2000, 5000, 10000]; +const DEFAULT_RECONNECT_FALLBACK = 10000; +const WORKER_SCRIPT = ` + addEventListener("message", (e) => { + if (e.data.event === "start") { + setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); + } + });`; +export default class RealtimeClient { + /** + * Initializes the Socket. + * + * @param endPoint The string WebSocket endpoint, ie, "ws://example.com/socket", "wss://example.com", "/socket" (inherited host & protocol) + * @param httpEndpoint The string HTTP endpoint, ie, "https://example.com", "/" (inherited host & protocol) + * @param options.transport The Websocket Transport, for example WebSocket. This can be a custom implementation + * @param options.timeout The default timeout in milliseconds to trigger push timeouts. + * @param options.params The optional params to pass when connecting. + * @param options.headers Deprecated: headers cannot be set on websocket connections and this option will be removed in the future. + * @param options.heartbeatIntervalMs The millisec interval to send a heartbeat message. + * @param options.heartbeatCallback The optional function to handle heartbeat status. + * @param options.logger The optional function for specialized logging, ie: logger: (kind, msg, data) => { console.log(`${kind}: ${msg}`, data) } + * @param options.logLevel Sets the log level for Realtime + * @param options.encode The function to encode outgoing messages. Defaults to JSON: (payload, callback) => callback(JSON.stringify(payload)) + * @param options.decode The function to decode incoming messages. Defaults to Serializer's decode. + * @param options.reconnectAfterMs he optional function that returns the millsec reconnect interval. Defaults to stepped backoff off. + * @param options.worker Use Web Worker to set a side flow. Defaults to false. + * @param options.workerUrl The URL of the worker script. Defaults to https://realtime.supabase.com/worker.js that includes a heartbeat event call to keep the connection alive. + * @example + * ```ts + * import RealtimeClient from '@supabase/realtime-js' + * + * const client = new RealtimeClient('https://xyzcompany.supabase.co/realtime/v1', { + * params: { apikey: 'public-anon-key' }, + * }) + * client.connect() + * ``` + */ + constructor(endPoint, options) { + var _a; + this.accessTokenValue = null; + this.apiKey = null; + this._manuallySetToken = false; + this.channels = new Array(); + this.endPoint = ''; + this.httpEndpoint = ''; + /** @deprecated headers cannot be set on websocket connections */ + this.headers = {}; + this.params = {}; + this.timeout = DEFAULT_TIMEOUT; + this.transport = null; + this.heartbeatIntervalMs = CONNECTION_TIMEOUTS.HEARTBEAT_INTERVAL; + this.heartbeatTimer = undefined; + this.pendingHeartbeatRef = null; + this.heartbeatCallback = noop; + this.ref = 0; + this.reconnectTimer = null; + this.vsn = DEFAULT_VSN; + this.logger = noop; + this.conn = null; + this.sendBuffer = []; + this.serializer = new Serializer(); + this.stateChangeCallbacks = { + open: [], + close: [], + error: [], + message: [], + }; + this.accessToken = null; + this._connectionState = 'disconnected'; + this._wasManualDisconnect = false; + this._authPromise = null; + /** + * Use either custom fetch, if provided, or default fetch to make HTTP requests + * + * @internal + */ + this._resolveFetch = (customFetch) => { + if (customFetch) { + return (...args) => customFetch(...args); + } + return (...args) => fetch(...args); + }; + // Validate required parameters + if (!((_a = options === null || options === void 0 ? void 0 : options.params) === null || _a === void 0 ? void 0 : _a.apikey)) { + throw new Error('API key is required to connect to Realtime'); + } + this.apiKey = options.params.apikey; + // Initialize endpoint URLs + this.endPoint = `${endPoint}/${TRANSPORTS.websocket}`; + this.httpEndpoint = httpEndpointURL(endPoint); + this._initializeOptions(options); + this._setupReconnectionTimer(); + this.fetch = this._resolveFetch(options === null || options === void 0 ? void 0 : options.fetch); + } + /** + * Connects the socket, unless already connected. + */ + connect() { + // Skip if already connecting, disconnecting, or connected + if (this.isConnecting() || + this.isDisconnecting() || + (this.conn !== null && this.isConnected())) { + return; + } + this._setConnectionState('connecting'); + // Trigger auth if needed and not already in progress + // This ensures auth is called for standalone RealtimeClient usage + // while avoiding race conditions with SupabaseClient's immediate setAuth call + if (this.accessToken && !this._authPromise) { + this._setAuthSafely('connect'); + } + // Establish WebSocket connection + if (this.transport) { + // Use custom transport if provided + this.conn = new this.transport(this.endpointURL()); + } + else { + // Try to use native WebSocket + try { + this.conn = WebSocketFactory.createWebSocket(this.endpointURL()); + } + catch (error) { + this._setConnectionState('disconnected'); + const errorMessage = error.message; + // Provide helpful error message based on environment + if (errorMessage.includes('Node.js')) { + throw new Error(`${errorMessage}\n\n` + + 'To use Realtime in Node.js, you need to provide a WebSocket implementation:\n\n' + + 'Option 1: Use Node.js 22+ which has native WebSocket support\n' + + 'Option 2: Install and provide the "ws" package:\n\n' + + ' npm install ws\n\n' + + ' import ws from "ws"\n' + + ' const client = new RealtimeClient(url, {\n' + + ' ...options,\n' + + ' transport: ws\n' + + ' })'); + } + throw new Error(`WebSocket not available: ${errorMessage}`); + } + } + this._setupConnectionHandlers(); + } + /** + * Returns the URL of the websocket. + * @returns string The URL of the websocket. + */ + endpointURL() { + return this._appendParams(this.endPoint, Object.assign({}, this.params, { vsn: this.vsn })); + } + /** + * Disconnects the socket. + * + * @param code A numeric status code to send on disconnect. + * @param reason A custom reason for the disconnect. + */ + disconnect(code, reason) { + if (this.isDisconnecting()) { + return; + } + this._setConnectionState('disconnecting', true); + if (this.conn) { + // Setup fallback timer to prevent hanging in disconnecting state + const fallbackTimer = setTimeout(() => { + this._setConnectionState('disconnected'); + }, 100); + this.conn.onclose = () => { + clearTimeout(fallbackTimer); + this._setConnectionState('disconnected'); + }; + // Close the WebSocket connection if close method exists + if (typeof this.conn.close === 'function') { + if (code) { + this.conn.close(code, reason !== null && reason !== void 0 ? reason : ''); + } + else { + this.conn.close(); + } + } + this._teardownConnection(); + } + else { + this._setConnectionState('disconnected'); + } + } + /** + * Returns all created channels + */ + getChannels() { + return this.channels; + } + /** + * Unsubscribes and removes a single channel + * @param channel A RealtimeChannel instance + */ + async removeChannel(channel) { + const status = await channel.unsubscribe(); + if (this.channels.length === 0) { + this.disconnect(); + } + return status; + } + /** + * Unsubscribes and removes all channels + */ + async removeAllChannels() { + const values_1 = await Promise.all(this.channels.map((channel) => channel.unsubscribe())); + this.channels = []; + this.disconnect(); + return values_1; + } + /** + * Logs the message. + * + * For customized logging, `this.logger` can be overridden. + */ + log(kind, msg, data) { + this.logger(kind, msg, data); + } + /** + * Returns the current state of the socket. + */ + connectionState() { + switch (this.conn && this.conn.readyState) { + case SOCKET_STATES.connecting: + return CONNECTION_STATE.Connecting; + case SOCKET_STATES.open: + return CONNECTION_STATE.Open; + case SOCKET_STATES.closing: + return CONNECTION_STATE.Closing; + default: + return CONNECTION_STATE.Closed; + } + } + /** + * Returns `true` is the connection is open. + */ + isConnected() { + return this.connectionState() === CONNECTION_STATE.Open; + } + /** + * Returns `true` if the connection is currently connecting. + */ + isConnecting() { + return this._connectionState === 'connecting'; + } + /** + * Returns `true` if the connection is currently disconnecting. + */ + isDisconnecting() { + return this._connectionState === 'disconnecting'; + } + /** + * Creates (or reuses) a {@link RealtimeChannel} for the provided topic. + * + * Topics are automatically prefixed with `realtime:` to match the Realtime service. + * If a channel with the same topic already exists it will be returned instead of creating + * a duplicate connection. + */ + channel(topic, params = { config: {} }) { + const realtimeTopic = `realtime:${topic}`; + const exists = this.getChannels().find((c) => c.topic === realtimeTopic); + if (!exists) { + const chan = new RealtimeChannel(`realtime:${topic}`, params, this); + this.channels.push(chan); + return chan; + } + else { + return exists; + } + } + /** + * Push out a message if the socket is connected. + * + * If the socket is not connected, the message gets enqueued within a local buffer, and sent out when a connection is next established. + */ + push(data) { + const { topic, event, payload, ref } = data; + const callback = () => { + this.encode(data, (result) => { + var _a; + (_a = this.conn) === null || _a === void 0 ? void 0 : _a.send(result); + }); + }; + this.log('push', `${topic} ${event} (${ref})`, payload); + if (this.isConnected()) { + callback(); + } + else { + this.sendBuffer.push(callback); + } + } + /** + * Sets the JWT access token used for channel subscription authorization and Realtime RLS. + * + * If param is null it will use the `accessToken` callback function or the token set on the client. + * + * On callback used, it will set the value of the token internal to the client. + * + * When a token is explicitly provided, it will be preserved across channel operations + * (including removeChannel and resubscribe). The `accessToken` callback will not be + * invoked until `setAuth()` is called without arguments. + * + * @param token A JWT string to override the token set on the client. + * + * @example + * // Use a manual token (preserved across resubscribes, ignores accessToken callback) + * client.realtime.setAuth('my-custom-jwt') + * + * // Switch back to using the accessToken callback + * client.realtime.setAuth() + */ + async setAuth(token = null) { + this._authPromise = this._performAuth(token); + try { + await this._authPromise; + } + finally { + this._authPromise = null; + } + } + /** + * Returns true if the current access token was explicitly set via setAuth(token), + * false if it was obtained via the accessToken callback. + * @internal + */ + _isManualToken() { + return this._manuallySetToken; + } + /** + * Sends a heartbeat message if the socket is connected. + */ + async sendHeartbeat() { + var _a; + if (!this.isConnected()) { + try { + this.heartbeatCallback('disconnected'); + } + catch (e) { + this.log('error', 'error in heartbeat callback', e); + } + return; + } + // Handle heartbeat timeout and force reconnection if needed + if (this.pendingHeartbeatRef) { + this.pendingHeartbeatRef = null; + this.log('transport', 'heartbeat timeout. Attempting to re-establish connection'); + try { + this.heartbeatCallback('timeout'); + } + catch (e) { + this.log('error', 'error in heartbeat callback', e); + } + // Force reconnection after heartbeat timeout + this._wasManualDisconnect = false; + (_a = this.conn) === null || _a === void 0 ? void 0 : _a.close(WS_CLOSE_NORMAL, 'heartbeat timeout'); + setTimeout(() => { + var _a; + if (!this.isConnected()) { + (_a = this.reconnectTimer) === null || _a === void 0 ? void 0 : _a.scheduleTimeout(); + } + }, CONNECTION_TIMEOUTS.HEARTBEAT_TIMEOUT_FALLBACK); + return; + } + // Send heartbeat message to server + this.pendingHeartbeatRef = this._makeRef(); + this.push({ + topic: 'phoenix', + event: 'heartbeat', + payload: {}, + ref: this.pendingHeartbeatRef, + }); + try { + this.heartbeatCallback('sent'); + } + catch (e) { + this.log('error', 'error in heartbeat callback', e); + } + this._setAuthSafely('heartbeat'); + } + /** + * Sets a callback that receives lifecycle events for internal heartbeat messages. + * Useful for instrumenting connection health (e.g. sent/ok/timeout/disconnected). + */ + onHeartbeat(callback) { + this.heartbeatCallback = callback; + } + /** + * Flushes send buffer + */ + flushSendBuffer() { + if (this.isConnected() && this.sendBuffer.length > 0) { + this.sendBuffer.forEach((callback) => callback()); + this.sendBuffer = []; + } + } + /** + * Return the next message ref, accounting for overflows + * + * @internal + */ + _makeRef() { + let newRef = this.ref + 1; + if (newRef === this.ref) { + this.ref = 0; + } + else { + this.ref = newRef; + } + return this.ref.toString(); + } + /** + * Unsubscribe from channels with the specified topic. + * + * @internal + */ + _leaveOpenTopic(topic) { + let dupChannel = this.channels.find((c) => c.topic === topic && (c._isJoined() || c._isJoining())); + if (dupChannel) { + this.log('transport', `leaving duplicate topic "${topic}"`); + dupChannel.unsubscribe(); + } + } + /** + * Removes a subscription from the socket. + * + * @param channel An open subscription. + * + * @internal + */ + _remove(channel) { + this.channels = this.channels.filter((c) => c.topic !== channel.topic); + } + /** @internal */ + _onConnMessage(rawMessage) { + this.decode(rawMessage.data, (msg) => { + // Handle heartbeat responses + if (msg.topic === 'phoenix' && msg.event === 'phx_reply') { + try { + this.heartbeatCallback(msg.payload.status === 'ok' ? 'ok' : 'error'); + } + catch (e) { + this.log('error', 'error in heartbeat callback', e); + } + } + // Handle pending heartbeat reference cleanup + if (msg.ref && msg.ref === this.pendingHeartbeatRef) { + this.pendingHeartbeatRef = null; + } + // Log incoming message + const { topic, event, payload, ref } = msg; + const refString = ref ? `(${ref})` : ''; + const status = payload.status || ''; + this.log('receive', `${status} ${topic} ${event} ${refString}`.trim(), payload); + // Route message to appropriate channels + this.channels + .filter((channel) => channel._isMember(topic)) + .forEach((channel) => channel._trigger(event, payload, ref)); + this._triggerStateCallbacks('message', msg); + }); + } + /** + * Clear specific timer + * @internal + */ + _clearTimer(timer) { + var _a; + if (timer === 'heartbeat' && this.heartbeatTimer) { + clearInterval(this.heartbeatTimer); + this.heartbeatTimer = undefined; + } + else if (timer === 'reconnect') { + (_a = this.reconnectTimer) === null || _a === void 0 ? void 0 : _a.reset(); + } + } + /** + * Clear all timers + * @internal + */ + _clearAllTimers() { + this._clearTimer('heartbeat'); + this._clearTimer('reconnect'); + } + /** + * Setup connection handlers for WebSocket events + * @internal + */ + _setupConnectionHandlers() { + if (!this.conn) + return; + // Set binary type if supported (browsers and most WebSocket implementations) + if ('binaryType' in this.conn) { + ; + this.conn.binaryType = 'arraybuffer'; + } + this.conn.onopen = () => this._onConnOpen(); + this.conn.onerror = (error) => this._onConnError(error); + this.conn.onmessage = (event) => this._onConnMessage(event); + this.conn.onclose = (event) => this._onConnClose(event); + } + /** + * Teardown connection and cleanup resources + * @internal + */ + _teardownConnection() { + if (this.conn) { + if (this.conn.readyState === SOCKET_STATES.open || + this.conn.readyState === SOCKET_STATES.connecting) { + try { + this.conn.close(); + } + catch (e) { + this.log('error', 'Error closing connection', e); + } + } + this.conn.onopen = null; + this.conn.onerror = null; + this.conn.onmessage = null; + this.conn.onclose = null; + this.conn = null; + } + this._clearAllTimers(); + this.channels.forEach((channel) => channel.teardown()); + } + /** @internal */ + _onConnOpen() { + this._setConnectionState('connected'); + this.log('transport', `connected to ${this.endpointURL()}`); + // Wait for any pending auth operations before flushing send buffer + // This ensures channel join messages include the correct access token + const authPromise = this._authPromise || + (this.accessToken && !this.accessTokenValue ? this.setAuth() : Promise.resolve()); + authPromise + .then(() => { + this.flushSendBuffer(); + }) + .catch((e) => { + this.log('error', 'error waiting for auth on connect', e); + // Proceed anyway to avoid hanging connections + this.flushSendBuffer(); + }); + this._clearTimer('reconnect'); + if (!this.worker) { + this._startHeartbeat(); + } + else { + if (!this.workerRef) { + this._startWorkerHeartbeat(); + } + } + this._triggerStateCallbacks('open'); + } + /** @internal */ + _startHeartbeat() { + this.heartbeatTimer && clearInterval(this.heartbeatTimer); + this.heartbeatTimer = setInterval(() => this.sendHeartbeat(), this.heartbeatIntervalMs); + } + /** @internal */ + _startWorkerHeartbeat() { + if (this.workerUrl) { + this.log('worker', `starting worker for from ${this.workerUrl}`); + } + else { + this.log('worker', `starting default worker`); + } + const objectUrl = this._workerObjectUrl(this.workerUrl); + this.workerRef = new Worker(objectUrl); + this.workerRef.onerror = (error) => { + this.log('worker', 'worker error', error.message); + this.workerRef.terminate(); + }; + this.workerRef.onmessage = (event) => { + if (event.data.event === 'keepAlive') { + this.sendHeartbeat(); + } + }; + this.workerRef.postMessage({ + event: 'start', + interval: this.heartbeatIntervalMs, + }); + } + /** @internal */ + _onConnClose(event) { + var _a; + this._setConnectionState('disconnected'); + this.log('transport', 'close', event); + this._triggerChanError(); + this._clearTimer('heartbeat'); + // Only schedule reconnection if it wasn't a manual disconnect + if (!this._wasManualDisconnect) { + (_a = this.reconnectTimer) === null || _a === void 0 ? void 0 : _a.scheduleTimeout(); + } + this._triggerStateCallbacks('close', event); + } + /** @internal */ + _onConnError(error) { + this._setConnectionState('disconnected'); + this.log('transport', `${error}`); + this._triggerChanError(); + this._triggerStateCallbacks('error', error); + } + /** @internal */ + _triggerChanError() { + this.channels.forEach((channel) => channel._trigger(CHANNEL_EVENTS.error)); + } + /** @internal */ + _appendParams(url, params) { + if (Object.keys(params).length === 0) { + return url; + } + const prefix = url.match(/\?/) ? '&' : '?'; + const query = new URLSearchParams(params); + return `${url}${prefix}${query}`; + } + _workerObjectUrl(url) { + let result_url; + if (url) { + result_url = url; + } + else { + const blob = new Blob([WORKER_SCRIPT], { type: 'application/javascript' }); + result_url = URL.createObjectURL(blob); + } + return result_url; + } + /** + * Set connection state with proper state management + * @internal + */ + _setConnectionState(state, manual = false) { + this._connectionState = state; + if (state === 'connecting') { + this._wasManualDisconnect = false; + } + else if (state === 'disconnecting') { + this._wasManualDisconnect = manual; + } + } + /** + * Perform the actual auth operation + * @internal + */ + async _performAuth(token = null) { + let tokenToSend; + let isManualToken = false; + if (token) { + tokenToSend = token; + // Track if this is a manually-provided token + isManualToken = true; + } + else if (this.accessToken) { + // Call the accessToken callback to get fresh token + try { + tokenToSend = await this.accessToken(); + } + catch (e) { + this.log('error', 'Error fetching access token from callback', e); + // Fall back to cached value if callback fails + tokenToSend = this.accessTokenValue; + } + } + else { + tokenToSend = this.accessTokenValue; + } + // Track whether this token was manually set or fetched via callback + if (isManualToken) { + this._manuallySetToken = true; + } + else if (this.accessToken) { + // If we used the callback, clear the manual flag + this._manuallySetToken = false; + } + if (this.accessTokenValue != tokenToSend) { + this.accessTokenValue = tokenToSend; + this.channels.forEach((channel) => { + const payload = { + access_token: tokenToSend, + version: DEFAULT_VERSION, + }; + tokenToSend && channel.updateJoinPayload(payload); + if (channel.joinedOnce && channel._isJoined()) { + channel._push(CHANNEL_EVENTS.access_token, { + access_token: tokenToSend, + }); + } + }); + } + } + /** + * Wait for any in-flight auth operations to complete + * @internal + */ + async _waitForAuthIfNeeded() { + if (this._authPromise) { + await this._authPromise; + } + } + /** + * Safely call setAuth with standardized error handling + * @internal + */ + _setAuthSafely(context = 'general') { + // Only refresh auth if using callback-based tokens + if (!this._isManualToken()) { + this.setAuth().catch((e) => { + this.log('error', `Error setting auth in ${context}`, e); + }); + } + } + /** + * Trigger state change callbacks with proper error handling + * @internal + */ + _triggerStateCallbacks(event, data) { + try { + this.stateChangeCallbacks[event].forEach((callback) => { + try { + callback(data); + } + catch (e) { + this.log('error', `error in ${event} callback`, e); + } + }); + } + catch (e) { + this.log('error', `error triggering ${event} callbacks`, e); + } + } + /** + * Setup reconnection timer with proper configuration + * @internal + */ + _setupReconnectionTimer() { + this.reconnectTimer = new Timer(async () => { + setTimeout(async () => { + await this._waitForAuthIfNeeded(); + if (!this.isConnected()) { + this.connect(); + } + }, CONNECTION_TIMEOUTS.RECONNECT_DELAY); + }, this.reconnectAfterMs); + } + /** + * Initialize client options with defaults + * @internal + */ + _initializeOptions(options) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m; + // Set defaults + this.transport = (_a = options === null || options === void 0 ? void 0 : options.transport) !== null && _a !== void 0 ? _a : null; + this.timeout = (_b = options === null || options === void 0 ? void 0 : options.timeout) !== null && _b !== void 0 ? _b : DEFAULT_TIMEOUT; + this.heartbeatIntervalMs = + (_c = options === null || options === void 0 ? void 0 : options.heartbeatIntervalMs) !== null && _c !== void 0 ? _c : CONNECTION_TIMEOUTS.HEARTBEAT_INTERVAL; + this.worker = (_d = options === null || options === void 0 ? void 0 : options.worker) !== null && _d !== void 0 ? _d : false; + this.accessToken = (_e = options === null || options === void 0 ? void 0 : options.accessToken) !== null && _e !== void 0 ? _e : null; + this.heartbeatCallback = (_f = options === null || options === void 0 ? void 0 : options.heartbeatCallback) !== null && _f !== void 0 ? _f : noop; + this.vsn = (_g = options === null || options === void 0 ? void 0 : options.vsn) !== null && _g !== void 0 ? _g : DEFAULT_VSN; + // Handle special cases + if (options === null || options === void 0 ? void 0 : options.params) + this.params = options.params; + if (options === null || options === void 0 ? void 0 : options.logger) + this.logger = options.logger; + if ((options === null || options === void 0 ? void 0 : options.logLevel) || (options === null || options === void 0 ? void 0 : options.log_level)) { + this.logLevel = options.logLevel || options.log_level; + this.params = Object.assign(Object.assign({}, this.params), { log_level: this.logLevel }); + } + // Set up functions with defaults + this.reconnectAfterMs = + (_h = options === null || options === void 0 ? void 0 : options.reconnectAfterMs) !== null && _h !== void 0 ? _h : ((tries) => { + return RECONNECT_INTERVALS[tries - 1] || DEFAULT_RECONNECT_FALLBACK; + }); + switch (this.vsn) { + case VSN_1_0_0: + this.encode = + (_j = options === null || options === void 0 ? void 0 : options.encode) !== null && _j !== void 0 ? _j : ((payload, callback) => { + return callback(JSON.stringify(payload)); + }); + this.decode = + (_k = options === null || options === void 0 ? void 0 : options.decode) !== null && _k !== void 0 ? _k : ((payload, callback) => { + return callback(JSON.parse(payload)); + }); + break; + case VSN_2_0_0: + this.encode = (_l = options === null || options === void 0 ? void 0 : options.encode) !== null && _l !== void 0 ? _l : this.serializer.encode.bind(this.serializer); + this.decode = (_m = options === null || options === void 0 ? void 0 : options.decode) !== null && _m !== void 0 ? _m : this.serializer.decode.bind(this.serializer); + break; + default: + throw new Error(`Unsupported serializer version: ${this.vsn}`); + } + // Handle worker setup + if (this.worker) { + if (typeof window !== 'undefined' && !window.Worker) { + throw new Error('Web Worker is not supported'); + } + this.workerUrl = options === null || options === void 0 ? void 0 : options.workerUrl; + } + } +} +//# sourceMappingURL=RealtimeClient.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/RealtimeClient.js.map b/backend/node_modules/@supabase/realtime-js/dist/module/RealtimeClient.js.map new file mode 100644 index 0000000..3d67665 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/RealtimeClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"RealtimeClient.js","sourceRoot":"","sources":["../../src/RealtimeClient.ts"],"names":[],"mappings":"AAAA,OAAO,gBAAmC,MAAM,yBAAyB,CAAA;AAEzE,OAAO,EACL,cAAc,EACd,gBAAgB,EAChB,eAAe,EACf,eAAe,EACf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,QAAkB,EAAE,EAAE;wBACvC,OAAO,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAA;oBACtC,CAAC,CAAC,CAAA;gBACJ,MAAK;YACP,KAAK,SAAS;gBACZ,IAAI,CAAC,MAAM,GAAG,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,MAAM,mCAAI,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,CAAA;gBAC7E,IAAI,CAAC,MAAM,GAAG,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,MAAM,mCAAI,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,CAAA;gBAC7E,MAAK;YACP;gBACE,MAAM,IAAI,KAAK,CAAC,mCAAmC,IAAI,CAAC,GAAG,EAAE,CAAC,CAAA;QAClE,CAAC;QAED,sBAAsB;QACtB,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YAChB,IAAI,OAAO,MAAM,KAAK,WAAW,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC;gBACpD,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAA;YAChD,CAAC;YACD,IAAI,CAAC,SAAS,GAAG,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,SAAS,CAAA;QACrC,CAAC;IACH,CAAC;CACF"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/RealtimePresence.d.ts b/backend/node_modules/@supabase/realtime-js/dist/module/RealtimePresence.d.ts new file mode 100644 index 0000000..583618b --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/RealtimePresence.d.ts @@ -0,0 +1,76 @@ +import type { PresenceOpts, PresenceOnJoinCallback, PresenceOnLeaveCallback } from 'phoenix'; +import type RealtimeChannel from './RealtimeChannel'; +type Presence = { + presence_ref: string; +} & T; +export type RealtimePresenceState = { + [key: string]: Presence[]; +}; +export type RealtimePresenceJoinPayload = { + event: `${REALTIME_PRESENCE_LISTEN_EVENTS.JOIN}`; + key: string; + currentPresences: Presence[]; + newPresences: Presence[]; +}; +export type RealtimePresenceLeavePayload = { + event: `${REALTIME_PRESENCE_LISTEN_EVENTS.LEAVE}`; + key: string; + currentPresences: Presence[]; + leftPresences: Presence[]; +}; +export declare enum REALTIME_PRESENCE_LISTEN_EVENTS { + SYNC = "sync", + JOIN = "join", + LEAVE = "leave" +} +type RawPresenceState = { + [key: string]: { + metas: { + phx_ref?: string; + phx_ref_prev?: string; + [key: string]: any; + }[]; + }; +}; +type RawPresenceDiff = { + joins: RawPresenceState; + leaves: RawPresenceState; +}; +export default class RealtimePresence { + channel: RealtimeChannel; + state: RealtimePresenceState; + pendingDiffs: RawPresenceDiff[]; + joinRef: string | null; + enabled: boolean; + caller: { + onJoin: PresenceOnJoinCallback; + onLeave: PresenceOnLeaveCallback; + onSync: () => void; + }; + /** + * Creates a Presence helper that keeps the local presence state in sync with the server. + * + * @param channel - The realtime channel to bind to. + * @param opts - Optional custom event names, e.g. `{ events: { state: 'state', diff: 'diff' } }`. + * + * @example + * ```ts + * const presence = new RealtimePresence(channel) + * + * channel.on('presence', ({ event, key }) => { + * console.log(`Presence ${event} on ${key}`) + * }) + * ``` + */ + constructor(channel: RealtimeChannel, opts?: PresenceOpts); +} +export {}; +//# sourceMappingURL=RealtimePresence.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/RealtimePresence.d.ts.map b/backend/node_modules/@supabase/realtime-js/dist/module/RealtimePresence.d.ts.map new file mode 100644 index 0000000..93f61dd --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/RealtimePresence.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"RealtimePresence.d.ts","sourceRoot":"","sources":["../../src/RealtimePresence.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,YAAY,EAAE,sBAAsB,EAAE,uBAAuB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YACL,OAAO,CAAC,EAAE,MAAM,CAAA;YAChB,YAAY,CAAC,EAAE,MAAM,CAAA;YACrB,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;SACnB,EAAE,CAAA;KACJ,CAAA;CACF,CAAA;AAED,KAAK,eAAe,GAAG;IACrB,KAAK,EAAE,gBAAgB,CAAA;IACvB,MAAM,EAAE,gBAAgB,CAAA;CACzB,CAAA;AAID,MAAM,CAAC,OAAO,OAAO,gBAAgB;IA+B1B,OAAO,EAAE,eAAe;IA9BjC,KAAK,EAAE,qBAAqB,CAAK;IACjC,YAAY,EAAE,eAAe,EAAE,CAAK;IACpC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAO;IAC7B,OAAO,EAAE,OAAO,CAAQ;IACxB,MAAM,EAAE;QACN,MAAM,EAAE,sBAAsB,CAAA;QAC9B,OAAO,EAAE,uBAAuB,CAAA;QAChC,MAAM,EAAE,MAAM,IAAI,CAAA;KACnB,CAIA;IAED;;;;;;;;;;;;;;OAcG;gBAEM,OAAO,EAAE,eAAe,EAC/B,IAAI,CAAC,EAAE,YAAY;CA+PtB"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/RealtimePresence.js b/backend/node_modules/@supabase/realtime-js/dist/module/RealtimePresence.js new file mode 100644 index 0000000..97ccd40 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/RealtimePresence.js @@ -0,0 +1,233 @@ +/* + This file draws heavily from https://github.com/phoenixframework/phoenix/blob/d344ec0a732ab4ee204215b31de69cf4be72e3bf/assets/js/phoenix/presence.js + License: https://github.com/phoenixframework/phoenix/blob/d344ec0a732ab4ee204215b31de69cf4be72e3bf/LICENSE.md +*/ +export var REALTIME_PRESENCE_LISTEN_EVENTS; +(function (REALTIME_PRESENCE_LISTEN_EVENTS) { + REALTIME_PRESENCE_LISTEN_EVENTS["SYNC"] = "sync"; + REALTIME_PRESENCE_LISTEN_EVENTS["JOIN"] = "join"; + REALTIME_PRESENCE_LISTEN_EVENTS["LEAVE"] = "leave"; +})(REALTIME_PRESENCE_LISTEN_EVENTS || (REALTIME_PRESENCE_LISTEN_EVENTS = {})); +export default class RealtimePresence { + /** + * Creates a Presence helper that keeps the local presence state in sync with the server. + * + * @param channel - The realtime channel to bind to. + * @param opts - Optional custom event names, e.g. `{ events: { state: 'state', diff: 'diff' } }`. + * + * @example + * ```ts + * const presence = new RealtimePresence(channel) + * + * channel.on('presence', ({ event, key }) => { + * console.log(`Presence ${event} on ${key}`) + * }) + * ``` + */ + constructor(channel, opts) { + this.channel = channel; + this.state = {}; + this.pendingDiffs = []; + this.joinRef = null; + this.enabled = false; + this.caller = { + onJoin: () => { }, + onLeave: () => { }, + onSync: () => { }, + }; + const events = (opts === null || opts === void 0 ? void 0 : opts.events) || { + state: 'presence_state', + diff: 'presence_diff', + }; + this.channel._on(events.state, {}, (newState) => { + const { onJoin, onLeave, onSync } = this.caller; + this.joinRef = this.channel._joinRef(); + this.state = RealtimePresence.syncState(this.state, newState, onJoin, onLeave); + this.pendingDiffs.forEach((diff) => { + this.state = RealtimePresence.syncDiff(this.state, diff, onJoin, onLeave); + }); + this.pendingDiffs = []; + onSync(); + }); + this.channel._on(events.diff, {}, (diff) => { + const { onJoin, onLeave, onSync } = this.caller; + if (this.inPendingSyncState()) { + this.pendingDiffs.push(diff); + } + else { + this.state = RealtimePresence.syncDiff(this.state, diff, onJoin, onLeave); + onSync(); + } + }); + this.onJoin((key, currentPresences, newPresences) => { + this.channel._trigger('presence', { + event: 'join', + key, + currentPresences, + newPresences, + }); + }); + this.onLeave((key, currentPresences, leftPresences) => { + this.channel._trigger('presence', { + event: 'leave', + key, + currentPresences, + leftPresences, + }); + }); + this.onSync(() => { + this.channel._trigger('presence', { event: 'sync' }); + }); + } + /** + * Used to sync the list of presences on the server with the + * client's state. + * + * An optional `onJoin` and `onLeave` callback can be provided to + * react to changes in the client's local presences across + * disconnects and reconnects with the server. + * + * @internal + */ + static syncState(currentState, newState, onJoin, onLeave) { + const state = this.cloneDeep(currentState); + const transformedState = this.transformState(newState); + const joins = {}; + const leaves = {}; + this.map(state, (key, presences) => { + if (!transformedState[key]) { + leaves[key] = presences; + } + }); + this.map(transformedState, (key, newPresences) => { + const currentPresences = state[key]; + if (currentPresences) { + const newPresenceRefs = newPresences.map((m) => m.presence_ref); + const curPresenceRefs = currentPresences.map((m) => m.presence_ref); + const joinedPresences = newPresences.filter((m) => curPresenceRefs.indexOf(m.presence_ref) < 0); + const leftPresences = currentPresences.filter((m) => newPresenceRefs.indexOf(m.presence_ref) < 0); + if (joinedPresences.length > 0) { + joins[key] = joinedPresences; + } + if (leftPresences.length > 0) { + leaves[key] = leftPresences; + } + } + else { + joins[key] = newPresences; + } + }); + return this.syncDiff(state, { joins, leaves }, onJoin, onLeave); + } + /** + * Used to sync a diff of presence join and leave events from the + * server, as they happen. + * + * Like `syncState`, `syncDiff` accepts optional `onJoin` and + * `onLeave` callbacks to react to a user joining or leaving from a + * device. + * + * @internal + */ + static syncDiff(state, diff, onJoin, onLeave) { + const { joins, leaves } = { + joins: this.transformState(diff.joins), + leaves: this.transformState(diff.leaves), + }; + if (!onJoin) { + onJoin = () => { }; + } + if (!onLeave) { + onLeave = () => { }; + } + this.map(joins, (key, newPresences) => { + var _a; + const currentPresences = (_a = state[key]) !== null && _a !== void 0 ? _a : []; + state[key] = this.cloneDeep(newPresences); + if (currentPresences.length > 0) { + const joinedPresenceRefs = state[key].map((m) => m.presence_ref); + const curPresences = currentPresences.filter((m) => joinedPresenceRefs.indexOf(m.presence_ref) < 0); + state[key].unshift(...curPresences); + } + onJoin(key, currentPresences, newPresences); + }); + this.map(leaves, (key, leftPresences) => { + let currentPresences = state[key]; + if (!currentPresences) + return; + const presenceRefsToRemove = leftPresences.map((m) => m.presence_ref); + currentPresences = currentPresences.filter((m) => presenceRefsToRemove.indexOf(m.presence_ref) < 0); + state[key] = currentPresences; + onLeave(key, currentPresences, leftPresences); + if (currentPresences.length === 0) + delete state[key]; + }); + return state; + } + /** @internal */ + static map(obj, func) { + return Object.getOwnPropertyNames(obj).map((key) => func(key, obj[key])); + } + /** + * Remove 'metas' key + * Change 'phx_ref' to 'presence_ref' + * Remove 'phx_ref' and 'phx_ref_prev' + * + * @example + * // returns { + * abc123: [ + * { presence_ref: '2', user_id: 1 }, + * { presence_ref: '3', user_id: 2 } + * ] + * } + * RealtimePresence.transformState({ + * abc123: { + * metas: [ + * { phx_ref: '2', phx_ref_prev: '1' user_id: 1 }, + * { phx_ref: '3', user_id: 2 } + * ] + * } + * }) + * + * @internal + */ + static transformState(state) { + state = this.cloneDeep(state); + return Object.getOwnPropertyNames(state).reduce((newState, key) => { + const presences = state[key]; + if ('metas' in presences) { + newState[key] = presences.metas.map((presence) => { + presence['presence_ref'] = presence['phx_ref']; + delete presence['phx_ref']; + delete presence['phx_ref_prev']; + return presence; + }); + } + else { + newState[key] = presences; + } + return newState; + }, {}); + } + /** @internal */ + static cloneDeep(obj) { + return JSON.parse(JSON.stringify(obj)); + } + /** @internal */ + onJoin(callback) { + this.caller.onJoin = callback; + } + /** @internal */ + onLeave(callback) { + this.caller.onLeave = callback; + } + /** @internal */ + onSync(callback) { + this.caller.onSync = callback; + } + /** @internal */ + inPendingSyncState() { + return !this.joinRef || this.joinRef !== this.channel._joinRef(); + } +} +//# sourceMappingURL=RealtimePresence.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/RealtimePresence.js.map b/backend/node_modules/@supabase/realtime-js/dist/module/RealtimePresence.js.map new file mode 100644 index 0000000..f5a1603 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/RealtimePresence.js.map @@ -0,0 +1 @@ +{"version":3,"file":"RealtimePresence.js","sourceRoot":"","sources":["../../src/RealtimePresence.ts"],"names":[],"mappings":"AAAA;;;EAGE;AA2BF,MAAM,CAAN,IAAY,+BAIX;AAJD,WAAY,+BAA+B;IACzC,gDAAa,CAAA;IACb,gDAAa,CAAA;IACb,kDAAe,CAAA;A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M,GAAG,QAAQ,CAAA;IAC/B,CAAC;IAED,gBAAgB;IACR,OAAO,CAAC,QAAiC;QAC/C,IAAI,CAAC,MAAM,CAAC,OAAO,GAAG,QAAQ,CAAA;IAChC,CAAC;IAED,gBAAgB;IACR,MAAM,CAAC,QAAoB;QACjC,IAAI,CAAC,MAAM,CAAC,MAAM,GAAG,QAAQ,CAAA;IAC/B,CAAC;IAED,gBAAgB;IACR,kBAAkB;QACxB,OAAO,CAAC,IAAI,CAAC,OAAO,IAAI,IAAI,CAAC,OAAO,KAAK,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAA;IAClE,CAAC;CACF"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/index.d.ts b/backend/node_modules/@supabase/realtime-js/dist/module/index.d.ts new file mode 100644 index 0000000..b7dbd1c --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/index.d.ts @@ -0,0 +1,6 @@ +import RealtimeClient, { RealtimeClientOptions, RealtimeMessage, RealtimeRemoveChannelResponse, WebSocketLikeConstructor } from './RealtimeClient'; +import RealtimeChannel, { RealtimeChannelOptions, RealtimeChannelSendResponse, RealtimePostgresChangesFilter, RealtimePostgresChangesPayload, RealtimePostgresInsertPayload, RealtimePostgresUpdatePayload, RealtimePostgresDeletePayload, REALTIME_LISTEN_TYPES, REALTIME_POSTGRES_CHANGES_LISTEN_EVENT, REALTIME_SUBSCRIBE_STATES, REALTIME_CHANNEL_STATES } from './RealtimeChannel'; +import RealtimePresence, { RealtimePresenceState, RealtimePresenceJoinPayload, RealtimePresenceLeavePayload, REALTIME_PRESENCE_LISTEN_EVENTS } from './RealtimePresence'; +import WebSocketFactory, { WebSocketLike } from './lib/websocket-factory'; +export { RealtimePresence, RealtimeChannel, RealtimeChannelOptions, RealtimeChannelSendResponse, RealtimeClient, RealtimeClientOptions, RealtimeMessage, RealtimePostgresChangesFilter, RealtimePostgresChangesPayload, RealtimePostgresInsertPayload, RealtimePostgresUpdatePayload, RealtimePostgresDeletePayload, RealtimePresenceJoinPayload, RealtimePresenceLeavePayload, RealtimePresenceState, RealtimeRemoveChannelResponse, REALTIME_LISTEN_TYPES, REALTIME_POSTGRES_CHANGES_LISTEN_EVENT, REALTIME_PRESENCE_LISTEN_EVENTS, REALTIME_SUBSCRIBE_STATES, REALTIME_CHANNEL_STATES, WebSocketFactory, WebSocketLike, WebSocketLikeConstructor, }; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/index.d.ts.map b/backend/node_modules/@supabase/realtime-js/dist/module/index.d.ts.map new file mode 100644 index 0000000..4e16838 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,EAAE,EACrB,qBAAqB,EACrB,eAAe,EACf,6BAA6B,EAC7B,wBAAwB,EACzB,MAAM,kBAAkB,CAAA;AACzB,OAAO,eAAe,EAAE,EACtB,sBAAsB,EACtB,2BAA2B,EAC3B,6BAA6B,EAC7B,8BAA8B,EAC9B,6BAA6B,EAC7B,6BAA6B,EAC7B,6BAA6B,EAC7B,qBAAqB,EACrB,sCAAsC,EACtC,yBAAyB,EACzB,uBAAuB,EACxB,MAAM,mBAAmB,CAAA;AAC1B,OAAO,gBAAgB,EAAE,EACvB,qBAAqB,EACrB,2BAA2B,EAC3B,4BAA4B,EAC5B,+BAA+B,EAChC,MAAM,oBAAoB,CAAA;AAC3B,OAAO,gBAAgB,EAAE,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAA;AAEzE,OAAO,EACL,gBAAgB,EAChB,eAAe,EACf,sBAAsB,EACtB,2BAA2B,EAC3B,cAAc,EACd,qBAAqB,EACrB,eAAe,EACf,6BAA6B,EAC7B,8BAA8B,EAC9B,6BAA6B,EAC7B,6BAA6B,EAC7B,6BAA6B,EAC7B,2BAA2B,EAC3B,4BAA4B,EAC5B,qBAAqB,EACrB,6BAA6B,EAC7B,qBAAqB,EACrB,sCAAsC,EACtC,+BAA+B,EAC/B,yBAAyB,EACzB,uBAAuB,EACvB,gBAAgB,EAChB,aAAa,EACb,wBAAwB,GACzB,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/index.js b/backend/node_modules/@supabase/realtime-js/dist/module/index.js new file mode 100644 index 0000000..60656c6 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/index.js @@ -0,0 +1,6 @@ +import RealtimeClient from './RealtimeClient'; +import RealtimeChannel, { REALTIME_LISTEN_TYPES, REALTIME_POSTGRES_CHANGES_LISTEN_EVENT, REALTIME_SUBSCRIBE_STATES, REALTIME_CHANNEL_STATES, } from './RealtimeChannel'; +import RealtimePresence, { REALTIME_PRESENCE_LISTEN_EVENTS, } from './RealtimePresence'; +import WebSocketFactory from './lib/websocket-factory'; +export { RealtimePresence, RealtimeChannel, RealtimeClient, REALTIME_LISTEN_TYPES, REALTIME_POSTGRES_CHANGES_LISTEN_EVENT, REALTIME_PRESENCE_LISTEN_EVENTS, REALTIME_SUBSCRIBE_STATES, REALTIME_CHANNEL_STATES, WebSocketFactory, }; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/index.js.map b/backend/node_modules/@supabase/realtime-js/dist/module/index.js.map new file mode 100644 index 0000000..95df7c1 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,cAKN,MAAM,kBAAkB,CAAA;AACzB,OAAO,eAAe,EAAE,EAQtB,qBAAqB,EACrB,sCAAsC,EACtC,yBAAyB,EACzB,uBAAuB,GACxB,MAAM,mBAAmB,CAAA;AAC1B,OAAO,gBAAgB,EAAE,EAIvB,+BAA+B,GAChC,MAAM,oBAAoB,CAAA;AAC3B,OAAO,gBAAmC,MAAM,yBAAyB,CAAA;AAEzE,OAAO,EACL,gBAAgB,EAChB,eAAe,EAGf,cAAc,EAYd,qBAAqB,EACrB,sCAAsC,EACtC,+BAA+B,EAC/B,yBAAyB,EACzB,uBAAuB,EACvB,gBAAgB,GAGjB,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/lib/constants.d.ts b/backend/node_modules/@supabase/realtime-js/dist/module/lib/constants.d.ts new file mode 100644 index 0000000..73410d4 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/lib/constants.d.ts @@ -0,0 +1,39 @@ +export declare const DEFAULT_VERSION = "realtime-js/2.87.1"; +export declare const VSN_1_0_0: string; +export declare const VSN_2_0_0: string; +export declare const DEFAULT_VSN: string; +export declare const VERSION = "2.87.1"; +export declare const DEFAULT_TIMEOUT = 10000; +export declare const WS_CLOSE_NORMAL = 1000; +export declare const MAX_PUSH_BUFFER_SIZE = 100; +export declare enum SOCKET_STATES { + connecting = 0, + open = 1, + closing = 2, + closed = 3 +} +export declare enum CHANNEL_STATES { + closed = "closed", + errored = "errored", + joined = "joined", + joining = "joining", + leaving = "leaving" +} +export declare enum CHANNEL_EVENTS { + close = "phx_close", + error = "phx_error", + join = "phx_join", + reply = "phx_reply", + leave = "phx_leave", + access_token = "access_token" +} +export declare enum TRANSPORTS { + websocket = "websocket" +} +export declare enum CONNECTION_STATE { + Connecting = "connecting", + Open = "open", + Closing = "closing", + Closed = "closed" +} +//# sourceMappingURL=constants.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/lib/constants.d.ts.map b/backend/node_modules/@supabase/realtime-js/dist/module/lib/constants.d.ts.map new file mode 100644 index 0000000..1e277aa --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/lib/constants.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,eAAe,uBAA2B,CAAA;AAEvD,eAAO,MAAM,SAAS,EAAE,MAAgB,CAAA;AACxC,eAAO,MAAM,SAAS,EAAE,MAAgB,CAAA;AACxC,eAAO,MAAM,WAAW,EAAE,MAAkB,CAAA;AAE5C,eAAO,MAAM,OAAO,WAAU,CAAA;AAE9B,eAAO,MAAM,eAAe,QAAQ,CAAA;AAEpC,eAAO,MAAM,eAAe,OAAO,CAAA;AACnC,eAAO,MAAM,oBAAoB,MAAM,CAAA;AAEvC,oBAAY,aAAa;IACvB,UAAU,IAAI;IACd,IAAI,IAAI;IACR,OAAO,IAAI;IACX,MAAM,IAAI;CACX;AAED,oBAAY,cAAc;IACxB,MAAM,WAAW;IACjB,OAAO,YAAY;IACnB,MAAM,WAAW;IACjB,OAAO,YAAY;IACnB,OAAO,YAAY;CACpB;AAED,oBAAY,cAAc;IACxB,KAAK,cAAc;IACnB,KAAK,cAAc;IACnB,IAAI,aAAa;IACjB,KAAK,cAAc;IACnB,KAAK,cAAc;IACnB,YAAY,iBAAiB;CAC9B;AAED,oBAAY,UAAU;IACpB,SAAS,cAAc;CACxB;AAED,oBAAY,gBAAgB;IAC1B,UAAU,eAAe;IACzB,IAAI,SAAS;IACb,OAAO,YAAY;IACnB,MAAM,WAAW;CAClB"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/lib/constants.js b/backend/node_modules/@supabase/realtime-js/dist/module/lib/constants.js new file mode 100644 index 0000000..4546e8c --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/lib/constants.js @@ -0,0 +1,45 @@ +import { version } from './version'; +export const DEFAULT_VERSION = `realtime-js/${version}`; +export const VSN_1_0_0 = '1.0.0'; +export const VSN_2_0_0 = '2.0.0'; +export const DEFAULT_VSN = VSN_1_0_0; +export const VERSION = version; +export const DEFAULT_TIMEOUT = 10000; +export const WS_CLOSE_NORMAL = 1000; +export const MAX_PUSH_BUFFER_SIZE = 100; +export var SOCKET_STATES; +(function (SOCKET_STATES) { + SOCKET_STATES[SOCKET_STATES["connecting"] = 0] = "connecting"; + SOCKET_STATES[SOCKET_STATES["open"] = 1] = "open"; + SOCKET_STATES[SOCKET_STATES["closing"] = 2] = "closing"; + SOCKET_STATES[SOCKET_STATES["closed"] = 3] = "closed"; +})(SOCKET_STATES || (SOCKET_STATES = {})); +export var CHANNEL_STATES; +(function (CHANNEL_STATES) { + CHANNEL_STATES["closed"] = "closed"; + CHANNEL_STATES["errored"] = "errored"; + CHANNEL_STATES["joined"] = "joined"; + CHANNEL_STATES["joining"] = "joining"; + CHANNEL_STATES["leaving"] = "leaving"; +})(CHANNEL_STATES || (CHANNEL_STATES = {})); +export var CHANNEL_EVENTS; +(function (CHANNEL_EVENTS) { + CHANNEL_EVENTS["close"] = "phx_close"; + CHANNEL_EVENTS["error"] = "phx_error"; + CHANNEL_EVENTS["join"] = "phx_join"; + CHANNEL_EVENTS["reply"] = "phx_reply"; + CHANNEL_EVENTS["leave"] = "phx_leave"; + CHANNEL_EVENTS["access_token"] = "access_token"; +})(CHANNEL_EVENTS || (CHANNEL_EVENTS = {})); +export var TRANSPORTS; +(function (TRANSPORTS) { + TRANSPORTS["websocket"] = "websocket"; +})(TRANSPORTS || (TRANSPORTS = {})); +export var CONNECTION_STATE; +(function (CONNECTION_STATE) { + CONNECTION_STATE["Connecting"] = "connecting"; + CONNECTION_STATE["Open"] = "open"; + CONNECTION_STATE["Closing"] = "closing"; + CONNECTION_STATE["Closed"] = "closed"; +})(CONNECTION_STATE || (CONNECTION_STATE = {})); +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/lib/constants.js.map b/backend/node_modules/@supabase/realtime-js/dist/module/lib/constants.js.map new file mode 100644 index 0000000..a5fdf2d --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/lib/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src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zB,iCAAa,CAAA;IACb,uCAAmB,CAAA;IACnB,qCAAiB,CAAA;AACnB,CAAC,EALW,gBAAgB,KAAhB,gBAAgB,QAK3B"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/lib/push.d.ts b/backend/node_modules/@supabase/realtime-js/dist/module/lib/push.d.ts new file mode 100644 index 0000000..604c4f7 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/lib/push.d.ts @@ -0,0 +1,48 @@ +import type RealtimeChannel from '../RealtimeChannel'; +export default class Push { + channel: RealtimeChannel; + event: string; + payload: { + [key: string]: any; + }; + timeout: number; + sent: boolean; + timeoutTimer: number | undefined; + ref: string; + receivedResp: { + status: string; + response: { + [key: string]: any; + }; + } | null; + recHooks: { + status: string; + callback: Function; + }[]; + refEvent: string | null; + /** + * Initializes the Push + * + * @param channel The Channel + * @param event The event, for example `"phx_join"` + * @param payload The payload, for example `{user_id: 123}` + * @param timeout The push timeout in milliseconds + */ + constructor(channel: RealtimeChannel, event: string, payload?: { + [key: string]: any; + }, timeout?: number); + resend(timeout: number): void; + send(): void; + updatePayload(payload: { + [key: string]: any; + }): void; + receive(status: string, callback: Function): this; + startTimeout(): void; + trigger(status: string, response: any): void; + destroy(): void; + private _cancelRefEvent; + private _cancelTimeout; + private _matchReceive; + private _hasReceived; +} +//# sourceMappingURL=push.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/lib/push.d.ts.map b/backend/node_modules/@supabase/realtime-js/dist/module/lib/push.d.ts.map new file mode 100644 index 0000000..9b612a0 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/lib/push.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"push.d.ts","sourceRoot":"","sources":["../../../src/lib/push.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,eAAe,MAAM,oBAAoB,CAAA;AAErD,MAAM,CAAC,OAAO,OAAO,IAAI;IAuBd,OAAO,EAAE,eAAe;IACxB,KAAK,EAAE,MAAM;IACb,OAAO,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KAAE;IAC/B,OAAO,EAAE,MAAM;IAzBxB,IAAI,EAAE,OAAO,CAAQ;IACrB,YAAY,EAAE,MAAM,GAAG,SAAS,CAAY;IAC5C,GAAG,EAAE,MAAM,CAAK;IAChB,YAAY,EAAE;QACZ,MAAM,EAAE,MAAM,CAAA;QACd,QAAQ,EAAE;YAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;SAAE,CAAA;KACjC,GAAG,IAAI,CAAO;IACf,QAAQ,EAAE;QACR,MAAM,EAAE,MAAM,CAAA;QACd,QAAQ,EAAE,QAAQ,CAAA;KACnB,EAAE,CAAK;IACR,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAO;IAE9B;;;;;;;OAOG;gBAEM,OAAO,EAAE,eAAe,EACxB,KAAK,EAAE,MAAM,EACb,OAAO,GAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KAAO,EACpC,OAAO,GAAE,MAAwB;IAG1C,MAAM,CAAC,OAAO,EAAE,MAAM;IAUtB,IAAI;IAeJ,aAAa,CAAC,OAAO,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KAAE,GAAG,IAAI;IAIpD,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ;IAS1C,YAAY;IAqBZ,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG;IAIrC,OAAO;IAKP,OAAO,CAAC,eAAe;IAQvB,OAAO,CAAC,cAAc;IAKtB,OAAO,CAAC,aAAa;IAIrB,OAAO,CAAC,YAAY;CAGrB"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/lib/push.js b/backend/node_modules/@supabase/realtime-js/dist/module/lib/push.js new file mode 100644 index 0000000..5fa90fe --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/lib/push.js @@ -0,0 +1,99 @@ +import { DEFAULT_TIMEOUT } from '../lib/constants'; +export default class Push { + /** + * Initializes the Push + * + * @param channel The Channel + * @param event The event, for example `"phx_join"` + * @param payload The payload, for example `{user_id: 123}` + * @param timeout The push timeout in milliseconds + */ + constructor(channel, event, payload = {}, timeout = DEFAULT_TIMEOUT) { + this.channel = channel; + this.event = event; + this.payload = payload; + this.timeout = timeout; + this.sent = false; + this.timeoutTimer = undefined; + this.ref = ''; + this.receivedResp = null; + this.recHooks = []; + this.refEvent = null; + } + resend(timeout) { + this.timeout = timeout; + this._cancelRefEvent(); + this.ref = ''; + this.refEvent = null; + this.receivedResp = null; + this.sent = false; + this.send(); + } + send() { + if (this._hasReceived('timeout')) { + return; + } + this.startTimeout(); + this.sent = true; + this.channel.socket.push({ + topic: this.channel.topic, + event: this.event, + payload: this.payload, + ref: this.ref, + join_ref: this.channel._joinRef(), + }); + } + updatePayload(payload) { + this.payload = Object.assign(Object.assign({}, this.payload), payload); + } + receive(status, callback) { + var _a; + if (this._hasReceived(status)) { + callback((_a = this.receivedResp) === null || _a === void 0 ? void 0 : _a.response); + } + this.recHooks.push({ status, callback }); + return this; + } + startTimeout() { + if (this.timeoutTimer) { + return; + } + this.ref = this.channel.socket._makeRef(); + this.refEvent = this.channel._replyEventName(this.ref); + const callback = (payload) => { + this._cancelRefEvent(); + this._cancelTimeout(); + this.receivedResp = payload; + this._matchReceive(payload); + }; + this.channel._on(this.refEvent, {}, callback); + this.timeoutTimer = setTimeout(() => { + this.trigger('timeout', {}); + }, this.timeout); + } + trigger(status, response) { + if (this.refEvent) + this.channel._trigger(this.refEvent, { status, response }); + } + destroy() { + this._cancelRefEvent(); + this._cancelTimeout(); + } + _cancelRefEvent() { + if (!this.refEvent) { + return; + } + this.channel._off(this.refEvent, {}); + } + _cancelTimeout() { + clearTimeout(this.timeoutTimer); + this.timeoutTimer = undefined; + } + _matchReceive({ status, response }) { + this.recHooks.filter((h) => h.status === status).forEach((h) => h.callback(response)); + } + _hasReceived(status) { + return this.receivedResp && this.receivedResp.status === status; + } +} +//# sourceMappingURL=push.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/lib/push.js.map b/backend/node_modules/@supabase/realtime-js/dist/module/lib/push.js.map new file mode 100644 index 0000000..4c702b1 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/lib/push.js.map @@ -0,0 +1 @@ +{"version":3,"file":"push.js","sourceRoot":"","sources":["../../../src/lib/push.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAA;AAGlD,MAAM,CAAC,OAAO,OAAO,IAAI;IAcvB;;;;;;;OAOG;IACH,YACS,OAAwB,EACxB,KAAa,EACb,UAAkC,EAAE,EACpC,UAAkB,eAAe;QAHjC,YAAO,GAAP,OAAO,CAAiB;QACxB,UAAK,GAAL,KAAK,CAAQ;QACb,YAAO,GAAP,OAAO,CAA6B;QACpC,YAAO,GAAP,OAAO,CAA0B;QAzB1C,SAAI,GAAY,KAAK,CAAA;QACrB,iBAAY,GAAuB,SAAS,CAAA;QAC5C,QAAG,GAAW,EAAE,CAAA;QAChB,iBAAY,GAGD,IAAI,CAAA;QACf,aAAQ,GAGF,EAAE,CAAA;QACR,aAAQ,GAAkB,IAAI,CAAA;IAe3B,CAAC;IAEJ,MAAM,CAAC,OAAe;QACpB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;QACtB,IAAI,CAAC,eAAe,EAAE,CAAA;QACtB,IAAI,CAAC,GAAG,GAAG,EAAE,CAAA;QACb,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAA;QACpB,IAAI,CAAC,YAAY,GAAG,IAAI,CAAA;QACxB,IAAI,CAAC,IAAI,GAAG,KAAK,CAAA;QACjB,IAAI,CAAC,IAAI,EAAE,CAAA;IACb,CAAC;IAED,IAAI;QACF,IAAI,IAAI,CAAC,YAAY,CAAC,SAAS,CAAC,EAAE,CAAC;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AAI,CAAC,YAAY,IAAI,IAAI,CAAC,YAAY,CAAC,MAAM,KAAK,MAAM,CAAA;IACjE,CAAC;CACF"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/lib/serializer.d.ts b/backend/node_modules/@supabase/realtime-js/dist/module/lib/serializer.d.ts new file mode 100644 index 0000000..39fbd2a --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/lib/serializer.d.ts @@ -0,0 +1,33 @@ +export type Msg = { + join_ref?: string | null; + ref?: string | null; + topic: string; + event: string; + payload: T; +}; +export default class Serializer { + HEADER_LENGTH: number; + USER_BROADCAST_PUSH_META_LENGTH: number; + KINDS: { + userBroadcastPush: number; + userBroadcast: number; + }; + BINARY_ENCODING: number; + JSON_ENCODING: number; + BROADCAST_EVENT: string; + allowedMetadataKeys: string[]; + constructor(allowedMetadataKeys?: string[] | null); + encode(msg: Msg<{ + [key: string]: any; + }>, callback: (result: ArrayBuffer | string) => any): any; + private _binaryEncodeUserBroadcastPush; + private _encodeBinaryUserBroadcastPush; + private _encodeJsonUserBroadcastPush; + private _encodeUserBroadcastPush; + decode(rawPayload: ArrayBuffer | string, callback: Function): any; + private _binaryDecode; + private _decodeUserBroadcast; + private _isArrayBuffer; + private _pick; +} +//# sourceMappingURL=serializer.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/lib/serializer.d.ts.map b/backend/node_modules/@supabase/realtime-js/dist/module/lib/serializer.d.ts.map new file mode 100644 index 0000000..0bb397b --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/lib/serializer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"serializer.d.ts","sourceRoot":"","sources":["../../../src/lib/serializer.ts"],"names":[],"mappings":"AAEA,MAAM,MAAM,GAAG,CAAC,CAAC,IAAI;IACnB,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACxB,GAAG,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACnB,KAAK,EAAE,MAAM,CAAA;IACb,KAAK,EAAE,MAAM,CAAA;IACb,OAAO,EAAE,CAAC,CAAA;CACX,CAAA;AAED,MAAM,CAAC,OAAO,OAAO,UAAU;IAC7B,aAAa,SAAI;IACjB,+BAA+B,SAAI;IACnC,KAAK;;;MAA6C;IAClD,eAAe,SAAI;IACnB,aAAa,SAAI;IACjB,eAAe,SAAc;IAE7B,mBAAmB,EAAE,MAAM,EAAE,CAAK;gBAEtB,mBAAmB,CAAC,EAAE,MAAM,EAAE,GAAG,IAAI;IAIjD,MAAM,CAAC,GAAG,EAAE,GAAG,CAAC;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KAAE,CAAC,EAAE,QAAQ,EAAE,CAAC,MAAM,EAAE,WAAW,GAAG,MAAM,KAAK,GAAG;IAexF,OAAO,CAAC,8BAA8B;IAQtC,OAAO,CAAC,8BAA8B;IAKtC,OAAO,CAAC,4BAA4B;IAOpC,OAAO,CAAC,wBAAwB;IAkEhC,MAAM,CAAC,UAAU,EAAE,WAAW,GAAG,MAAM,EAAE,QAAQ,EAAE,QAAQ;IAe3D,OAAO,CAAC,aAAa;IAUrB,OAAO,CAAC,oBAAoB;IA0C5B,OAAO,CAAC,cAAc;IAItB,OAAO,CAAC,KAAK;CAMd"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/lib/serializer.js b/backend/node_modules/@supabase/realtime-js/dist/module/lib/serializer.js new file mode 100644 index 0000000..fea5a3f --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/lib/serializer.js @@ -0,0 +1,152 @@ +export default class Serializer { + constructor(allowedMetadataKeys) { + this.HEADER_LENGTH = 1; + this.USER_BROADCAST_PUSH_META_LENGTH = 6; + this.KINDS = { userBroadcastPush: 3, userBroadcast: 4 }; + this.BINARY_ENCODING = 0; + this.JSON_ENCODING = 1; + this.BROADCAST_EVENT = 'broadcast'; + this.allowedMetadataKeys = []; + this.allowedMetadataKeys = allowedMetadataKeys !== null && allowedMetadataKeys !== void 0 ? allowedMetadataKeys : []; + } + encode(msg, callback) { + if (msg.event === this.BROADCAST_EVENT && + !(msg.payload instanceof ArrayBuffer) && + typeof msg.payload.event === 'string') { + return callback(this._binaryEncodeUserBroadcastPush(msg)); + } + let payload = [msg.join_ref, msg.ref, msg.topic, msg.event, msg.payload]; + return callback(JSON.stringify(payload)); + } + _binaryEncodeUserBroadcastPush(message) { + var _a; + if (this._isArrayBuffer((_a = message.payload) === null || _a === void 0 ? void 0 : _a.payload)) { + return this._encodeBinaryUserBroadcastPush(message); + } + else { + return this._encodeJsonUserBroadcastPush(message); + } + } + _encodeBinaryUserBroadcastPush(message) { + var _a, _b; + const userPayload = (_b = (_a = message.payload) === null || _a === void 0 ? void 0 : _a.payload) !== null && _b !== void 0 ? _b : new ArrayBuffer(0); + return this._encodeUserBroadcastPush(message, this.BINARY_ENCODING, userPayload); + } + _encodeJsonUserBroadcastPush(message) { + var _a, _b; + const userPayload = (_b = (_a = message.payload) === null || _a === void 0 ? void 0 : _a.payload) !== null && _b !== void 0 ? _b : {}; + const encoder = new TextEncoder(); + const encodedUserPayload = encoder.encode(JSON.stringify(userPayload)).buffer; + return this._encodeUserBroadcastPush(message, this.JSON_ENCODING, encodedUserPayload); + } + _encodeUserBroadcastPush(message, encodingType, encodedPayload) { + var _a, _b; + const topic = message.topic; + const ref = (_a = message.ref) !== null && _a !== void 0 ? _a : ''; + const joinRef = (_b = message.join_ref) !== null && _b !== void 0 ? _b : ''; + const userEvent = message.payload.event; + // Filter metadata based on allowed keys + const rest = this.allowedMetadataKeys + ? this._pick(message.payload, this.allowedMetadataKeys) + : {}; + const metadata = Object.keys(rest).length === 0 ? '' : JSON.stringify(rest); + // Validate lengths don't exceed uint8 max value (255) + if (joinRef.length > 255) { + throw new Error(`joinRef length ${joinRef.length} exceeds maximum of 255`); + } + if (ref.length > 255) { + throw new Error(`ref length ${ref.length} exceeds maximum of 255`); + } + if (topic.length > 255) { + throw new Error(`topic length ${topic.length} exceeds maximum of 255`); + } + if (userEvent.length > 255) { + throw new Error(`userEvent length ${userEvent.length} exceeds maximum of 255`); + } + if (metadata.length > 255) { + throw new Error(`metadata length ${metadata.length} exceeds maximum of 255`); + } + const metaLength = this.USER_BROADCAST_PUSH_META_LENGTH + + joinRef.length + + ref.length + + topic.length + + userEvent.length + + metadata.length; + const header = new ArrayBuffer(this.HEADER_LENGTH + metaLength); + let view = new DataView(header); + let offset = 0; + view.setUint8(offset++, this.KINDS.userBroadcastPush); // kind + view.setUint8(offset++, joinRef.length); + view.setUint8(offset++, ref.length); + view.setUint8(offset++, topic.length); + view.setUint8(offset++, userEvent.length); + view.setUint8(offset++, metadata.length); + view.setUint8(offset++, encodingType); + Array.from(joinRef, (char) => view.setUint8(offset++, char.charCodeAt(0))); + Array.from(ref, (char) => view.setUint8(offset++, char.charCodeAt(0))); + Array.from(topic, (char) => view.setUint8(offset++, char.charCodeAt(0))); + Array.from(userEvent, (char) => view.setUint8(offset++, char.charCodeAt(0))); + Array.from(metadata, (char) => view.setUint8(offset++, char.charCodeAt(0))); + var combined = new Uint8Array(header.byteLength + encodedPayload.byteLength); + combined.set(new Uint8Array(header), 0); + combined.set(new Uint8Array(encodedPayload), header.byteLength); + return combined.buffer; + } + decode(rawPayload, callback) { + if (this._isArrayBuffer(rawPayload)) { + let result = this._binaryDecode(rawPayload); + return callback(result); + } + if (typeof rawPayload === 'string') { + const jsonPayload = JSON.parse(rawPayload); + const [join_ref, ref, topic, event, payload] = jsonPayload; + return callback({ join_ref, ref, topic, event, payload }); + } + return callback({}); + } + _binaryDecode(buffer) { + const view = new DataView(buffer); + const kind = view.getUint8(0); + const decoder = new TextDecoder(); + switch (kind) { + case this.KINDS.userBroadcast: + return this._decodeUserBroadcast(buffer, view, decoder); + } + } + _decodeUserBroadcast(buffer, view, decoder) { + const topicSize = view.getUint8(1); + const userEventSize = view.getUint8(2); + const metadataSize = view.getUint8(3); + const payloadEncoding = view.getUint8(4); + let offset = this.HEADER_LENGTH + 4; + const topic = decoder.decode(buffer.slice(offset, offset + topicSize)); + offset = offset + topicSize; + const userEvent = decoder.decode(buffer.slice(offset, offset + userEventSize)); + offset = offset + userEventSize; + const metadata = decoder.decode(buffer.slice(offset, offset + metadataSize)); + offset = offset + metadataSize; + const payload = buffer.slice(offset, buffer.byteLength); + const parsedPayload = payloadEncoding === this.JSON_ENCODING ? JSON.parse(decoder.decode(payload)) : payload; + const data = { + type: this.BROADCAST_EVENT, + event: userEvent, + payload: parsedPayload, + }; + // Metadata is optional and always JSON encoded + if (metadataSize > 0) { + data['meta'] = JSON.parse(metadata); + } + return { join_ref: null, ref: null, topic: topic, event: this.BROADCAST_EVENT, payload: data }; + } + _isArrayBuffer(buffer) { + var _a; + return buffer instanceof ArrayBuffer || ((_a = buffer === null || buffer === void 0 ? void 0 : buffer.constructor) === null || _a === void 0 ? void 0 : _a.name) === 'ArrayBuffer'; + } + _pick(obj, keys) { + if (!obj || typeof obj !== 'object') { + return {}; + } + return Object.fromEntries(Object.entries(obj).filter(([key]) => keys.includes(key))); + } +} +//# sourceMappingURL=serializer.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/lib/serializer.js.map b/backend/node_modules/@supabase/realtime-js/dist/module/lib/serializer.js.map new file mode 100644 index 0000000..1e3b86b --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/lib/serializer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"serializer.js","sourceRoot":"","sources":["../../../src/lib/serializer.ts"],"names":[],"mappings":"AAUA,MAAM,CAAC,OAAO,OAAO,UAAU;IAU7B,YAAY,mBAAqC;QATjD,kBAAa,GAAG,CAAC,CAAA;QACjB,oCAA+B,GAAG,CAAC,CAAA;QACnC,UAAK,GAAG,EAAE,iBAAiB,EAAE,CAAC,EAAE,aAAa,EAAE,CAAC,EAAE,CAAA;QAClD,oBAAe,GAAG,CAAC,CAAA;QACnB,kBAAa,GAAG,CAAC,CAAA;QACjB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AY,GAAG,CAAC,EAAE,CAAC;YACrB,IAAI,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAA;QACrC,CAAC;QAED,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,CAAC,eAAe,EAAE,OAAO,EAAE,IAAI,EAAE,CAAA;IAChG,CAAC;IAEO,cAAc,CAAC,MAAW;;QAChC,OAAO,MAAM,YAAY,WAAW,IAAI,CAAA,MAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,WAAW,0CAAE,IAAI,MAAK,aAAa,CAAA;IACrF,CAAC;IAEO,KAAK,CAAC,GAA2C,EAAE,IAAc;QACvE,IAAI,CAAC,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE,CAAC;YACpC,OAAO,EAAE,CAAA;QACX,CAAC;QACD,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAA;IACtF,CAAC;CACF"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/lib/timer.d.ts b/backend/node_modules/@supabase/realtime-js/dist/module/lib/timer.d.ts new file mode 100644 index 0000000..d5df4a6 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/lib/timer.d.ts @@ -0,0 +1,22 @@ +/** + * Creates a timer that accepts a `timerCalc` function to perform calculated timeout retries, such as exponential backoff. + * + * @example + * let reconnectTimer = new Timer(() => this.connect(), function(tries){ + * return [1000, 5000, 10000][tries - 1] || 10000 + * }) + * reconnectTimer.scheduleTimeout() // fires after 1000 + * reconnectTimer.scheduleTimeout() // fires after 5000 + * reconnectTimer.reset() + * reconnectTimer.scheduleTimeout() // fires after 1000 + */ +export default class Timer { + callback: Function; + timerCalc: Function; + timer: number | undefined; + tries: number; + constructor(callback: Function, timerCalc: Function); + reset(): void; + scheduleTimeout(): void; +} +//# sourceMappingURL=timer.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/lib/timer.d.ts.map b/backend/node_modules/@supabase/realtime-js/dist/module/lib/timer.d.ts.map new file mode 100644 index 0000000..3cee271 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/lib/timer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"timer.d.ts","sourceRoot":"","sources":["../../../src/lib/timer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,OAAO,OAAO,KAAK;IAKf,QAAQ,EAAE,QAAQ;IAClB,SAAS,EAAE,QAAQ;IAL5B,KAAK,EAAE,MAAM,GAAG,SAAS,CAAY;IACrC,KAAK,EAAE,MAAM,CAAI;gBAGR,QAAQ,EAAE,QAAQ,EAClB,SAAS,EAAE,QAAQ;IAM5B,KAAK;IAOL,eAAe;CAWhB"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/lib/timer.js b/backend/node_modules/@supabase/realtime-js/dist/module/lib/timer.js new file mode 100644 index 0000000..fc38667 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/lib/timer.js @@ -0,0 +1,36 @@ +/** + * Creates a timer that accepts a `timerCalc` function to perform calculated timeout retries, such as exponential backoff. + * + * @example + * let reconnectTimer = new Timer(() => this.connect(), function(tries){ + * return [1000, 5000, 10000][tries - 1] || 10000 + * }) + * reconnectTimer.scheduleTimeout() // fires after 1000 + * reconnectTimer.scheduleTimeout() // fires after 5000 + * reconnectTimer.reset() + * reconnectTimer.scheduleTimeout() // fires after 1000 + */ +export default class Timer { + constructor(callback, timerCalc) { + this.callback = callback; + this.timerCalc = timerCalc; + this.timer = undefined; + this.tries = 0; + this.callback = callback; + this.timerCalc = timerCalc; + } + reset() { + this.tries = 0; + clearTimeout(this.timer); + this.timer = undefined; + } + // Cancels any previous scheduleTimeout and schedules callback + scheduleTimeout() { + clearTimeout(this.timer); + this.timer = setTimeout(() => { + this.tries = this.tries + 1; + this.callback(); + }, this.timerCalc(this.tries + 1)); + } +} +//# sourceMappingURL=timer.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/lib/timer.js.map b/backend/node_modules/@supabase/realtime-js/dist/module/lib/timer.js.map new file mode 100644 index 0000000..0b4c7b9 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/lib/timer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"timer.js","sourceRoot":"","sources":["../../../src/lib/timer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,OAAO,OAAO,KAAK;IAIxB,YACS,QAAkB,EAClB,SAAmB;QADnB,aAAQ,GAAR,QAAQ,CAAU;QAClB,cAAS,GAAT,SAAS,CAAU;QAL5B,UAAK,GAAuB,SAAS,CAAA;QACrC,UAAK,GAAW,CAAC,CAAA;QAMf,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;QACxB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAA;IAC5B,CAAC;IAED,KAAK;QACH,IAAI,CAAC,KAAK,GAAG,CAAC,CAAA;QACd,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;QACxB,IAAI,CAAC,KAAK,GAAG,SAAS,CAAA;IACxB,CAAC;IAED,8DAA8D;IAC9D,eAAe;QACb,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;QAExB,IAAI,CAAC,KAAK,GAAQ,UAAU,CAC1B,GAAG,EAAE;YACH,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,GAAG,CAAC,CAAA;YAC3B,IAAI,CAAC,QAAQ,EAAE,CAAA;QACjB,CAAC,EACD,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,KAAK,GAAG,CAAC,CAAC,CAC/B,CAAA;IACH,CAAC;CACF"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/lib/transformers.d.ts b/backend/node_modules/@supabase/realtime-js/dist/module/lib/transformers.d.ts new file mode 100644 index 0000000..d52adaf --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/lib/transformers.d.ts @@ -0,0 +1,109 @@ +/** + * Helpers to convert the change Payload into native JS types. + */ +export declare enum PostgresTypes { + abstime = "abstime", + bool = "bool", + date = "date", + daterange = "daterange", + float4 = "float4", + float8 = "float8", + int2 = "int2", + int4 = "int4", + int4range = "int4range", + int8 = "int8", + int8range = "int8range", + json = "json", + jsonb = "jsonb", + money = "money", + numeric = "numeric", + oid = "oid", + reltime = "reltime", + text = "text", + time = "time", + timestamp = "timestamp", + timestamptz = "timestamptz", + timetz = "timetz", + tsrange = "tsrange", + tstzrange = "tstzrange" +} +type Columns = { + name: string; + type: string; + flags?: string[]; + type_modifier?: number; +}[]; +type BaseValue = null | string | number | boolean; +type RecordValue = BaseValue | BaseValue[]; +type Record = { + [key: string]: RecordValue; +}; +/** + * Takes an array of columns and an object of string values then converts each string value + * to its mapped type. + * + * @param {{name: String, type: String}[]} columns + * @param {Object} record + * @param {Object} options The map of various options that can be applied to the mapper + * @param {Array} options.skipTypes The array of types that should not be converted + * + * @example convertChangeData([{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age:'33'}, {}) + * //=>{ first_name: 'Paul', age: 33 } + */ +export declare const convertChangeData: (columns: Columns, record: Record | null, options?: { + skipTypes?: string[]; +}) => Record; +/** + * Converts the value of an individual column. + * + * @param {String} columnName The column that you want to convert + * @param {{name: String, type: String}[]} columns All of the columns + * @param {Object} record The map of string values + * @param {Array} skipTypes An array of types that should not be converted + * @return {object} Useless information + * + * @example convertColumn('age', [{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age: '33'}, []) + * //=> 33 + * @example convertColumn('age', [{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age: '33'}, ['int4']) + * //=> "33" + */ +export declare const convertColumn: (columnName: string, columns: Columns, record: Record, skipTypes: string[]) => RecordValue; +/** + * If the value of the cell is `null`, returns null. + * Otherwise converts the string value to the correct type. + * @param {String} type A postgres column type + * @param {String} value The cell value + * + * @example convertCell('bool', 't') + * //=> true + * @example convertCell('int8', '10') + * //=> 10 + * @example convertCell('_int4', '{1,2,3,4}') + * //=> [1,2,3,4] + */ +export declare const convertCell: (type: string, value: RecordValue) => RecordValue; +export declare const toBoolean: (value: RecordValue) => RecordValue; +export declare const toNumber: (value: RecordValue) => RecordValue; +export declare const toJson: (value: RecordValue) => RecordValue; +/** + * Converts a Postgres Array into a native JS array + * + * @example toArray('{}', 'int4') + * //=> [] + * @example toArray('{"[2021-01-01,2021-12-31)","(2021-01-01,2021-12-32]"}', 'daterange') + * //=> ['[2021-01-01,2021-12-31)', '(2021-01-01,2021-12-32]'] + * @example toArray([1,2,3,4], 'int4') + * //=> [1,2,3,4] + */ +export declare const toArray: (value: RecordValue, type: string) => RecordValue; +/** + * Fixes timestamp to be ISO-8601. Swaps the space between the date and time for a 'T' + * See https://github.com/supabase/supabase/issues/18 + * + * @example toTimestampString('2019-09-10 00:00:00') + * //=> '2019-09-10T00:00:00' + */ +export declare const toTimestampString: (value: RecordValue) => RecordValue; +export declare const httpEndpointURL: (socketUrl: string) => string; +export {}; +//# sourceMappingURL=transformers.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/lib/transformers.d.ts.map b/backend/node_modules/@supabase/realtime-js/dist/module/lib/transformers.d.ts.map new file mode 100644 index 0000000..0804f76 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/lib/transformers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"transformers.d.ts","sourceRoot":"","sources":["../../../src/lib/transformers.ts"],"names":[],"mappings":"AAAA;;GAEG;AAKH,oBAAY,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KAAG,WA0C9D,CAAA;AAKD,eAAO,MAAM,SAAS,GAAI,OAAO,WAAW,KAAG,WAS9C,CAAA;AACD,eAAO,MAAM,QAAQ,GAAI,OAAO,WAAW,KAAG,WAQ7C,CAAA;AACD,eAAO,MAAM,MAAM,GAAI,OAAO,WAAW,KAAG,WAU3C,CAAA;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,OAAO,GAAI,OAAO,WAAW,EAAE,MAAM,MAAM,KAAG,WA0B1D,CAAA;AAED;;;;;;GAMG;AACH,eAAO,MAAM,iBAAiB,GAAI,OAAO,WAAW,KAAG,WAMtD,CAAA;AAED,eAAO,MAAM,eAAe,GAAI,WAAW,MAAM,KAAG,MAkBnD,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/lib/transformers.js b/backend/node_modules/@supabase/realtime-js/dist/module/lib/transformers.js new file mode 100644 index 0000000..c7e88c8 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/lib/transformers.js @@ -0,0 +1,230 @@ +/** + * Helpers to convert the change Payload into native JS types. + */ +// Adapted from epgsql (src/epgsql_binary.erl), this module licensed under +// 3-clause BSD found here: https://raw.githubusercontent.com/epgsql/epgsql/devel/LICENSE +export var PostgresTypes; +(function (PostgresTypes) { + PostgresTypes["abstime"] = "abstime"; + PostgresTypes["bool"] = "bool"; + PostgresTypes["date"] = "date"; + PostgresTypes["daterange"] = "daterange"; + PostgresTypes["float4"] = "float4"; + PostgresTypes["float8"] = "float8"; + PostgresTypes["int2"] = "int2"; + PostgresTypes["int4"] = "int4"; + PostgresTypes["int4range"] = "int4range"; + PostgresTypes["int8"] = "int8"; + PostgresTypes["int8range"] = "int8range"; + PostgresTypes["json"] = "json"; + PostgresTypes["jsonb"] = "jsonb"; + PostgresTypes["money"] = "money"; + PostgresTypes["numeric"] = "numeric"; + PostgresTypes["oid"] = "oid"; + PostgresTypes["reltime"] = "reltime"; + PostgresTypes["text"] = "text"; + PostgresTypes["time"] = "time"; + PostgresTypes["timestamp"] = "timestamp"; + PostgresTypes["timestamptz"] = "timestamptz"; + PostgresTypes["timetz"] = "timetz"; + PostgresTypes["tsrange"] = "tsrange"; + PostgresTypes["tstzrange"] = "tstzrange"; +})(PostgresTypes || (PostgresTypes = {})); +/** + * Takes an array of columns and an object of string values then converts each string value + * to its mapped type. + * + * @param {{name: String, type: String}[]} columns + * @param {Object} record + * @param {Object} options The map of various options that can be applied to the mapper + * @param {Array} options.skipTypes The array of types that should not be converted + * + * @example convertChangeData([{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age:'33'}, {}) + * //=>{ first_name: 'Paul', age: 33 } + */ +export const convertChangeData = (columns, record, options = {}) => { + var _a; + const skipTypes = (_a = options.skipTypes) !== null && _a !== void 0 ? _a : []; + if (!record) { + return {}; + } + return Object.keys(record).reduce((acc, rec_key) => { + acc[rec_key] = convertColumn(rec_key, columns, record, skipTypes); + return acc; + }, {}); +}; +/** + * Converts the value of an individual column. + * + * @param {String} columnName The column that you want to convert + * @param {{name: String, type: String}[]} columns All of the columns + * @param {Object} record The map of string values + * @param {Array} skipTypes An array of types that should not be converted + * @return {object} Useless information + * + * @example convertColumn('age', [{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age: '33'}, []) + * //=> 33 + * @example convertColumn('age', [{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age: '33'}, ['int4']) + * //=> "33" + */ +export const convertColumn = (columnName, columns, record, skipTypes) => { + const column = columns.find((x) => x.name === columnName); + const colType = column === null || column === void 0 ? void 0 : column.type; + const value = record[columnName]; + if (colType && !skipTypes.includes(colType)) { + return convertCell(colType, value); + } + return noop(value); +}; +/** + * If the value of the cell is `null`, returns null. + * Otherwise converts the string value to the correct type. + * @param {String} type A postgres column type + * @param {String} value The cell value + * + * @example convertCell('bool', 't') + * //=> true + * @example convertCell('int8', '10') + * //=> 10 + * @example convertCell('_int4', '{1,2,3,4}') + * //=> [1,2,3,4] + */ +export const convertCell = (type, value) => { + // if data type is an array + if (type.charAt(0) === '_') { + const dataType = type.slice(1, type.length); + return toArray(value, dataType); + } + // If not null, convert to correct type. + switch (type) { + case PostgresTypes.bool: + return toBoolean(value); + case PostgresTypes.float4: + case PostgresTypes.float8: + case PostgresTypes.int2: + case PostgresTypes.int4: + case PostgresTypes.int8: + case PostgresTypes.numeric: + case PostgresTypes.oid: + return toNumber(value); + case PostgresTypes.json: + case PostgresTypes.jsonb: + return toJson(value); + case PostgresTypes.timestamp: + return toTimestampString(value); // Format to be consistent with PostgREST + case PostgresTypes.abstime: // To allow users to cast it based on Timezone + case PostgresTypes.date: // To allow users to cast it based on Timezone + case PostgresTypes.daterange: + case PostgresTypes.int4range: + case PostgresTypes.int8range: + case PostgresTypes.money: + case PostgresTypes.reltime: // To allow users to cast it based on Timezone + case PostgresTypes.text: + case PostgresTypes.time: // To allow users to cast it based on Timezone + case PostgresTypes.timestamptz: // To allow users to cast it based on Timezone + case PostgresTypes.timetz: // To allow users to cast it based on Timezone + case PostgresTypes.tsrange: + case PostgresTypes.tstzrange: + return noop(value); + default: + // Return the value for remaining types + return noop(value); + } +}; +const noop = (value) => { + return value; +}; +export const toBoolean = (value) => { + switch (value) { + case 't': + return true; + case 'f': + return false; + default: + return value; + } +}; +export const toNumber = (value) => { + if (typeof value === 'string') { + const parsedValue = parseFloat(value); + if (!Number.isNaN(parsedValue)) { + return parsedValue; + } + } + return value; +}; +export const toJson = (value) => { + if (typeof value === 'string') { + try { + return JSON.parse(value); + } + catch (error) { + console.log(`JSON parse error: ${error}`); + return value; + } + } + return value; +}; +/** + * Converts a Postgres Array into a native JS array + * + * @example toArray('{}', 'int4') + * //=> [] + * @example toArray('{"[2021-01-01,2021-12-31)","(2021-01-01,2021-12-32]"}', 'daterange') + * //=> ['[2021-01-01,2021-12-31)', '(2021-01-01,2021-12-32]'] + * @example toArray([1,2,3,4], 'int4') + * //=> [1,2,3,4] + */ +export const toArray = (value, type) => { + if (typeof value !== 'string') { + return value; + } + const lastIdx = value.length - 1; + const closeBrace = value[lastIdx]; + const openBrace = value[0]; + // Confirm value is a Postgres array by checking curly brackets + if (openBrace === '{' && closeBrace === '}') { + let arr; + const valTrim = value.slice(1, lastIdx); + // TODO: find a better solution to separate Postgres array data + try { + arr = JSON.parse('[' + valTrim + ']'); + } + catch (_) { + // WARNING: splitting on comma does not cover all edge cases + arr = valTrim ? valTrim.split(',') : []; + } + return arr.map((val) => convertCell(type, val)); + } + return value; +}; +/** + * Fixes timestamp to be ISO-8601. Swaps the space between the date and time for a 'T' + * See https://github.com/supabase/supabase/issues/18 + * + * @example toTimestampString('2019-09-10 00:00:00') + * //=> '2019-09-10T00:00:00' + */ +export const toTimestampString = (value) => { + if (typeof value === 'string') { + return value.replace(' ', 'T'); + } + return value; +}; +export const httpEndpointURL = (socketUrl) => { + const wsUrl = new URL(socketUrl); + wsUrl.protocol = wsUrl.protocol.replace(/^ws/i, 'http'); + wsUrl.pathname = wsUrl.pathname + .replace(/\/+$/, '') // remove all trailing slashes + .replace(/\/socket\/websocket$/i, '') // remove the socket/websocket path + .replace(/\/socket$/i, '') // remove the socket path + .replace(/\/websocket$/i, ''); // remove the websocket path + if (wsUrl.pathname === '' || wsUrl.pathname === '/') { + wsUrl.pathname = '/api/broadcast'; + } + else { + wsUrl.pathname = wsUrl.pathname + '/api/broadcast'; + } + return wsUrl.href; +}; +//# sourceMappingURL=transformers.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/lib/transformers.js.map b/backend/node_modules/@supabase/realtime-js/dist/module/lib/transformers.js.map new file mode 100644 index 0000000..528abba --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/lib/transformers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"transformers.js","sourceRoot":"","sources":["../../../src/lib/transformers.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,0EAA0E;AAC1E,yFAAyF;AAEzF,MAAM,CAAN,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AAC;QACpD,KAAK,CAAC,QAAQ,GAAG,gBAAgB,CAAA;IACnC,CAAC;SAAM,CAAC;QACN,KAAK,CAAC,QAAQ,GAAG,KAAK,CAAC,QAAQ,GAAG,gBAAgB,CAAA;IACpD,CAAC;IAED,OAAO,KAAK,CAAC,IAAI,CAAA;AACnB,CAAC,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/lib/version.d.ts b/backend/node_modules/@supabase/realtime-js/dist/module/lib/version.d.ts new file mode 100644 index 0000000..da11aac --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/lib/version.d.ts @@ -0,0 +1,2 @@ +export declare const version = "2.87.1"; +//# sourceMappingURL=version.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/lib/version.d.ts.map b/backend/node_modules/@supabase/realtime-js/dist/module/lib/version.d.ts.map new file mode 100644 index 0000000..a4c2b72 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/lib/version.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,OAAO,WAAW,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/lib/version.js b/backend/node_modules/@supabase/realtime-js/dist/module/lib/version.js new file mode 100644 index 0000000..8a1c0bd --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/lib/version.js @@ -0,0 +1,8 @@ +// Generated automatically during releases by scripts/update-version-files.ts +// This file provides runtime access to the package version for: +// - HTTP request headers (e.g., X-Client-Info header for API requests) +// - Debugging and support (identifying which version is running) +// - Telemetry and logging (version reporting in errors/analytics) +// - Ensuring build artifacts match the published package version +export const version = '2.87.1'; +//# sourceMappingURL=version.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/lib/version.js.map b/backend/node_modules/@supabase/realtime-js/dist/module/lib/version.js.map new file mode 100644 index 0000000..b571c4f --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/lib/version.js.map @@ -0,0 +1 @@ +{"version":3,"file":"version.js","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,gEAAgE;AAChE,uEAAuE;AACvE,iEAAiE;AACjE,kEAAkE;AAClE,iEAAiE;AACjE,MAAM,CAAC,MAAM,OAAO,GAAG,QAAQ,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/lib/websocket-factory.d.ts b/backend/node_modules/@supabase/realtime-js/dist/module/lib/websocket-factory.d.ts new file mode 100644 index 0000000..3a19990 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/lib/websocket-factory.d.ts @@ -0,0 +1,81 @@ +export interface WebSocketLike { + readonly CONNECTING: number; + readonly OPEN: number; + readonly CLOSING: number; + readonly CLOSED: number; + readonly readyState: number; + readonly url: string; + readonly protocol: string; + /** + * Closes the socket, optionally providing a close code and reason. + */ + close(code?: number, reason?: string): void; + /** + * Sends data through the socket using the underlying implementation. + */ + send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void; + onopen: ((this: any, ev: Event) => any) | null; + onmessage: ((this: any, ev: MessageEvent) => any) | null; + onclose: ((this: any, ev: CloseEvent) => any) | null; + onerror: ((this: any, ev: Event) => any) | null; + /** + * Registers an event listener on the socket (compatible with browser WebSocket API). + */ + addEventListener(type: string, listener: EventListener): void; + /** + * Removes a previously registered event listener. + */ + removeEventListener(type: string, listener: EventListener): void; + binaryType?: string; + bufferedAmount?: number; + extensions?: string; + dispatchEvent?: (event: Event) => boolean; +} +export interface WebSocketEnvironment { + type: 'native' | 'ws' | 'cloudflare' | 'unsupported'; + constructor?: any; + error?: string; + workaround?: string; +} +/** + * Utilities for creating WebSocket instances across runtimes. + */ +export declare class WebSocketFactory { + /** + * Static-only utility – prevent instantiation. + */ + private constructor(); + private static detectEnvironment; + /** + * Returns the best available WebSocket constructor for the current runtime. + * + * @example + * ```ts + * const WS = WebSocketFactory.getWebSocketConstructor() + * const socket = new WS('wss://realtime.supabase.co/socket') + * ``` + */ + static getWebSocketConstructor(): typeof WebSocket; + /** + * Creates a WebSocket using the detected constructor. + * + * @example + * ```ts + * const socket = WebSocketFactory.createWebSocket('wss://realtime.supabase.co/socket') + * ``` + */ + static createWebSocket(url: string | URL, protocols?: string | string[]): WebSocketLike; + /** + * Detects whether the runtime can establish WebSocket connections. + * + * @example + * ```ts + * if (!WebSocketFactory.isWebSocketSupported()) { + * console.warn('Falling back to long polling') + * } + * ``` + */ + static isWebSocketSupported(): boolean; +} +export default WebSocketFactory; +//# sourceMappingURL=websocket-factory.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/lib/websocket-factory.d.ts.map b/backend/node_modules/@supabase/realtime-js/dist/module/lib/websocket-factory.d.ts.map new file mode 100644 index 0000000..b045f0b --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/lib/websocket-factory.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"websocket-factory.d.ts","sourceRoot":"","sources":["../../../src/lib/websocket-factory.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAA;IAC3B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;IACxB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAA;IAC3B,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAA;IACpB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAA;IAEzB;;OAEG;IACH,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IAC3C;;OAEG;IACH,IAAI,CAAC,IAAI,EAAE,MAAM,GAA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G;WACW,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,aAAa;IAK9F;;;;;;;;;OASG;WACW,oBAAoB,IAAI,OAAO;CAQ9C;AAED,eAAe,gBAAgB,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/lib/websocket-factory.js b/backend/node_modules/@supabase/realtime-js/dist/module/lib/websocket-factory.js new file mode 100644 index 0000000..e5dcbf2 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/lib/websocket-factory.js @@ -0,0 +1,126 @@ +/** + * Utilities for creating WebSocket instances across runtimes. + */ +export class WebSocketFactory { + /** + * Static-only utility – prevent instantiation. + */ + constructor() { } + static detectEnvironment() { + var _a; + if (typeof WebSocket !== 'undefined') { + return { type: 'native', constructor: WebSocket }; + } + if (typeof globalThis !== 'undefined' && typeof globalThis.WebSocket !== 'undefined') { + return { type: 'native', constructor: globalThis.WebSocket }; + } + if (typeof global !== 'undefined' && typeof global.WebSocket !== 'undefined') { + return { type: 'native', constructor: global.WebSocket }; + } + if (typeof globalThis !== 'undefined' && + typeof globalThis.WebSocketPair !== 'undefined' && + typeof globalThis.WebSocket === 'undefined') { + return { + type: 'cloudflare', + error: 'Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.', + workaround: 'Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime.', + }; + } + if ((typeof globalThis !== 'undefined' && globalThis.EdgeRuntime) || + (typeof navigator !== 'undefined' && ((_a = navigator.userAgent) === null || _a === void 0 ? void 0 : _a.includes('Vercel-Edge')))) { + return { + type: 'unsupported', + error: 'Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.', + workaround: 'Use serverless functions or a different deployment target for WebSocket functionality.', + }; + } + if (typeof process !== 'undefined') { + // Use dynamic property access to avoid Next.js Edge Runtime static analysis warnings + const processVersions = process['versions']; + if (processVersions && processVersions['node']) { + // Remove 'v' prefix if present and parse the major version + const versionString = processVersions['node']; + const nodeVersion = parseInt(versionString.replace(/^v/, '').split('.')[0]); + // Node.js 22+ should have native WebSocket + if (nodeVersion >= 22) { + // Check if native WebSocket is available (should be in Node.js 22+) + if (typeof globalThis.WebSocket !== 'undefined') { + return { type: 'native', constructor: globalThis.WebSocket }; + } + // If not available, user needs to provide it + return { + type: 'unsupported', + error: `Node.js ${nodeVersion} detected but native WebSocket not found.`, + workaround: 'Provide a WebSocket implementation via the transport option.', + }; + } + // Node.js < 22 doesn't have native WebSocket + return { + type: 'unsupported', + error: `Node.js ${nodeVersion} detected without native WebSocket support.`, + workaround: 'For Node.js < 22, install "ws" package and provide it via the transport option:\n' + + 'import ws from "ws"\n' + + 'new RealtimeClient(url, { transport: ws })', + }; + } + } + return { + type: 'unsupported', + error: 'Unknown JavaScript runtime without WebSocket support.', + workaround: "Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation.", + }; + } + /** + * Returns the best available WebSocket constructor for the current runtime. + * + * @example + * ```ts + * const WS = WebSocketFactory.getWebSocketConstructor() + * const socket = new WS('wss://realtime.supabase.co/socket') + * ``` + */ + static getWebSocketConstructor() { + const env = this.detectEnvironment(); + if (env.constructor) { + return env.constructor; + } + let errorMessage = env.error || 'WebSocket not supported in this environment.'; + if (env.workaround) { + errorMessage += `\n\nSuggested solution: ${env.workaround}`; + } + throw new Error(errorMessage); + } + /** + * Creates a WebSocket using the detected constructor. + * + * @example + * ```ts + * const socket = WebSocketFactory.createWebSocket('wss://realtime.supabase.co/socket') + * ``` + */ + static createWebSocket(url, protocols) { + const WS = this.getWebSocketConstructor(); + return new WS(url, protocols); + } + /** + * Detects whether the runtime can establish WebSocket connections. + * + * @example + * ```ts + * if (!WebSocketFactory.isWebSocketSupported()) { + * console.warn('Falling back to long polling') + * } + * ``` + */ + static isWebSocketSupported() { + try { + const env = this.detectEnvironment(); + return env.type === 'native' || env.type === 'ws'; + } + catch (_a) { + return false; + } + } +} +export default WebSocketFactory; +//# sourceMappingURL=websocket-factory.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/dist/module/lib/websocket-factory.js.map b/backend/node_modules/@supabase/realtime-js/dist/module/lib/websocket-factory.js.map new file mode 100644 index 0000000..b712e79 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/dist/module/lib/websocket-factory.js.map @@ -0,0 +1 @@ +{"version":3,"file":"websocket-factory.js","sourceRoot":"","sources":["../../../src/lib/websocket-factory.ts"],"names":[],"mappings":"AA8CA;;GAEG;AACH,MAAM,OAAO,gBAAgB;IAC3B;;OAEG;IACH,gBAAuB,CAAC;IAChB,MAAM,CAAC,iBAAiB;;QAC9B,IAAI,OAAO,SAAS,KAAK,WAAW,EAAE,CAAC;YACrC,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,SAAS,EAAE,CAAA;QACnD,CAAC;QAED,IAAI,OAAO,UAAU,KAAK,WAAW,IAAI,OAAQ,UAAkB,CAAC,SAAS,KAAK,WAAW,EAAE,CAAC;YAC9F,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAG,UAAkB,CAAC,SAAS,EAAE,CAAA;QACvE,CAAC;QAED,IAAI,OAAO,MAAM,KAAK,WAAW,IAAI,OAAQ,MAAc,CAAC,SAAS,KAAK,WAAW,EAAE,CAAC;YACtF,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAG,MAAc,CAAC,SAAS,EAAE,CAAA;QACnE,CAAC;QAED,IACE,OAAO,UAAU,KAAK,WAAW;YACjC,OAAQ,UAAkB,CAAC,aAAa,KAAK,WAAW;YACxD,OAAO,UAAU,CAAC,SAAS,KAAK,WAAW,EAC3C,CAAC;YACD,OAAO;gBACL,IAAI,EAAE,YAAY;gBAClB,KAAK,EACH,yFAAyF;gBAC3F,UAAU,EACR,4GAA4G;aAC/G,CAAA;QACH,CAAC;QAED,IACE,CAAC,OAAO,UAAU,KA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AC;QACH,CAAC;QAED,OAAO;YACL,IAAI,EAAE,aAAa;YACnB,KAAK,EAAE,uDAAuD;YAC9D,UAAU,EACR,yHAAyH;SAC5H,CAAA;IACH,CAAC;IAED;;;;;;;;OAQG;IACI,MAAM,CAAC,uBAAuB;QACnC,MAAM,GAAG,GAAG,IAAI,CAAC,iBAAiB,EAAE,CAAA;QACpC,IAAI,GAAG,CAAC,WAAW,EAAE,CAAC;YACpB,OAAO,GAAG,CAAC,WAAW,CAAA;QACxB,CAAC;QACD,IAAI,YAAY,GAAG,GAAG,CAAC,KAAK,IAAI,8CAA8C,CAAA;QAC9E,IAAI,GAAG,CAAC,UAAU,EAAE,CAAC;YACnB,YAAY,IAAI,2BAA2B,GAAG,CAAC,UAAU,EAAE,CAAA;QAC7D,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,YAAY,CAAC,CAAA;IAC/B,CAAC;IAED;;;;;;;OAOG;IACI,MAAM,CAAC,eAAe,CAAC,GAAiB,EAAE,SAA6B;QAC5E,MAAM,EAAE,GAAG,IAAI,CAAC,uBAAuB,EAAE,CAAA;QACzC,OAAO,IAAI,EAAE,CAAC,GAAG,EAAE,SAAS,CAAC,CAAA;IAC/B,CAAC;IAED;;;;;;;;;OASG;IACI,MAAM,CAAC,oBAAoB;QAChC,IAAI,CAAC;YACH,MAAM,GAAG,GAAG,IAAI,CAAC,iBAAiB,EAAE,CAAA;YACpC,OAAO,GAAG,CAAC,IAAI,KAAK,QAAQ,IAAI,GAAG,CAAC,IAAI,KAAK,IAAI,CAAA;QACnD,CAAC;QAAC,WAAM,CAAC;YACP,OAAO,KAAK,CAAA;QACd,CAAC;IACH,CAAC;CACF;AAED,eAAe,gBAAgB,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/realtime-js/package.json b/backend/node_modules/@supabase/realtime-js/package.json new file mode 100644 index 0000000..7ec43f0 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/package.json @@ -0,0 +1,61 @@ +{ + "name": "@supabase/realtime-js", + "version": "2.87.1", + "description": "Listen to realtime updates to your PostgreSQL database", + "keywords": [ + "realtime", + "phoenix", + "elixir", + "javascript", + "typescript", + "firebase", + "supabase" + ], + "homepage": "https://github.com/supabase/supabase-js/tree/master/packages/core/realtime-js", + "bugs": "https://github.com/supabase/supabase-js/issues", + "files": [ + "dist", + "src" + ], + "main": "dist/main/index.js", + "module": "dist/module/index.js", + "types": "dist/module/index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/supabase/supabase-js.git", + "directory": "packages/core/realtime-js" + }, + "author": "Supabase", + "license": "MIT", + "scripts": { + "build": "npm run build:main && npm run build:module", + "build:main": "tsc -p tsconfig.json", + "build:module": "tsc -p tsconfig.module.json", + "test": "vitest run", + "test:watch": "vitest", + "test:coverage": "vitest run --coverage.enabled true --coverage.reporter=text", + "docs": "typedoc src/index.ts --out docs/v2", + "docs:json": "typedoc --json docs/v2/spec.json --excludeExternals src/index.ts", + "check-exports": "attw --pack .", + "test:ci": "vitest run --coverage" + }, + "dependencies": { + "@types/phoenix": "^1.6.6", + "@types/ws": "^8.18.1", + "tslib": "2.8.1", + "ws": "^8.18.2" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.16.4", + "@vitest/coverage-v8": "^3.1.4", + "esm": "^3.2.25", + "jsdom": "^16.7.0", + "jsdom-global": "3.0.0", + "mock-socket": "^9.3.1", + "nyc": "^15.1.0", + "web-worker": "1.2.0" + }, + "engines": { + "node": ">=20.0.0" + } +} diff --git a/backend/node_modules/@supabase/realtime-js/src/RealtimeChannel.ts b/backend/node_modules/@supabase/realtime-js/src/RealtimeChannel.ts new file mode 100644 index 0000000..aa73036 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/src/RealtimeChannel.ts @@ -0,0 +1,1031 @@ +import { CHANNEL_EVENTS, CHANNEL_STATES, MAX_PUSH_BUFFER_SIZE } from './lib/constants' +import Push from './lib/push' +import type RealtimeClient from './RealtimeClient' +import Timer from './lib/timer' +import RealtimePresence, { REALTIME_PRESENCE_LISTEN_EVENTS } from './RealtimePresence' +import type { + RealtimePresenceJoinPayload, + RealtimePresenceLeavePayload, + RealtimePresenceState, +} from './RealtimePresence' +import * as Transformers from './lib/transformers' +import { httpEndpointURL } from './lib/transformers' + +type ReplayOption = { + since: number + limit?: number +} + +export type RealtimeChannelOptions = { + config: { + /** + * self option enables client to receive message it broadcast + * ack option instructs server to acknowledge that broadcast message was received + * replay option instructs server to replay broadcast messages + */ + broadcast?: { self?: boolean; ack?: boolean; replay?: ReplayOption } + /** + * key option is used to track presence payload across clients + */ + presence?: { key?: string; enabled?: boolean } + /** + * defines if the channel is private or not and if RLS policies will be used to check data + */ + private?: boolean + } +} + +type RealtimeChangesPayloadBase = { + schema: string + table: string +} + +type RealtimeBroadcastChangesPayloadBase = RealtimeChangesPayloadBase & { + id: string +} + +export type RealtimeBroadcastInsertPayload = + RealtimeBroadcastChangesPayloadBase & { + operation: `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.INSERT}` + record: T + old_record: null + } + +export type RealtimeBroadcastUpdatePayload = + RealtimeBroadcastChangesPayloadBase & { + operation: `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.UPDATE}` + record: T + old_record: T + } + +export type RealtimeBroadcastDeletePayload = + RealtimeBroadcastChangesPayloadBase & { + operation: `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE}` + record: null + old_record: T + } + +export type RealtimeBroadcastPayload = + | RealtimeBroadcastInsertPayload + | RealtimeBroadcastUpdatePayload + | RealtimeBroadcastDeletePayload + +type RealtimePostgresChangesPayloadBase = { + schema: string + table: string + commit_timestamp: string + errors: string[] +} + +export type RealtimePostgresInsertPayload = + RealtimePostgresChangesPayloadBase & { + eventType: `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.INSERT}` + new: T + old: {} + } + +export type RealtimePostgresUpdatePayload = + RealtimePostgresChangesPayloadBase & { + eventType: `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.UPDATE}` + new: T + old: Partial + } + +export type RealtimePostgresDeletePayload = + RealtimePostgresChangesPayloadBase & { + eventType: `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE}` + new: {} + old: Partial + } + +export type RealtimePostgresChangesPayload = + | RealtimePostgresInsertPayload + | RealtimePostgresUpdatePayload + | RealtimePostgresDeletePayload + +export type RealtimePostgresChangesFilter = { + /** + * The type of database change to listen to. + */ + event: T + /** + * The database schema to listen to. + */ + schema: string + /** + * The database table to listen to. + */ + table?: string + /** + * Receive database changes when filter is matched. + */ + filter?: string +} + +export type RealtimeChannelSendResponse = 'ok' | 'timed out' | 'error' + +export enum REALTIME_POSTGRES_CHANGES_LISTEN_EVENT { + ALL = '*', + INSERT = 'INSERT', + UPDATE = 'UPDATE', + DELETE = 'DELETE', +} + +export enum REALTIME_LISTEN_TYPES { + BROADCAST = 'broadcast', + PRESENCE = 'presence', + POSTGRES_CHANGES = 'postgres_changes', + SYSTEM = 'system', +} + +export enum REALTIME_SUBSCRIBE_STATES { + SUBSCRIBED = 'SUBSCRIBED', + TIMED_OUT = 'TIMED_OUT', + CLOSED = 'CLOSED', + CHANNEL_ERROR = 'CHANNEL_ERROR', +} + +export const REALTIME_CHANNEL_STATES = CHANNEL_STATES + +interface PostgresChangesFilters { + postgres_changes: { + id: string + event: string + schema?: string + table?: string + filter?: string + }[] +} +/** A channel is the basic building block of Realtime + * and narrows the scope of data flow to subscribed clients. + * You can think of a channel as a chatroom where participants are able to see who's online + * and send and receive messages. + */ +export default class RealtimeChannel { + bindings: { + [key: string]: { + type: string + filter: { [key: string]: any } + callback: Function + id?: string + }[] + } = {} + timeout: number + state: CHANNEL_STATES = CHANNEL_STATES.closed + joinedOnce = false + joinPush: Push + rejoinTimer: Timer + pushBuffer: Push[] = [] + presence: RealtimePresence + broadcastEndpointURL: string + subTopic: string + private: boolean + + /** + * Creates a channel that can broadcast messages, sync presence, and listen to Postgres changes. + * + * The topic determines which realtime stream you are subscribing to. Config options let you + * enable acknowledgement for broadcasts, presence tracking, or private channels. + * + * @example + * ```ts + * import RealtimeClient from '@supabase/realtime-js' + * + * const client = new RealtimeClient('https://xyzcompany.supabase.co/realtime/v1', { + * params: { apikey: 'public-anon-key' }, + * }) + * const channel = new RealtimeChannel('realtime:public:messages', { config: {} }, client) + * ``` + */ + constructor( + /** Topic name can be any string. */ + public topic: string, + public params: RealtimeChannelOptions = { config: {} }, + public socket: RealtimeClient + ) { + this.subTopic = topic.replace(/^realtime:/i, '') + this.params.config = { + ...{ + broadcast: { ack: false, self: false }, + presence: { key: '', enabled: false }, + private: false, + }, + ...params.config, + } + this.timeout = this.socket.timeout + this.joinPush = new Push(this, CHANNEL_EVENTS.join, this.params, this.timeout) + this.rejoinTimer = new Timer(() => this._rejoinUntilConnected(), this.socket.reconnectAfterMs) + this.joinPush.receive('ok', () => { + this.state = CHANNEL_STATES.joined + this.rejoinTimer.reset() + this.pushBuffer.forEach((pushEvent: Push) => pushEvent.send()) + this.pushBuffer = [] + }) + this._onClose(() => { + this.rejoinTimer.reset() + this.socket.log('channel', `close ${this.topic} ${this._joinRef()}`) + this.state = CHANNEL_STATES.closed + this.socket._remove(this) + }) + this._onError((reason: string) => { + if (this._isLeaving() || this._isClosed()) { + return + } + this.socket.log('channel', `error ${this.topic}`, reason) + this.state = CHANNEL_STATES.errored + this.rejoinTimer.scheduleTimeout() + }) + this.joinPush.receive('timeout', () => { + if (!this._isJoining()) { + return + } + this.socket.log('channel', `timeout ${this.topic}`, this.joinPush.timeout) + this.state = CHANNEL_STATES.errored + this.rejoinTimer.scheduleTimeout() + }) + + this.joinPush.receive('error', (reason: any) => { + if (this._isLeaving() || this._isClosed()) { + return + } + this.socket.log('channel', `error ${this.topic}`, reason) + this.state = CHANNEL_STATES.errored + this.rejoinTimer.scheduleTimeout() + }) + this._on(CHANNEL_EVENTS.reply, {}, (payload: any, ref: string) => { + this._trigger(this._replyEventName(ref), payload) + }) + + this.presence = new RealtimePresence(this) + + this.broadcastEndpointURL = httpEndpointURL(this.socket.endPoint) + this.private = this.params.config.private || false + + if (!this.private && this.params.config?.broadcast?.replay) { + throw `tried to use replay on public channel '${this.topic}'. It must be a private channel.` + } + } + + /** Subscribe registers your client with the server */ + subscribe( + callback?: (status: REALTIME_SUBSCRIBE_STATES, err?: Error) => void, + timeout = this.timeout + ): RealtimeChannel { + if (!this.socket.isConnected()) { + this.socket.connect() + } + if (this.state == CHANNEL_STATES.closed) { + const { + config: { broadcast, presence, private: isPrivate }, + } = this.params + + const postgres_changes = this.bindings.postgres_changes?.map((r) => r.filter) ?? [] + + const presence_enabled = + (!!this.bindings[REALTIME_LISTEN_TYPES.PRESENCE] && + this.bindings[REALTIME_LISTEN_TYPES.PRESENCE].length > 0) || + this.params.config.presence?.enabled === true + const accessTokenPayload: { access_token?: string } = {} + const config = { + broadcast, + presence: { ...presence, enabled: presence_enabled }, + postgres_changes, + private: isPrivate, + } + + if (this.socket.accessTokenValue) { + accessTokenPayload.access_token = this.socket.accessTokenValue + } + + this._onError((e: Error) => callback?.(REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR, e)) + + this._onClose(() => callback?.(REALTIME_SUBSCRIBE_STATES.CLOSED)) + + this.updateJoinPayload({ ...{ config }, ...accessTokenPayload }) + + this.joinedOnce = true + this._rejoin(timeout) + + this.joinPush + .receive('ok', async ({ postgres_changes }: PostgresChangesFilters) => { + // Only refresh auth if using callback-based tokens + if (!this.socket._isManualToken()) { + this.socket.setAuth() + } + if (postgres_changes === undefined) { + callback?.(REALTIME_SUBSCRIBE_STATES.SUBSCRIBED) + return + } else { + const clientPostgresBindings = this.bindings.postgres_changes + const bindingsLen = clientPostgresBindings?.length ?? 0 + const newPostgresBindings = [] + + for (let i = 0; i < bindingsLen; i++) { + const clientPostgresBinding = clientPostgresBindings[i] + const { + filter: { event, schema, table, filter }, + } = clientPostgresBinding + const serverPostgresFilter = postgres_changes && postgres_changes[i] + + if ( + serverPostgresFilter && + serverPostgresFilter.event === event && + RealtimeChannel.isFilterValueEqual(serverPostgresFilter.schema, schema) && + RealtimeChannel.isFilterValueEqual(serverPostgresFilter.table, table) && + RealtimeChannel.isFilterValueEqual(serverPostgresFilter.filter, filter) + ) { + newPostgresBindings.push({ + ...clientPostgresBinding, + id: serverPostgresFilter.id, + }) + } else { + this.unsubscribe() + this.state = CHANNEL_STATES.errored + + callback?.( + REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR, + new Error('mismatch between server and client bindings for postgres changes') + ) + return + } + } + + this.bindings.postgres_changes = newPostgresBindings + + callback && callback(REALTIME_SUBSCRIBE_STATES.SUBSCRIBED) + return + } + }) + .receive('error', (error: { [key: string]: any }) => { + this.state = CHANNEL_STATES.errored + callback?.( + REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR, + new Error(JSON.stringify(Object.values(error).join(', ') || 'error')) + ) + return + }) + .receive('timeout', () => { + callback?.(REALTIME_SUBSCRIBE_STATES.TIMED_OUT) + return + }) + } + return this + } + + /** + * Returns the current presence state for this channel. + * + * The shape is a map keyed by presence key (for example a user id) where each entry contains the + * tracked metadata for that user. + */ + presenceState(): RealtimePresenceState { + return this.presence.state as RealtimePresenceState + } + + /** + * Sends the supplied payload to the presence tracker so other subscribers can see that this + * client is online. Use `untrack` to stop broadcasting presence for the same key. + */ + async track( + payload: { [key: string]: any }, + opts: { [key: string]: any } = {} + ): Promise { + return await this.send( + { + type: 'presence', + event: 'track', + payload, + }, + opts.timeout || this.timeout + ) + } + + /** + * Removes the current presence state for this client. + */ + async untrack(opts: { [key: string]: any } = {}): Promise { + return await this.send( + { + type: 'presence', + event: 'untrack', + }, + opts + ) + } + + /** + * Creates an event handler that listens to changes. + */ + on( + type: `${REALTIME_LISTEN_TYPES.PRESENCE}`, + filter: { event: `${REALTIME_PRESENCE_LISTEN_EVENTS.SYNC}` }, + callback: () => void + ): RealtimeChannel + on( + type: `${REALTIME_LISTEN_TYPES.PRESENCE}`, + filter: { event: `${REALTIME_PRESENCE_LISTEN_EVENTS.JOIN}` }, + callback: (payload: RealtimePresenceJoinPayload) => void + ): RealtimeChannel + on( + type: `${REALTIME_LISTEN_TYPES.PRESENCE}`, + filter: { event: `${REALTIME_PRESENCE_LISTEN_EVENTS.LEAVE}` }, + callback: (payload: RealtimePresenceLeavePayload) => void + ): RealtimeChannel + on( + type: `${REALTIME_LISTEN_TYPES.POSTGRES_CHANGES}`, + filter: RealtimePostgresChangesFilter<`${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.ALL}`>, + callback: (payload: RealtimePostgresChangesPayload) => void + ): RealtimeChannel + on( + type: `${REALTIME_LISTEN_TYPES.POSTGRES_CHANGES}`, + filter: RealtimePostgresChangesFilter<`${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.INSERT}`>, + callback: (payload: RealtimePostgresInsertPayload) => void + ): RealtimeChannel + on( + type: `${REALTIME_LISTEN_TYPES.POSTGRES_CHANGES}`, + filter: RealtimePostgresChangesFilter<`${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.UPDATE}`>, + callback: (payload: RealtimePostgresUpdatePayload) => void + ): RealtimeChannel + on( + type: `${REALTIME_LISTEN_TYPES.POSTGRES_CHANGES}`, + filter: RealtimePostgresChangesFilter<`${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE}`>, + callback: (payload: RealtimePostgresDeletePayload) => void + ): RealtimeChannel + /** + * The following is placed here to display on supabase.com/docs/reference/javascript/subscribe. + * @param type One of "broadcast", "presence", or "postgres_changes". + * @param filter Custom object specific to the Realtime feature detailing which payloads to receive. + * @param callback Function to be invoked when event handler is triggered. + */ + on( + type: `${REALTIME_LISTEN_TYPES.BROADCAST}`, + filter: { event: string }, + callback: (payload: { + type: `${REALTIME_LISTEN_TYPES.BROADCAST}` + event: string + meta?: { + replayed?: boolean + id: string + } + [key: string]: any + }) => void + ): RealtimeChannel + on( + type: `${REALTIME_LISTEN_TYPES.BROADCAST}`, + filter: { event: string }, + callback: (payload: { + type: `${REALTIME_LISTEN_TYPES.BROADCAST}` + event: string + meta?: { + replayed?: boolean + id: string + } + payload: T + }) => void + ): RealtimeChannel + on>( + type: `${REALTIME_LISTEN_TYPES.BROADCAST}`, + filter: { event: REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.ALL }, + callback: (payload: { + type: `${REALTIME_LISTEN_TYPES.BROADCAST}` + event: REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.ALL + payload: RealtimeBroadcastPayload + }) => void + ): RealtimeChannel + on( + type: `${REALTIME_LISTEN_TYPES.BROADCAST}`, + filter: { event: REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.INSERT }, + callback: (payload: { + type: `${REALTIME_LISTEN_TYPES.BROADCAST}` + event: REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.INSERT + payload: RealtimeBroadcastInsertPayload + }) => void + ): RealtimeChannel + on( + type: `${REALTIME_LISTEN_TYPES.BROADCAST}`, + filter: { event: REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.UPDATE }, + callback: (payload: { + type: `${REALTIME_LISTEN_TYPES.BROADCAST}` + event: REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.UPDATE + payload: RealtimeBroadcastUpdatePayload + }) => void + ): RealtimeChannel + on( + type: `${REALTIME_LISTEN_TYPES.BROADCAST}`, + filter: { event: REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE }, + callback: (payload: { + type: `${REALTIME_LISTEN_TYPES.BROADCAST}` + event: REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE + payload: RealtimeBroadcastDeletePayload + }) => void + ): RealtimeChannel + on( + type: `${REALTIME_LISTEN_TYPES.SYSTEM}`, + filter: {}, + callback: (payload: any) => void + ): RealtimeChannel + on( + type: `${REALTIME_LISTEN_TYPES}`, + filter: { event: string; [key: string]: string }, + callback: (payload: any) => void + ): RealtimeChannel { + if (this.state === CHANNEL_STATES.joined && type === REALTIME_LISTEN_TYPES.PRESENCE) { + this.socket.log( + 'channel', + `resubscribe to ${this.topic} due to change in presence callbacks on joined channel` + ) + this.unsubscribe().then(async () => await this.subscribe()) + } + return this._on(type, filter, callback) + } + /** + * Sends a broadcast message explicitly via REST API. + * + * This method always uses the REST API endpoint regardless of WebSocket connection state. + * Useful when you want to guarantee REST delivery or when gradually migrating from implicit REST fallback. + * + * @param event The name of the broadcast event + * @param payload Payload to be sent (required) + * @param opts Options including timeout + * @returns Promise resolving to object with success status, and error details if failed + */ + async httpSend( + event: string, + payload: any, + opts: { timeout?: number } = {} + ): Promise<{ success: true } | { success: false; status: number; error: string }> { + const authorization = this.socket.accessTokenValue + ? `Bearer ${this.socket.accessTokenValue}` + : '' + + if (payload === undefined || payload === null) { + return Promise.reject('Payload is required for httpSend()') + } + + const options = { + method: 'POST', + headers: { + Authorization: authorization, + apikey: this.socket.apiKey ? this.socket.apiKey : '', + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + messages: [ + { + topic: this.subTopic, + event, + payload: payload, + private: this.private, + }, + ], + }), + } + + const response = await this._fetchWithTimeout( + this.broadcastEndpointURL, + options, + opts.timeout ?? this.timeout + ) + + if (response.status === 202) { + return { success: true } + } + + let errorMessage = response.statusText + try { + const errorBody = await response.json() + errorMessage = errorBody.error || errorBody.message || errorMessage + } catch {} + + return Promise.reject(new Error(errorMessage)) + } + + /** + * Sends a message into the channel. + * + * @param args Arguments to send to channel + * @param args.type The type of event to send + * @param args.event The name of the event being sent + * @param args.payload Payload to be sent + * @param opts Options to be used during the send process + */ + async send( + args: { + type: 'broadcast' | 'presence' | 'postgres_changes' + event: string + payload?: any + [key: string]: any + }, + opts: { [key: string]: any } = {} + ): Promise { + if (!this._canPush() && args.type === 'broadcast') { + console.warn( + 'Realtime send() is automatically falling back to REST API. ' + + 'This behavior will be deprecated in the future. ' + + 'Please use httpSend() explicitly for REST delivery.' + ) + + const { event, payload: endpoint_payload } = args + const authorization = this.socket.accessTokenValue + ? `Bearer ${this.socket.accessTokenValue}` + : '' + const options = { + method: 'POST', + headers: { + Authorization: authorization, + apikey: this.socket.apiKey ? this.socket.apiKey : '', + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + messages: [ + { + topic: this.subTopic, + event, + payload: endpoint_payload, + private: this.private, + }, + ], + }), + } + + try { + const response = await this._fetchWithTimeout( + this.broadcastEndpointURL, + options, + opts.timeout ?? this.timeout + ) + + await response.body?.cancel() + return response.ok ? 'ok' : 'error' + } catch (error: any) { + if (error.name === 'AbortError') { + return 'timed out' + } else { + return 'error' + } + } + } else { + return new Promise((resolve) => { + const push = this._push(args.type, args, opts.timeout || this.timeout) + + if (args.type === 'broadcast' && !this.params?.config?.broadcast?.ack) { + resolve('ok') + } + + push.receive('ok', () => resolve('ok')) + push.receive('error', () => resolve('error')) + push.receive('timeout', () => resolve('timed out')) + }) + } + } + + /** + * Updates the payload that will be sent the next time the channel joins (reconnects). + * Useful for rotating access tokens or updating config without re-creating the channel. + */ + updateJoinPayload(payload: { [key: string]: any }): void { + this.joinPush.updatePayload(payload) + } + + /** + * Leaves the channel. + * + * Unsubscribes from server events, and instructs channel to terminate on server. + * Triggers onClose() hooks. + * + * To receive leave acknowledgements, use the a `receive` hook to bind to the server ack, ie: + * channel.unsubscribe().receive("ok", () => alert("left!") ) + */ + unsubscribe(timeout = this.timeout): Promise<'ok' | 'timed out' | 'error'> { + this.state = CHANNEL_STATES.leaving + const onClose = () => { + this.socket.log('channel', `leave ${this.topic}`) + this._trigger(CHANNEL_EVENTS.close, 'leave', this._joinRef()) + } + + this.joinPush.destroy() + + let leavePush: Push | null = null + + return new Promise((resolve) => { + leavePush = new Push(this, CHANNEL_EVENTS.leave, {}, timeout) + leavePush + .receive('ok', () => { + onClose() + resolve('ok') + }) + .receive('timeout', () => { + onClose() + resolve('timed out') + }) + .receive('error', () => { + resolve('error') + }) + + leavePush.send() + if (!this._canPush()) { + leavePush.trigger('ok', {}) + } + }).finally(() => { + leavePush?.destroy() + }) + } + /** + * Teardown the channel. + * + * Destroys and stops related timers. + */ + teardown() { + this.pushBuffer.forEach((push: Push) => push.destroy()) + this.pushBuffer = [] + this.rejoinTimer.reset() + this.joinPush.destroy() + this.state = CHANNEL_STATES.closed + this.bindings = {} + } + + /** @internal */ + + async _fetchWithTimeout(url: string, options: { [key: string]: any }, timeout: number) { + const controller = new AbortController() + const id = setTimeout(() => controller.abort(), timeout) + + const response = await this.socket.fetch(url, { + ...options, + signal: controller.signal, + }) + + clearTimeout(id) + + return response + } + + /** @internal */ + _push(event: string, payload: { [key: string]: any }, timeout = this.timeout) { + if (!this.joinedOnce) { + throw `tried to push '${event}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events` + } + let pushEvent = new Push(this, event, payload, timeout) + if (this._canPush()) { + pushEvent.send() + } else { + this._addToPushBuffer(pushEvent) + } + + return pushEvent + } + + /** @internal */ + _addToPushBuffer(pushEvent: Push) { + pushEvent.startTimeout() + this.pushBuffer.push(pushEvent) + + // Enforce buffer size limit + if (this.pushBuffer.length > MAX_PUSH_BUFFER_SIZE) { + const removedPush = this.pushBuffer.shift() + if (removedPush) { + removedPush.destroy() + this.socket.log( + 'channel', + `discarded push due to buffer overflow: ${removedPush.event}`, + removedPush.payload + ) + } + } + } + + /** + * Overridable message hook + * + * Receives all events for specialized message handling before dispatching to the channel callbacks. + * Must return the payload, modified or unmodified. + * + * @internal + */ + _onMessage(_event: string, payload: any, _ref?: string) { + return payload + } + + /** @internal */ + _isMember(topic: string): boolean { + return this.topic === topic + } + + /** @internal */ + _joinRef(): string { + return this.joinPush.ref + } + + /** @internal */ + _trigger(type: string, payload?: any, ref?: string) { + const typeLower = type.toLocaleLowerCase() + const { close, error, leave, join } = CHANNEL_EVENTS + const events: string[] = [close, error, leave, join] + if (ref && events.indexOf(typeLower) >= 0 && ref !== this._joinRef()) { + return + } + let handledPayload = this._onMessage(typeLower, payload, ref) + if (payload && !handledPayload) { + throw 'channel onMessage callbacks must return the payload, modified or unmodified' + } + + if (['insert', 'update', 'delete'].includes(typeLower)) { + this.bindings.postgres_changes + ?.filter((bind) => { + return bind.filter?.event === '*' || bind.filter?.event?.toLocaleLowerCase() === typeLower + }) + .map((bind) => bind.callback(handledPayload, ref)) + } else { + this.bindings[typeLower] + ?.filter((bind) => { + if (['broadcast', 'presence', 'postgres_changes'].includes(typeLower)) { + if ('id' in bind) { + const bindId = bind.id + const bindEvent = bind.filter?.event + return ( + bindId && + payload.ids?.includes(bindId) && + (bindEvent === '*' || + bindEvent?.toLocaleLowerCase() === payload.data?.type.toLocaleLowerCase()) + ) + } else { + const bindEvent = bind?.filter?.event?.toLocaleLowerCase() + return bindEvent === '*' || bindEvent === payload?.event?.toLocaleLowerCase() + } + } else { + return bind.type.toLocaleLowerCase() === typeLower + } + }) + .map((bind) => { + if (typeof handledPayload === 'object' && 'ids' in handledPayload) { + const postgresChanges = handledPayload.data + const { schema, table, commit_timestamp, type, errors } = postgresChanges + const enrichedPayload = { + schema: schema, + table: table, + commit_timestamp: commit_timestamp, + eventType: type, + new: {}, + old: {}, + errors: errors, + } + handledPayload = { + ...enrichedPayload, + ...this._getPayloadRecords(postgresChanges), + } + } + bind.callback(handledPayload, ref) + }) + } + } + + /** @internal */ + _isClosed(): boolean { + return this.state === CHANNEL_STATES.closed + } + + /** @internal */ + _isJoined(): boolean { + return this.state === CHANNEL_STATES.joined + } + + /** @internal */ + _isJoining(): boolean { + return this.state === CHANNEL_STATES.joining + } + + /** @internal */ + _isLeaving(): boolean { + return this.state === CHANNEL_STATES.leaving + } + + /** @internal */ + _replyEventName(ref: string): string { + return `chan_reply_${ref}` + } + + /** @internal */ + _on(type: string, filter: { [key: string]: any }, callback: Function) { + const typeLower = type.toLocaleLowerCase() + const binding = { + type: typeLower, + filter: filter, + callback: callback, + } + + if (this.bindings[typeLower]) { + this.bindings[typeLower].push(binding) + } else { + this.bindings[typeLower] = [binding] + } + + return this + } + + /** @internal */ + _off(type: string, filter: { [key: string]: any }) { + const typeLower = type.toLocaleLowerCase() + + if (this.bindings[typeLower]) { + this.bindings[typeLower] = this.bindings[typeLower].filter((bind) => { + return !( + bind.type?.toLocaleLowerCase() === typeLower && + RealtimeChannel.isEqual(bind.filter, filter) + ) + }) + } + return this + } + + /** @internal */ + private static isEqual(obj1: { [key: string]: string }, obj2: { [key: string]: string }) { + if (Object.keys(obj1).length !== Object.keys(obj2).length) { + return false + } + + for (const k in obj1) { + if (obj1[k] !== obj2[k]) { + return false + } + } + + return true + } + + /** + * Compares two optional filter values for equality. + * Treats undefined, null, and empty string as equivalent empty values. + * @internal + */ + private static isFilterValueEqual( + serverValue: string | undefined | null, + clientValue: string | undefined + ): boolean { + const normalizedServer = serverValue ?? undefined + const normalizedClient = clientValue ?? undefined + return normalizedServer === normalizedClient + } + + /** @internal */ + private _rejoinUntilConnected() { + this.rejoinTimer.scheduleTimeout() + if (this.socket.isConnected()) { + this._rejoin() + } + } + + /** + * Registers a callback that will be executed when the channel closes. + * + * @internal + */ + private _onClose(callback: Function) { + this._on(CHANNEL_EVENTS.close, {}, callback) + } + + /** + * Registers a callback that will be executed when the channel encounteres an error. + * + * @internal + */ + private _onError(callback: Function) { + this._on(CHANNEL_EVENTS.error, {}, (reason: string) => callback(reason)) + } + + /** + * Returns `true` if the socket is connected and the channel has been joined. + * + * @internal + */ + private _canPush(): boolean { + return this.socket.isConnected() && this._isJoined() + } + + /** @internal */ + private _rejoin(timeout = this.timeout): void { + if (this._isLeaving()) { + return + } + this.socket._leaveOpenTopic(this.topic) + this.state = CHANNEL_STATES.joining + this.joinPush.resend(timeout) + } + + /** @internal */ + private _getPayloadRecords(payload: any) { + const records = { + new: {}, + old: {}, + } + + if (payload.type === 'INSERT' || payload.type === 'UPDATE') { + records.new = Transformers.convertChangeData(payload.columns, payload.record) + } + + if (payload.type === 'UPDATE' || payload.type === 'DELETE') { + records.old = Transformers.convertChangeData(payload.columns, payload.old_record) + } + + return records + } +} diff --git a/backend/node_modules/@supabase/realtime-js/src/RealtimeClient.ts b/backend/node_modules/@supabase/realtime-js/src/RealtimeClient.ts new file mode 100644 index 0000000..9188047 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/src/RealtimeClient.ts @@ -0,0 +1,966 @@ +import WebSocketFactory, { WebSocketLike } from './lib/websocket-factory' + +import { + CHANNEL_EVENTS, + CONNECTION_STATE, + DEFAULT_VERSION, + DEFAULT_TIMEOUT, + SOCKET_STATES, + TRANSPORTS, + DEFAULT_VSN, + VSN_1_0_0, + VSN_2_0_0, + WS_CLOSE_NORMAL, +} from './lib/constants' + +import Serializer from './lib/serializer' +import Timer from './lib/timer' + +import { httpEndpointURL } from './lib/transformers' +import RealtimeChannel from './RealtimeChannel' +import type { RealtimeChannelOptions } from './RealtimeChannel' + +type Fetch = typeof fetch + +export type Channel = { + name: string + inserted_at: string + updated_at: string + id: number +} +export type LogLevel = 'info' | 'warn' | 'error' + +export type RealtimeMessage = { + topic: string + event: string + payload: any + ref: string + join_ref?: string +} + +export type RealtimeRemoveChannelResponse = 'ok' | 'timed out' | 'error' +export type HeartbeatStatus = 'sent' | 'ok' | 'error' | 'timeout' | 'disconnected' + +const noop = () => {} + +type RealtimeClientState = 'connecting' | 'connected' | 'disconnecting' | 'disconnected' + +// Connection-related constants +const CONNECTION_TIMEOUTS = { + HEARTBEAT_INTERVAL: 25000, + RECONNECT_DELAY: 10, + HEARTBEAT_TIMEOUT_FALLBACK: 100, +} as const + +const RECONNECT_INTERVALS = [1000, 2000, 5000, 10000] as const +const DEFAULT_RECONNECT_FALLBACK = 10000 + +/** + * Minimal WebSocket constructor interface that RealtimeClient can work with. + * Supply a compatible implementation (native WebSocket, `ws`, etc) when running outside the browser. + */ +export interface WebSocketLikeConstructor { + new (address: string | URL, subprotocols?: string | string[] | undefined): WebSocketLike + // Allow additional properties that may exist on WebSocket constructors + [key: string]: any +} + +export interface WebSocketLikeError { + error: any + message: string + type: string +} + +export type RealtimeClientOptions = { + transport?: WebSocketLikeConstructor + timeout?: number + heartbeatIntervalMs?: number + heartbeatCallback?: (status: HeartbeatStatus) => void + vsn?: string + logger?: Function + encode?: Function + decode?: Function + reconnectAfterMs?: Function + headers?: { [key: string]: string } + params?: { [key: string]: any } + //Deprecated: Use it in favour of correct casing `logLevel` + log_level?: LogLevel + logLevel?: LogLevel + fetch?: Fetch + worker?: boolean + workerUrl?: string + accessToken?: () => Promise +} + +const WORKER_SCRIPT = ` + addEventListener("message", (e) => { + if (e.data.event === "start") { + setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); + } + });` + +export default class RealtimeClient { + accessTokenValue: string | null = null + apiKey: string | null = null + private _manuallySetToken: boolean = false + channels: RealtimeChannel[] = new Array() + endPoint: string = '' + httpEndpoint: string = '' + /** @deprecated headers cannot be set on websocket connections */ + headers?: { [key: string]: string } = {} + params?: { [key: string]: string } = {} + timeout: number = DEFAULT_TIMEOUT + transport: WebSocketLikeConstructor | null = null + heartbeatIntervalMs: number = CONNECTION_TIMEOUTS.HEARTBEAT_INTERVAL + heartbeatTimer: ReturnType | undefined = undefined + pendingHeartbeatRef: string | null = null + heartbeatCallback: (status: HeartbeatStatus) => void = noop + ref: number = 0 + reconnectTimer: Timer | null = null + vsn: string = DEFAULT_VSN + logger: Function = noop + logLevel?: LogLevel + encode!: Function + decode!: Function + reconnectAfterMs!: Function + conn: WebSocketLike | null = null + sendBuffer: Function[] = [] + serializer: Serializer = new Serializer() + stateChangeCallbacks: { + open: Function[] + close: Function[] + error: Function[] + message: Function[] + } = { + open: [], + close: [], + error: [], + message: [], + } + fetch: Fetch + accessToken: (() => Promise) | null = null + worker?: boolean + workerUrl?: string + workerRef?: Worker + private _connectionState: RealtimeClientState = 'disconnected' + private _wasManualDisconnect: boolean = false + private _authPromise: Promise | null = null + + /** + * Initializes the Socket. + * + * @param endPoint The string WebSocket endpoint, ie, "ws://example.com/socket", "wss://example.com", "/socket" (inherited host & protocol) + * @param httpEndpoint The string HTTP endpoint, ie, "https://example.com", "/" (inherited host & protocol) + * @param options.transport The Websocket Transport, for example WebSocket. This can be a custom implementation + * @param options.timeout The default timeout in milliseconds to trigger push timeouts. + * @param options.params The optional params to pass when connecting. + * @param options.headers Deprecated: headers cannot be set on websocket connections and this option will be removed in the future. + * @param options.heartbeatIntervalMs The millisec interval to send a heartbeat message. + * @param options.heartbeatCallback The optional function to handle heartbeat status. + * @param options.logger The optional function for specialized logging, ie: logger: (kind, msg, data) => { console.log(`${kind}: ${msg}`, data) } + * @param options.logLevel Sets the log level for Realtime + * @param options.encode The function to encode outgoing messages. Defaults to JSON: (payload, callback) => callback(JSON.stringify(payload)) + * @param options.decode The function to decode incoming messages. Defaults to Serializer's decode. + * @param options.reconnectAfterMs he optional function that returns the millsec reconnect interval. Defaults to stepped backoff off. + * @param options.worker Use Web Worker to set a side flow. Defaults to false. + * @param options.workerUrl The URL of the worker script. Defaults to https://realtime.supabase.com/worker.js that includes a heartbeat event call to keep the connection alive. + * @example + * ```ts + * import RealtimeClient from '@supabase/realtime-js' + * + * const client = new RealtimeClient('https://xyzcompany.supabase.co/realtime/v1', { + * params: { apikey: 'public-anon-key' }, + * }) + * client.connect() + * ``` + */ + constructor(endPoint: string, options?: RealtimeClientOptions) { + // Validate required parameters + if (!options?.params?.apikey) { + throw new Error('API key is required to connect to Realtime') + } + this.apiKey = options.params.apikey + + // Initialize endpoint URLs + this.endPoint = `${endPoint}/${TRANSPORTS.websocket}` + this.httpEndpoint = httpEndpointURL(endPoint) + + this._initializeOptions(options) + this._setupReconnectionTimer() + this.fetch = this._resolveFetch(options?.fetch) + } + + /** + * Connects the socket, unless already connected. + */ + connect(): void { + // Skip if already connecting, disconnecting, or connected + if ( + this.isConnecting() || + this.isDisconnecting() || + (this.conn !== null && this.isConnected()) + ) { + return + } + + this._setConnectionState('connecting') + + // Trigger auth if needed and not already in progress + // This ensures auth is called for standalone RealtimeClient usage + // while avoiding race conditions with SupabaseClient's immediate setAuth call + if (this.accessToken && !this._authPromise) { + this._setAuthSafely('connect') + } + + // Establish WebSocket connection + if (this.transport) { + // Use custom transport if provided + this.conn = new this.transport(this.endpointURL()) as WebSocketLike + } else { + // Try to use native WebSocket + try { + this.conn = WebSocketFactory.createWebSocket(this.endpointURL()) + } catch (error) { + this._setConnectionState('disconnected') + const errorMessage = (error as Error).message + + // Provide helpful error message based on environment + if (errorMessage.includes('Node.js')) { + throw new Error( + `${errorMessage}\n\n` + + 'To use Realtime in Node.js, you need to provide a WebSocket implementation:\n\n' + + 'Option 1: Use Node.js 22+ which has native WebSocket support\n' + + 'Option 2: Install and provide the "ws" package:\n\n' + + ' npm install ws\n\n' + + ' import ws from "ws"\n' + + ' const client = new RealtimeClient(url, {\n' + + ' ...options,\n' + + ' transport: ws\n' + + ' })' + ) + } + throw new Error(`WebSocket not available: ${errorMessage}`) + } + } + this._setupConnectionHandlers() + } + + /** + * Returns the URL of the websocket. + * @returns string The URL of the websocket. + */ + endpointURL(): string { + return this._appendParams(this.endPoint, Object.assign({}, this.params, { vsn: this.vsn })) + } + + /** + * Disconnects the socket. + * + * @param code A numeric status code to send on disconnect. + * @param reason A custom reason for the disconnect. + */ + disconnect(code?: number, reason?: string): void { + if (this.isDisconnecting()) { + return + } + + this._setConnectionState('disconnecting', true) + + if (this.conn) { + // Setup fallback timer to prevent hanging in disconnecting state + const fallbackTimer = setTimeout(() => { + this._setConnectionState('disconnected') + }, 100) + + this.conn.onclose = () => { + clearTimeout(fallbackTimer) + this._setConnectionState('disconnected') + } + + // Close the WebSocket connection if close method exists + if (typeof this.conn.close === 'function') { + if (code) { + this.conn.close(code, reason ?? '') + } else { + this.conn.close() + } + } + + this._teardownConnection() + } else { + this._setConnectionState('disconnected') + } + } + + /** + * Returns all created channels + */ + getChannels(): RealtimeChannel[] { + return this.channels + } + + /** + * Unsubscribes and removes a single channel + * @param channel A RealtimeChannel instance + */ + async removeChannel(channel: RealtimeChannel): Promise { + const status = await channel.unsubscribe() + + if (this.channels.length === 0) { + this.disconnect() + } + + return status + } + + /** + * Unsubscribes and removes all channels + */ + async removeAllChannels(): Promise { + const values_1 = await Promise.all(this.channels.map((channel) => channel.unsubscribe())) + this.channels = [] + this.disconnect() + return values_1 + } + + /** + * Logs the message. + * + * For customized logging, `this.logger` can be overridden. + */ + log(kind: string, msg: string, data?: any) { + this.logger(kind, msg, data) + } + + /** + * Returns the current state of the socket. + */ + connectionState(): CONNECTION_STATE { + switch (this.conn && this.conn.readyState) { + case SOCKET_STATES.connecting: + return CONNECTION_STATE.Connecting + case SOCKET_STATES.open: + return CONNECTION_STATE.Open + case SOCKET_STATES.closing: + return CONNECTION_STATE.Closing + default: + return CONNECTION_STATE.Closed + } + } + + /** + * Returns `true` is the connection is open. + */ + isConnected(): boolean { + return this.connectionState() === CONNECTION_STATE.Open + } + + /** + * Returns `true` if the connection is currently connecting. + */ + isConnecting(): boolean { + return this._connectionState === 'connecting' + } + + /** + * Returns `true` if the connection is currently disconnecting. + */ + isDisconnecting(): boolean { + return this._connectionState === 'disconnecting' + } + + /** + * Creates (or reuses) a {@link RealtimeChannel} for the provided topic. + * + * Topics are automatically prefixed with `realtime:` to match the Realtime service. + * If a channel with the same topic already exists it will be returned instead of creating + * a duplicate connection. + */ + channel(topic: string, params: RealtimeChannelOptions = { config: {} }): RealtimeChannel { + const realtimeTopic = `realtime:${topic}` + const exists = this.getChannels().find((c: RealtimeChannel) => c.topic === realtimeTopic) + + if (!exists) { + const chan = new RealtimeChannel(`realtime:${topic}`, params, this) + this.channels.push(chan) + + return chan + } else { + return exists + } + } + + /** + * Push out a message if the socket is connected. + * + * If the socket is not connected, the message gets enqueued within a local buffer, and sent out when a connection is next established. + */ + push(data: RealtimeMessage): void { + const { topic, event, payload, ref } = data + const callback = () => { + this.encode(data, (result: any) => { + this.conn?.send(result) + }) + } + this.log('push', `${topic} ${event} (${ref})`, payload) + if (this.isConnected()) { + callback() + } else { + this.sendBuffer.push(callback) + } + } + + /** + * Sets the JWT access token used for channel subscription authorization and Realtime RLS. + * + * If param is null it will use the `accessToken` callback function or the token set on the client. + * + * On callback used, it will set the value of the token internal to the client. + * + * When a token is explicitly provided, it will be preserved across channel operations + * (including removeChannel and resubscribe). The `accessToken` callback will not be + * invoked until `setAuth()` is called without arguments. + * + * @param token A JWT string to override the token set on the client. + * + * @example + * // Use a manual token (preserved across resubscribes, ignores accessToken callback) + * client.realtime.setAuth('my-custom-jwt') + * + * // Switch back to using the accessToken callback + * client.realtime.setAuth() + */ + async setAuth(token: string | null = null): Promise { + this._authPromise = this._performAuth(token) + try { + await this._authPromise + } finally { + this._authPromise = null + } + } + + /** + * Returns true if the current access token was explicitly set via setAuth(token), + * false if it was obtained via the accessToken callback. + * @internal + */ + _isManualToken(): boolean { + return this._manuallySetToken + } + + /** + * Sends a heartbeat message if the socket is connected. + */ + async sendHeartbeat() { + if (!this.isConnected()) { + try { + this.heartbeatCallback('disconnected') + } catch (e) { + this.log('error', 'error in heartbeat callback', e) + } + return + } + + // Handle heartbeat timeout and force reconnection if needed + if (this.pendingHeartbeatRef) { + this.pendingHeartbeatRef = null + this.log('transport', 'heartbeat timeout. Attempting to re-establish connection') + try { + this.heartbeatCallback('timeout') + } catch (e) { + this.log('error', 'error in heartbeat callback', e) + } + + // Force reconnection after heartbeat timeout + this._wasManualDisconnect = false + this.conn?.close(WS_CLOSE_NORMAL, 'heartbeat timeout') + + setTimeout(() => { + if (!this.isConnected()) { + this.reconnectTimer?.scheduleTimeout() + } + }, CONNECTION_TIMEOUTS.HEARTBEAT_TIMEOUT_FALLBACK) + return + } + + // Send heartbeat message to server + this.pendingHeartbeatRef = this._makeRef() + this.push({ + topic: 'phoenix', + event: 'heartbeat', + payload: {}, + ref: this.pendingHeartbeatRef, + }) + try { + this.heartbeatCallback('sent') + } catch (e) { + this.log('error', 'error in heartbeat callback', e) + } + + this._setAuthSafely('heartbeat') + } + + /** + * Sets a callback that receives lifecycle events for internal heartbeat messages. + * Useful for instrumenting connection health (e.g. sent/ok/timeout/disconnected). + */ + onHeartbeat(callback: (status: HeartbeatStatus) => void): void { + this.heartbeatCallback = callback + } + /** + * Flushes send buffer + */ + flushSendBuffer() { + if (this.isConnected() && this.sendBuffer.length > 0) { + this.sendBuffer.forEach((callback) => callback()) + this.sendBuffer = [] + } + } + + /** + * Use either custom fetch, if provided, or default fetch to make HTTP requests + * + * @internal + */ + _resolveFetch = (customFetch?: Fetch): Fetch => { + if (customFetch) { + return (...args) => customFetch(...args) + } + return (...args) => fetch(...args) + } + + /** + * Return the next message ref, accounting for overflows + * + * @internal + */ + _makeRef(): string { + let newRef = this.ref + 1 + if (newRef === this.ref) { + this.ref = 0 + } else { + this.ref = newRef + } + + return this.ref.toString() + } + + /** + * Unsubscribe from channels with the specified topic. + * + * @internal + */ + _leaveOpenTopic(topic: string): void { + let dupChannel = this.channels.find( + (c) => c.topic === topic && (c._isJoined() || c._isJoining()) + ) + if (dupChannel) { + this.log('transport', `leaving duplicate topic "${topic}"`) + dupChannel.unsubscribe() + } + } + + /** + * Removes a subscription from the socket. + * + * @param channel An open subscription. + * + * @internal + */ + _remove(channel: RealtimeChannel) { + this.channels = this.channels.filter((c) => c.topic !== channel.topic) + } + + /** @internal */ + private _onConnMessage(rawMessage: { data: any }) { + this.decode(rawMessage.data, (msg: RealtimeMessage) => { + // Handle heartbeat responses + if (msg.topic === 'phoenix' && msg.event === 'phx_reply') { + try { + this.heartbeatCallback(msg.payload.status === 'ok' ? 'ok' : 'error') + } catch (e) { + this.log('error', 'error in heartbeat callback', e) + } + } + + // Handle pending heartbeat reference cleanup + if (msg.ref && msg.ref === this.pendingHeartbeatRef) { + this.pendingHeartbeatRef = null + } + + // Log incoming message + const { topic, event, payload, ref } = msg + const refString = ref ? `(${ref})` : '' + const status = payload.status || '' + this.log('receive', `${status} ${topic} ${event} ${refString}`.trim(), payload) + + // Route message to appropriate channels + this.channels + .filter((channel: RealtimeChannel) => channel._isMember(topic)) + .forEach((channel: RealtimeChannel) => channel._trigger(event, payload, ref)) + + this._triggerStateCallbacks('message', msg) + }) + } + + /** + * Clear specific timer + * @internal + */ + private _clearTimer(timer: 'heartbeat' | 'reconnect'): void { + if (timer === 'heartbeat' && this.heartbeatTimer) { + clearInterval(this.heartbeatTimer) + this.heartbeatTimer = undefined + } else if (timer === 'reconnect') { + this.reconnectTimer?.reset() + } + } + + /** + * Clear all timers + * @internal + */ + private _clearAllTimers(): void { + this._clearTimer('heartbeat') + this._clearTimer('reconnect') + } + + /** + * Setup connection handlers for WebSocket events + * @internal + */ + private _setupConnectionHandlers(): void { + if (!this.conn) return + + // Set binary type if supported (browsers and most WebSocket implementations) + if ('binaryType' in this.conn) { + ;(this.conn as any).binaryType = 'arraybuffer' + } + + this.conn.onopen = () => this._onConnOpen() + this.conn.onerror = (error: Event) => this._onConnError(error) + this.conn.onmessage = (event: any) => this._onConnMessage(event) + this.conn.onclose = (event: any) => this._onConnClose(event) + } + + /** + * Teardown connection and cleanup resources + * @internal + */ + private _teardownConnection(): void { + if (this.conn) { + if ( + this.conn.readyState === SOCKET_STATES.open || + this.conn.readyState === SOCKET_STATES.connecting + ) { + try { + this.conn.close() + } catch (e) { + this.log('error', 'Error closing connection', e) + } + } + + this.conn.onopen = null + this.conn.onerror = null + this.conn.onmessage = null + this.conn.onclose = null + this.conn = null + } + this._clearAllTimers() + this.channels.forEach((channel) => channel.teardown()) + } + + /** @internal */ + private _onConnOpen() { + this._setConnectionState('connected') + this.log('transport', `connected to ${this.endpointURL()}`) + + // Wait for any pending auth operations before flushing send buffer + // This ensures channel join messages include the correct access token + const authPromise = + this._authPromise || + (this.accessToken && !this.accessTokenValue ? this.setAuth() : Promise.resolve()) + + authPromise + .then(() => { + this.flushSendBuffer() + }) + .catch((e) => { + this.log('error', 'error waiting for auth on connect', e) + // Proceed anyway to avoid hanging connections + this.flushSendBuffer() + }) + + this._clearTimer('reconnect') + + if (!this.worker) { + this._startHeartbeat() + } else { + if (!this.workerRef) { + this._startWorkerHeartbeat() + } + } + + this._triggerStateCallbacks('open') + } + /** @internal */ + private _startHeartbeat() { + this.heartbeatTimer && clearInterval(this.heartbeatTimer) + this.heartbeatTimer = setInterval(() => this.sendHeartbeat(), this.heartbeatIntervalMs) + } + + /** @internal */ + private _startWorkerHeartbeat() { + if (this.workerUrl) { + this.log('worker', `starting worker for from ${this.workerUrl}`) + } else { + this.log('worker', `starting default worker`) + } + const objectUrl = this._workerObjectUrl(this.workerUrl!) + this.workerRef = new Worker(objectUrl) + this.workerRef.onerror = (error) => { + this.log('worker', 'worker error', (error as ErrorEvent).message) + this.workerRef!.terminate() + } + this.workerRef.onmessage = (event) => { + if (event.data.event === 'keepAlive') { + this.sendHeartbeat() + } + } + this.workerRef.postMessage({ + event: 'start', + interval: this.heartbeatIntervalMs, + }) + } + /** @internal */ + private _onConnClose(event: any) { + this._setConnectionState('disconnected') + this.log('transport', 'close', event) + this._triggerChanError() + this._clearTimer('heartbeat') + + // Only schedule reconnection if it wasn't a manual disconnect + if (!this._wasManualDisconnect) { + this.reconnectTimer?.scheduleTimeout() + } + + this._triggerStateCallbacks('close', event) + } + + /** @internal */ + private _onConnError(error: Event) { + this._setConnectionState('disconnected') + this.log('transport', `${error}`) + this._triggerChanError() + this._triggerStateCallbacks('error', error) + } + + /** @internal */ + private _triggerChanError() { + this.channels.forEach((channel: RealtimeChannel) => channel._trigger(CHANNEL_EVENTS.error)) + } + + /** @internal */ + private _appendParams(url: string, params: { [key: string]: string }): string { + if (Object.keys(params).length === 0) { + return url + } + const prefix = url.match(/\?/) ? '&' : '?' + const query = new URLSearchParams(params) + return `${url}${prefix}${query}` + } + + private _workerObjectUrl(url: string | undefined): string { + let result_url: string + if (url) { + result_url = url + } else { + const blob = new Blob([WORKER_SCRIPT], { type: 'application/javascript' }) + result_url = URL.createObjectURL(blob) + } + return result_url + } + + /** + * Set connection state with proper state management + * @internal + */ + private _setConnectionState(state: RealtimeClientState, manual = false): void { + this._connectionState = state + + if (state === 'connecting') { + this._wasManualDisconnect = false + } else if (state === 'disconnecting') { + this._wasManualDisconnect = manual + } + } + + /** + * Perform the actual auth operation + * @internal + */ + private async _performAuth(token: string | null = null): Promise { + let tokenToSend: string | null + let isManualToken = false + + if (token) { + tokenToSend = token + // Track if this is a manually-provided token + isManualToken = true + } else if (this.accessToken) { + // Call the accessToken callback to get fresh token + try { + tokenToSend = await this.accessToken() + } catch (e) { + this.log('error', 'Error fetching access token from callback', e) + // Fall back to cached value if callback fails + tokenToSend = this.accessTokenValue + } + } else { + tokenToSend = this.accessTokenValue + } + + // Track whether this token was manually set or fetched via callback + if (isManualToken) { + this._manuallySetToken = true + } else if (this.accessToken) { + // If we used the callback, clear the manual flag + this._manuallySetToken = false + } + + if (this.accessTokenValue != tokenToSend) { + this.accessTokenValue = tokenToSend + this.channels.forEach((channel) => { + const payload = { + access_token: tokenToSend, + version: DEFAULT_VERSION, + } + + tokenToSend && channel.updateJoinPayload(payload) + + if (channel.joinedOnce && channel._isJoined()) { + channel._push(CHANNEL_EVENTS.access_token, { + access_token: tokenToSend, + }) + } + }) + } + } + + /** + * Wait for any in-flight auth operations to complete + * @internal + */ + private async _waitForAuthIfNeeded(): Promise { + if (this._authPromise) { + await this._authPromise + } + } + + /** + * Safely call setAuth with standardized error handling + * @internal + */ + private _setAuthSafely(context = 'general'): void { + // Only refresh auth if using callback-based tokens + if (!this._isManualToken()) { + this.setAuth().catch((e) => { + this.log('error', `Error setting auth in ${context}`, e) + }) + } + } + + /** + * Trigger state change callbacks with proper error handling + * @internal + */ + private _triggerStateCallbacks(event: keyof typeof this.stateChangeCallbacks, data?: any): void { + try { + this.stateChangeCallbacks[event].forEach((callback) => { + try { + callback(data) + } catch (e) { + this.log('error', `error in ${event} callback`, e) + } + }) + } catch (e) { + this.log('error', `error triggering ${event} callbacks`, e) + } + } + + /** + * Setup reconnection timer with proper configuration + * @internal + */ + private _setupReconnectionTimer(): void { + this.reconnectTimer = new Timer(async () => { + setTimeout(async () => { + await this._waitForAuthIfNeeded() + if (!this.isConnected()) { + this.connect() + } + }, CONNECTION_TIMEOUTS.RECONNECT_DELAY) + }, this.reconnectAfterMs) + } + + /** + * Initialize client options with defaults + * @internal + */ + private _initializeOptions(options?: RealtimeClientOptions): void { + // Set defaults + this.transport = options?.transport ?? null + this.timeout = options?.timeout ?? DEFAULT_TIMEOUT + this.heartbeatIntervalMs = + options?.heartbeatIntervalMs ?? CONNECTION_TIMEOUTS.HEARTBEAT_INTERVAL + this.worker = options?.worker ?? false + this.accessToken = options?.accessToken ?? null + this.heartbeatCallback = options?.heartbeatCallback ?? noop + this.vsn = options?.vsn ?? DEFAULT_VSN + + // Handle special cases + if (options?.params) this.params = options.params + if (options?.logger) this.logger = options.logger + if (options?.logLevel || options?.log_level) { + this.logLevel = options.logLevel || options.log_level + this.params = { ...this.params, log_level: this.logLevel as string } + } + + // Set up functions with defaults + this.reconnectAfterMs = + options?.reconnectAfterMs ?? + ((tries: number) => { + return RECONNECT_INTERVALS[tries - 1] || DEFAULT_RECONNECT_FALLBACK + }) + + switch (this.vsn) { + case VSN_1_0_0: + this.encode = + options?.encode ?? + ((payload: JSON, callback: Function) => { + return callback(JSON.stringify(payload)) + }) + + this.decode = + options?.decode ?? + ((payload: string, callback: Function) => { + return callback(JSON.parse(payload)) + }) + break + case VSN_2_0_0: + this.encode = options?.encode ?? this.serializer.encode.bind(this.serializer) + this.decode = options?.decode ?? this.serializer.decode.bind(this.serializer) + break + default: + throw new Error(`Unsupported serializer version: ${this.vsn}`) + } + + // Handle worker setup + if (this.worker) { + if (typeof window !== 'undefined' && !window.Worker) { + throw new Error('Web Worker is not supported') + } + this.workerUrl = options?.workerUrl + } + } +} diff --git a/backend/node_modules/@supabase/realtime-js/src/RealtimePresence.ts b/backend/node_modules/@supabase/realtime-js/src/RealtimePresence.ts new file mode 100644 index 0000000..aaa5d21 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/src/RealtimePresence.ts @@ -0,0 +1,346 @@ +/* + This file draws heavily from https://github.com/phoenixframework/phoenix/blob/d344ec0a732ab4ee204215b31de69cf4be72e3bf/assets/js/phoenix/presence.js + License: https://github.com/phoenixframework/phoenix/blob/d344ec0a732ab4ee204215b31de69cf4be72e3bf/LICENSE.md +*/ + +import type { PresenceOpts, PresenceOnJoinCallback, PresenceOnLeaveCallback } from 'phoenix' +import type RealtimeChannel from './RealtimeChannel' + +type Presence = { + presence_ref: string +} & T + +export type RealtimePresenceState = { + [key: string]: Presence[] +} + +export type RealtimePresenceJoinPayload = { + event: `${REALTIME_PRESENCE_LISTEN_EVENTS.JOIN}` + key: string + currentPresences: Presence[] + newPresences: Presence[] +} + +export type RealtimePresenceLeavePayload = { + event: `${REALTIME_PRESENCE_LISTEN_EVENTS.LEAVE}` + key: string + currentPresences: Presence[] + leftPresences: Presence[] +} + +export enum REALTIME_PRESENCE_LISTEN_EVENTS { + SYNC = 'sync', + JOIN = 'join', + LEAVE = 'leave', +} + +type PresenceDiff = { + joins: RealtimePresenceState + leaves: RealtimePresenceState +} + +type RawPresenceState = { + [key: string]: { + metas: { + phx_ref?: string + phx_ref_prev?: string + [key: string]: any + }[] + } +} + +type RawPresenceDiff = { + joins: RawPresenceState + leaves: RawPresenceState +} + +type PresenceChooser = (key: string, presences: Presence[]) => T + +export default class RealtimePresence { + state: RealtimePresenceState = {} + pendingDiffs: RawPresenceDiff[] = [] + joinRef: string | null = null + enabled: boolean = false + caller: { + onJoin: PresenceOnJoinCallback + onLeave: PresenceOnLeaveCallback + onSync: () => void + } = { + onJoin: () => {}, + onLeave: () => {}, + onSync: () => {}, + } + + /** + * Creates a Presence helper that keeps the local presence state in sync with the server. + * + * @param channel - The realtime channel to bind to. + * @param opts - Optional custom event names, e.g. `{ events: { state: 'state', diff: 'diff' } }`. + * + * @example + * ```ts + * const presence = new RealtimePresence(channel) + * + * channel.on('presence', ({ event, key }) => { + * console.log(`Presence ${event} on ${key}`) + * }) + * ``` + */ + constructor( + public channel: RealtimeChannel, + opts?: PresenceOpts + ) { + const events = opts?.events || { + state: 'presence_state', + diff: 'presence_diff', + } + + this.channel._on(events.state, {}, (newState: RawPresenceState) => { + const { onJoin, onLeave, onSync } = this.caller + + this.joinRef = this.channel._joinRef() + + this.state = RealtimePresence.syncState(this.state, newState, onJoin, onLeave) + + this.pendingDiffs.forEach((diff) => { + this.state = RealtimePresence.syncDiff(this.state, diff, onJoin, onLeave) + }) + + this.pendingDiffs = [] + + onSync() + }) + + this.channel._on(events.diff, {}, (diff: RawPresenceDiff) => { + const { onJoin, onLeave, onSync } = this.caller + + if (this.inPendingSyncState()) { + this.pendingDiffs.push(diff) + } else { + this.state = RealtimePresence.syncDiff(this.state, diff, onJoin, onLeave) + + onSync() + } + }) + + this.onJoin((key, currentPresences, newPresences) => { + this.channel._trigger('presence', { + event: 'join', + key, + currentPresences, + newPresences, + }) + }) + + this.onLeave((key, currentPresences, leftPresences) => { + this.channel._trigger('presence', { + event: 'leave', + key, + currentPresences, + leftPresences, + }) + }) + + this.onSync(() => { + this.channel._trigger('presence', { event: 'sync' }) + }) + } + + /** + * Used to sync the list of presences on the server with the + * client's state. + * + * An optional `onJoin` and `onLeave` callback can be provided to + * react to changes in the client's local presences across + * disconnects and reconnects with the server. + * + * @internal + */ + private static syncState( + currentState: RealtimePresenceState, + newState: RawPresenceState | RealtimePresenceState, + onJoin: PresenceOnJoinCallback, + onLeave: PresenceOnLeaveCallback + ): RealtimePresenceState { + const state = this.cloneDeep(currentState) + const transformedState = this.transformState(newState) + const joins: RealtimePresenceState = {} + const leaves: RealtimePresenceState = {} + + this.map(state, (key: string, presences: Presence[]) => { + if (!transformedState[key]) { + leaves[key] = presences + } + }) + + this.map(transformedState, (key, newPresences: Presence[]) => { + const currentPresences: Presence[] = state[key] + + if (currentPresences) { + const newPresenceRefs = newPresences.map((m: Presence) => m.presence_ref) + const curPresenceRefs = currentPresences.map((m: Presence) => m.presence_ref) + const joinedPresences: Presence[] = newPresences.filter( + (m: Presence) => curPresenceRefs.indexOf(m.presence_ref) < 0 + ) + const leftPresences: Presence[] = currentPresences.filter( + (m: Presence) => newPresenceRefs.indexOf(m.presence_ref) < 0 + ) + + if (joinedPresences.length > 0) { + joins[key] = joinedPresences + } + + if (leftPresences.length > 0) { + leaves[key] = leftPresences + } + } else { + joins[key] = newPresences + } + }) + + return this.syncDiff(state, { joins, leaves }, onJoin, onLeave) + } + + /** + * Used to sync a diff of presence join and leave events from the + * server, as they happen. + * + * Like `syncState`, `syncDiff` accepts optional `onJoin` and + * `onLeave` callbacks to react to a user joining or leaving from a + * device. + * + * @internal + */ + private static syncDiff( + state: RealtimePresenceState, + diff: RawPresenceDiff | PresenceDiff, + onJoin: PresenceOnJoinCallback, + onLeave: PresenceOnLeaveCallback + ): RealtimePresenceState { + const { joins, leaves } = { + joins: this.transformState(diff.joins), + leaves: this.transformState(diff.leaves), + } + + if (!onJoin) { + onJoin = () => {} + } + + if (!onLeave) { + onLeave = () => {} + } + + this.map(joins, (key, newPresences: Presence[]) => { + const currentPresences: Presence[] = state[key] ?? [] + state[key] = this.cloneDeep(newPresences) + + if (currentPresences.length > 0) { + const joinedPresenceRefs = state[key].map((m: Presence) => m.presence_ref) + const curPresences: Presence[] = currentPresences.filter( + (m: Presence) => joinedPresenceRefs.indexOf(m.presence_ref) < 0 + ) + + state[key].unshift(...curPresences) + } + + onJoin(key, currentPresences, newPresences) + }) + + this.map(leaves, (key, leftPresences: Presence[]) => { + let currentPresences: Presence[] = state[key] + + if (!currentPresences) return + + const presenceRefsToRemove = leftPresences.map((m: Presence) => m.presence_ref) + currentPresences = currentPresences.filter( + (m: Presence) => presenceRefsToRemove.indexOf(m.presence_ref) < 0 + ) + + state[key] = currentPresences + + onLeave(key, currentPresences, leftPresences) + + if (currentPresences.length === 0) delete state[key] + }) + + return state + } + + /** @internal */ + private static map(obj: RealtimePresenceState, func: PresenceChooser): T[] { + return Object.getOwnPropertyNames(obj).map((key) => func(key, obj[key])) + } + + /** + * Remove 'metas' key + * Change 'phx_ref' to 'presence_ref' + * Remove 'phx_ref' and 'phx_ref_prev' + * + * @example + * // returns { + * abc123: [ + * { presence_ref: '2', user_id: 1 }, + * { presence_ref: '3', user_id: 2 } + * ] + * } + * RealtimePresence.transformState({ + * abc123: { + * metas: [ + * { phx_ref: '2', phx_ref_prev: '1' user_id: 1 }, + * { phx_ref: '3', user_id: 2 } + * ] + * } + * }) + * + * @internal + */ + private static transformState( + state: RawPresenceState | RealtimePresenceState + ): RealtimePresenceState { + state = this.cloneDeep(state) + + return Object.getOwnPropertyNames(state).reduce((newState, key) => { + const presences = state[key] + + if ('metas' in presences) { + newState[key] = presences.metas.map((presence) => { + presence['presence_ref'] = presence['phx_ref'] + + delete presence['phx_ref'] + delete presence['phx_ref_prev'] + + return presence + }) as Presence[] + } else { + newState[key] = presences + } + + return newState + }, {} as RealtimePresenceState) + } + + /** @internal */ + private static cloneDeep(obj: { [key: string]: any }) { + return JSON.parse(JSON.stringify(obj)) + } + + /** @internal */ + private onJoin(callback: PresenceOnJoinCallback): void { + this.caller.onJoin = callback + } + + /** @internal */ + private onLeave(callback: PresenceOnLeaveCallback): void { + this.caller.onLeave = callback + } + + /** @internal */ + private onSync(callback: () => void): void { + this.caller.onSync = callback + } + + /** @internal */ + private inPendingSyncState(): boolean { + return !this.joinRef || this.joinRef !== this.channel._joinRef() + } +} diff --git a/backend/node_modules/@supabase/realtime-js/src/index.ts b/backend/node_modules/@supabase/realtime-js/src/index.ts new file mode 100644 index 0000000..1620115 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/src/index.ts @@ -0,0 +1,53 @@ +import RealtimeClient, { + RealtimeClientOptions, + RealtimeMessage, + RealtimeRemoveChannelResponse, + WebSocketLikeConstructor, +} from './RealtimeClient' +import RealtimeChannel, { + RealtimeChannelOptions, + RealtimeChannelSendResponse, + RealtimePostgresChangesFilter, + RealtimePostgresChangesPayload, + RealtimePostgresInsertPayload, + RealtimePostgresUpdatePayload, + RealtimePostgresDeletePayload, + REALTIME_LISTEN_TYPES, + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT, + REALTIME_SUBSCRIBE_STATES, + REALTIME_CHANNEL_STATES, +} from './RealtimeChannel' +import RealtimePresence, { + RealtimePresenceState, + RealtimePresenceJoinPayload, + RealtimePresenceLeavePayload, + REALTIME_PRESENCE_LISTEN_EVENTS, +} from './RealtimePresence' +import WebSocketFactory, { WebSocketLike } from './lib/websocket-factory' + +export { + RealtimePresence, + RealtimeChannel, + RealtimeChannelOptions, + RealtimeChannelSendResponse, + RealtimeClient, + RealtimeClientOptions, + RealtimeMessage, + RealtimePostgresChangesFilter, + RealtimePostgresChangesPayload, + RealtimePostgresInsertPayload, + RealtimePostgresUpdatePayload, + RealtimePostgresDeletePayload, + RealtimePresenceJoinPayload, + RealtimePresenceLeavePayload, + RealtimePresenceState, + RealtimeRemoveChannelResponse, + REALTIME_LISTEN_TYPES, + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT, + REALTIME_PRESENCE_LISTEN_EVENTS, + REALTIME_SUBSCRIBE_STATES, + REALTIME_CHANNEL_STATES, + WebSocketFactory, + WebSocketLike, + WebSocketLikeConstructor, +} diff --git a/backend/node_modules/@supabase/realtime-js/src/lib/constants.ts b/backend/node_modules/@supabase/realtime-js/src/lib/constants.ts new file mode 100644 index 0000000..9024833 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/src/lib/constants.ts @@ -0,0 +1,49 @@ +import { version } from './version' + +export const DEFAULT_VERSION = `realtime-js/${version}` + +export const VSN_1_0_0: string = '1.0.0' +export const VSN_2_0_0: string = '2.0.0' +export const DEFAULT_VSN: string = VSN_1_0_0 + +export const VERSION = version + +export const DEFAULT_TIMEOUT = 10000 + +export const WS_CLOSE_NORMAL = 1000 +export const MAX_PUSH_BUFFER_SIZE = 100 + +export enum SOCKET_STATES { + connecting = 0, + open = 1, + closing = 2, + closed = 3, +} + +export enum CHANNEL_STATES { + closed = 'closed', + errored = 'errored', + joined = 'joined', + joining = 'joining', + leaving = 'leaving', +} + +export enum CHANNEL_EVENTS { + close = 'phx_close', + error = 'phx_error', + join = 'phx_join', + reply = 'phx_reply', + leave = 'phx_leave', + access_token = 'access_token', +} + +export enum TRANSPORTS { + websocket = 'websocket', +} + +export enum CONNECTION_STATE { + Connecting = 'connecting', + Open = 'open', + Closing = 'closing', + Closed = 'closed', +} diff --git a/backend/node_modules/@supabase/realtime-js/src/lib/push.ts b/backend/node_modules/@supabase/realtime-js/src/lib/push.ts new file mode 100644 index 0000000..9bf77f1 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/src/lib/push.ts @@ -0,0 +1,121 @@ +import { DEFAULT_TIMEOUT } from '../lib/constants' +import type RealtimeChannel from '../RealtimeChannel' + +export default class Push { + sent: boolean = false + timeoutTimer: number | undefined = undefined + ref: string = '' + receivedResp: { + status: string + response: { [key: string]: any } + } | null = null + recHooks: { + status: string + callback: Function + }[] = [] + refEvent: string | null = null + + /** + * Initializes the Push + * + * @param channel The Channel + * @param event The event, for example `"phx_join"` + * @param payload The payload, for example `{user_id: 123}` + * @param timeout The push timeout in milliseconds + */ + constructor( + public channel: RealtimeChannel, + public event: string, + public payload: { [key: string]: any } = {}, + public timeout: number = DEFAULT_TIMEOUT + ) {} + + resend(timeout: number) { + this.timeout = timeout + this._cancelRefEvent() + this.ref = '' + this.refEvent = null + this.receivedResp = null + this.sent = false + this.send() + } + + send() { + if (this._hasReceived('timeout')) { + return + } + this.startTimeout() + this.sent = true + this.channel.socket.push({ + topic: this.channel.topic, + event: this.event, + payload: this.payload, + ref: this.ref, + join_ref: this.channel._joinRef(), + }) + } + + updatePayload(payload: { [key: string]: any }): void { + this.payload = { ...this.payload, ...payload } + } + + receive(status: string, callback: Function) { + if (this._hasReceived(status)) { + callback(this.receivedResp?.response) + } + + this.recHooks.push({ status, callback }) + return this + } + + startTimeout() { + if (this.timeoutTimer) { + return + } + this.ref = this.channel.socket._makeRef() + this.refEvent = this.channel._replyEventName(this.ref) + + const callback = (payload: any) => { + this._cancelRefEvent() + this._cancelTimeout() + this.receivedResp = payload + this._matchReceive(payload) + } + + this.channel._on(this.refEvent, {}, callback) + + this.timeoutTimer = setTimeout(() => { + this.trigger('timeout', {}) + }, this.timeout) + } + + trigger(status: string, response: any) { + if (this.refEvent) this.channel._trigger(this.refEvent, { status, response }) + } + + destroy() { + this._cancelRefEvent() + this._cancelTimeout() + } + + private _cancelRefEvent() { + if (!this.refEvent) { + return + } + + this.channel._off(this.refEvent, {}) + } + + private _cancelTimeout() { + clearTimeout(this.timeoutTimer) + this.timeoutTimer = undefined + } + + private _matchReceive({ status, response }: { status: string; response: Function }) { + this.recHooks.filter((h) => h.status === status).forEach((h) => h.callback(response)) + } + + private _hasReceived(status: string) { + return this.receivedResp && this.receivedResp.status === status + } +} diff --git a/backend/node_modules/@supabase/realtime-js/src/lib/serializer.ts b/backend/node_modules/@supabase/realtime-js/src/lib/serializer.ts new file mode 100644 index 0000000..668ade2 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/src/lib/serializer.ts @@ -0,0 +1,203 @@ +// This file draws heavily from https://github.com/phoenixframework/phoenix/commit/cf098e9cf7a44ee6479d31d911a97d3c7430c6fe +// License: https://github.com/phoenixframework/phoenix/blob/master/LICENSE.md +export type Msg = { + join_ref?: string | null + ref?: string | null + topic: string + event: string + payload: T +} + +export default class Serializer { + HEADER_LENGTH = 1 + USER_BROADCAST_PUSH_META_LENGTH = 6 + KINDS = { userBroadcastPush: 3, userBroadcast: 4 } + BINARY_ENCODING = 0 + JSON_ENCODING = 1 + BROADCAST_EVENT = 'broadcast' + + allowedMetadataKeys: string[] = [] + + constructor(allowedMetadataKeys?: string[] | null) { + this.allowedMetadataKeys = allowedMetadataKeys ?? [] + } + + encode(msg: Msg<{ [key: string]: any }>, callback: (result: ArrayBuffer | string) => any) { + if ( + msg.event === this.BROADCAST_EVENT && + !(msg.payload instanceof ArrayBuffer) && + typeof msg.payload.event === 'string' + ) { + return callback( + this._binaryEncodeUserBroadcastPush(msg as Msg<{ event: string } & { [key: string]: any }>) + ) + } + + let payload = [msg.join_ref, msg.ref, msg.topic, msg.event, msg.payload] + return callback(JSON.stringify(payload)) + } + + private _binaryEncodeUserBroadcastPush(message: Msg<{ event: string } & { [key: string]: any }>) { + if (this._isArrayBuffer(message.payload?.payload)) { + return this._encodeBinaryUserBroadcastPush(message) + } else { + return this._encodeJsonUserBroadcastPush(message) + } + } + + private _encodeBinaryUserBroadcastPush(message: Msg<{ event: string } & { [key: string]: any }>) { + const userPayload = message.payload?.payload ?? new ArrayBuffer(0) + return this._encodeUserBroadcastPush(message, this.BINARY_ENCODING, userPayload) + } + + private _encodeJsonUserBroadcastPush(message: Msg<{ event: string } & { [key: string]: any }>) { + const userPayload = message.payload?.payload ?? {} + const encoder = new TextEncoder() + const encodedUserPayload = encoder.encode(JSON.stringify(userPayload)).buffer + return this._encodeUserBroadcastPush(message, this.JSON_ENCODING, encodedUserPayload) + } + + private _encodeUserBroadcastPush( + message: Msg<{ event: string } & { [key: string]: any }>, + encodingType: number, + encodedPayload: ArrayBuffer + ) { + const topic = message.topic + const ref = message.ref ?? '' + const joinRef = message.join_ref ?? '' + const userEvent = message.payload.event + + // Filter metadata based on allowed keys + const rest = this.allowedMetadataKeys + ? this._pick(message.payload, this.allowedMetadataKeys) + : {} + + const metadata = Object.keys(rest).length === 0 ? '' : JSON.stringify(rest) + + // Validate lengths don't exceed uint8 max value (255) + if (joinRef.length > 255) { + throw new Error(`joinRef length ${joinRef.length} exceeds maximum of 255`) + } + if (ref.length > 255) { + throw new Error(`ref length ${ref.length} exceeds maximum of 255`) + } + if (topic.length > 255) { + throw new Error(`topic length ${topic.length} exceeds maximum of 255`) + } + if (userEvent.length > 255) { + throw new Error(`userEvent length ${userEvent.length} exceeds maximum of 255`) + } + if (metadata.length > 255) { + throw new Error(`metadata length ${metadata.length} exceeds maximum of 255`) + } + + const metaLength = + this.USER_BROADCAST_PUSH_META_LENGTH + + joinRef.length + + ref.length + + topic.length + + userEvent.length + + metadata.length + + const header = new ArrayBuffer(this.HEADER_LENGTH + metaLength) + let view = new DataView(header) + let offset = 0 + + view.setUint8(offset++, this.KINDS.userBroadcastPush) // kind + view.setUint8(offset++, joinRef.length) + view.setUint8(offset++, ref.length) + view.setUint8(offset++, topic.length) + view.setUint8(offset++, userEvent.length) + view.setUint8(offset++, metadata.length) + view.setUint8(offset++, encodingType) + Array.from(joinRef, (char) => view.setUint8(offset++, char.charCodeAt(0))) + Array.from(ref, (char) => view.setUint8(offset++, char.charCodeAt(0))) + Array.from(topic, (char) => view.setUint8(offset++, char.charCodeAt(0))) + Array.from(userEvent, (char) => view.setUint8(offset++, char.charCodeAt(0))) + Array.from(metadata, (char) => view.setUint8(offset++, char.charCodeAt(0))) + + var combined = new Uint8Array(header.byteLength + encodedPayload.byteLength) + combined.set(new Uint8Array(header), 0) + combined.set(new Uint8Array(encodedPayload), header.byteLength) + + return combined.buffer + } + + decode(rawPayload: ArrayBuffer | string, callback: Function) { + if (this._isArrayBuffer(rawPayload)) { + let result = this._binaryDecode(rawPayload as ArrayBuffer) + return callback(result) + } + + if (typeof rawPayload === 'string') { + const jsonPayload = JSON.parse(rawPayload) + const [join_ref, ref, topic, event, payload] = jsonPayload + return callback({ join_ref, ref, topic, event, payload }) + } + + return callback({}) + } + + private _binaryDecode(buffer: ArrayBuffer) { + const view = new DataView(buffer) + const kind = view.getUint8(0) + const decoder = new TextDecoder() + switch (kind) { + case this.KINDS.userBroadcast: + return this._decodeUserBroadcast(buffer, view, decoder) + } + } + + private _decodeUserBroadcast( + buffer: ArrayBuffer, + view: DataView, + decoder: TextDecoder + ): { + join_ref: null + ref: null + topic: string + event: string + payload: { [key: string]: any } + } { + const topicSize = view.getUint8(1) + const userEventSize = view.getUint8(2) + const metadataSize = view.getUint8(3) + const payloadEncoding = view.getUint8(4) + + let offset = this.HEADER_LENGTH + 4 + const topic = decoder.decode(buffer.slice(offset, offset + topicSize)) + offset = offset + topicSize + const userEvent = decoder.decode(buffer.slice(offset, offset + userEventSize)) + offset = offset + userEventSize + const metadata = decoder.decode(buffer.slice(offset, offset + metadataSize)) + offset = offset + metadataSize + + const payload = buffer.slice(offset, buffer.byteLength) + const parsedPayload = + payloadEncoding === this.JSON_ENCODING ? JSON.parse(decoder.decode(payload)) : payload + + const data: { [key: string]: any } = { + type: this.BROADCAST_EVENT, + event: userEvent, + payload: parsedPayload, + } + + // Metadata is optional and always JSON encoded + if (metadataSize > 0) { + data['meta'] = JSON.parse(metadata) + } + + return { join_ref: null, ref: null, topic: topic, event: this.BROADCAST_EVENT, payload: data } + } + + private _isArrayBuffer(buffer: any): boolean { + return buffer instanceof ArrayBuffer || buffer?.constructor?.name === 'ArrayBuffer' + } + + private _pick(obj: Record | null | undefined, keys: string[]): Record { + if (!obj || typeof obj !== 'object') { + return {} + } + return Object.fromEntries(Object.entries(obj).filter(([key]) => keys.includes(key))) + } +} diff --git a/backend/node_modules/@supabase/realtime-js/src/lib/timer.ts b/backend/node_modules/@supabase/realtime-js/src/lib/timer.ts new file mode 100644 index 0000000..5c4ed14 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/src/lib/timer.ts @@ -0,0 +1,43 @@ +/** + * Creates a timer that accepts a `timerCalc` function to perform calculated timeout retries, such as exponential backoff. + * + * @example + * let reconnectTimer = new Timer(() => this.connect(), function(tries){ + * return [1000, 5000, 10000][tries - 1] || 10000 + * }) + * reconnectTimer.scheduleTimeout() // fires after 1000 + * reconnectTimer.scheduleTimeout() // fires after 5000 + * reconnectTimer.reset() + * reconnectTimer.scheduleTimeout() // fires after 1000 + */ +export default class Timer { + timer: number | undefined = undefined + tries: number = 0 + + constructor( + public callback: Function, + public timerCalc: Function + ) { + this.callback = callback + this.timerCalc = timerCalc + } + + reset() { + this.tries = 0 + clearTimeout(this.timer) + this.timer = undefined + } + + // Cancels any previous scheduleTimeout and schedules callback + scheduleTimeout() { + clearTimeout(this.timer) + + this.timer = setTimeout( + () => { + this.tries = this.tries + 1 + this.callback() + }, + this.timerCalc(this.tries + 1) + ) + } +} diff --git a/backend/node_modules/@supabase/realtime-js/src/lib/transformers.ts b/backend/node_modules/@supabase/realtime-js/src/lib/transformers.ts new file mode 100644 index 0000000..c034a0b --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/src/lib/transformers.ts @@ -0,0 +1,271 @@ +/** + * Helpers to convert the change Payload into native JS types. + */ + +// Adapted from epgsql (src/epgsql_binary.erl), this module licensed under +// 3-clause BSD found here: https://raw.githubusercontent.com/epgsql/epgsql/devel/LICENSE + +export enum PostgresTypes { + abstime = 'abstime', + bool = 'bool', + date = 'date', + daterange = 'daterange', + float4 = 'float4', + float8 = 'float8', + int2 = 'int2', + int4 = 'int4', + int4range = 'int4range', + int8 = 'int8', + int8range = 'int8range', + json = 'json', + jsonb = 'jsonb', + money = 'money', + numeric = 'numeric', + oid = 'oid', + reltime = 'reltime', + text = 'text', + time = 'time', + timestamp = 'timestamp', + timestamptz = 'timestamptz', + timetz = 'timetz', + tsrange = 'tsrange', + tstzrange = 'tstzrange', +} + +type Columns = { + name: string // the column name. eg: "user_id" + type: string // the column type. eg: "uuid" + flags?: string[] // any special flags for the column. eg: ["key"] + type_modifier?: number // the type modifier. eg: 4294967295 +}[] + +type BaseValue = null | string | number | boolean +type RecordValue = BaseValue | BaseValue[] + +type Record = { + [key: string]: RecordValue +} + +/** + * Takes an array of columns and an object of string values then converts each string value + * to its mapped type. + * + * @param {{name: String, type: String}[]} columns + * @param {Object} record + * @param {Object} options The map of various options that can be applied to the mapper + * @param {Array} options.skipTypes The array of types that should not be converted + * + * @example convertChangeData([{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age:'33'}, {}) + * //=>{ first_name: 'Paul', age: 33 } + */ +export const convertChangeData = ( + columns: Columns, + record: Record | null, + options: { skipTypes?: string[] } = {} +): Record => { + const skipTypes = options.skipTypes ?? [] + + if (!record) { + return {} + } + + return Object.keys(record).reduce((acc, rec_key) => { + acc[rec_key] = convertColumn(rec_key, columns, record, skipTypes) + return acc + }, {} as Record) +} + +/** + * Converts the value of an individual column. + * + * @param {String} columnName The column that you want to convert + * @param {{name: String, type: String}[]} columns All of the columns + * @param {Object} record The map of string values + * @param {Array} skipTypes An array of types that should not be converted + * @return {object} Useless information + * + * @example convertColumn('age', [{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age: '33'}, []) + * //=> 33 + * @example convertColumn('age', [{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age: '33'}, ['int4']) + * //=> "33" + */ +export const convertColumn = ( + columnName: string, + columns: Columns, + record: Record, + skipTypes: string[] +): RecordValue => { + const column = columns.find((x) => x.name === columnName) + const colType = column?.type + const value = record[columnName] + + if (colType && !skipTypes.includes(colType)) { + return convertCell(colType, value) + } + + return noop(value) +} + +/** + * If the value of the cell is `null`, returns null. + * Otherwise converts the string value to the correct type. + * @param {String} type A postgres column type + * @param {String} value The cell value + * + * @example convertCell('bool', 't') + * //=> true + * @example convertCell('int8', '10') + * //=> 10 + * @example convertCell('_int4', '{1,2,3,4}') + * //=> [1,2,3,4] + */ +export const convertCell = (type: string, value: RecordValue): RecordValue => { + // if data type is an array + if (type.charAt(0) === '_') { + const dataType = type.slice(1, type.length) + return toArray(value, dataType) + } + + // If not null, convert to correct type. + switch (type) { + case PostgresTypes.bool: + return toBoolean(value) + case PostgresTypes.float4: + case PostgresTypes.float8: + case PostgresTypes.int2: + case PostgresTypes.int4: + case PostgresTypes.int8: + case PostgresTypes.numeric: + case PostgresTypes.oid: + return toNumber(value) + case PostgresTypes.json: + case PostgresTypes.jsonb: + return toJson(value) + case PostgresTypes.timestamp: + return toTimestampString(value) // Format to be consistent with PostgREST + case PostgresTypes.abstime: // To allow users to cast it based on Timezone + case PostgresTypes.date: // To allow users to cast it based on Timezone + case PostgresTypes.daterange: + case PostgresTypes.int4range: + case PostgresTypes.int8range: + case PostgresTypes.money: + case PostgresTypes.reltime: // To allow users to cast it based on Timezone + case PostgresTypes.text: + case PostgresTypes.time: // To allow users to cast it based on Timezone + case PostgresTypes.timestamptz: // To allow users to cast it based on Timezone + case PostgresTypes.timetz: // To allow users to cast it based on Timezone + case PostgresTypes.tsrange: + case PostgresTypes.tstzrange: + return noop(value) + default: + // Return the value for remaining types + return noop(value) + } +} + +const noop = (value: RecordValue): RecordValue => { + return value +} +export const toBoolean = (value: RecordValue): RecordValue => { + switch (value) { + case 't': + return true + case 'f': + return false + default: + return value + } +} +export const toNumber = (value: RecordValue): RecordValue => { + if (typeof value === 'string') { + const parsedValue = parseFloat(value) + if (!Number.isNaN(parsedValue)) { + return parsedValue + } + } + return value +} +export const toJson = (value: RecordValue): RecordValue => { + if (typeof value === 'string') { + try { + return JSON.parse(value) + } catch (error) { + console.log(`JSON parse error: ${error}`) + return value + } + } + return value +} + +/** + * Converts a Postgres Array into a native JS array + * + * @example toArray('{}', 'int4') + * //=> [] + * @example toArray('{"[2021-01-01,2021-12-31)","(2021-01-01,2021-12-32]"}', 'daterange') + * //=> ['[2021-01-01,2021-12-31)', '(2021-01-01,2021-12-32]'] + * @example toArray([1,2,3,4], 'int4') + * //=> [1,2,3,4] + */ +export const toArray = (value: RecordValue, type: string): RecordValue => { + if (typeof value !== 'string') { + return value + } + + const lastIdx = value.length - 1 + const closeBrace = value[lastIdx] + const openBrace = value[0] + + // Confirm value is a Postgres array by checking curly brackets + if (openBrace === '{' && closeBrace === '}') { + let arr + const valTrim = value.slice(1, lastIdx) + + // TODO: find a better solution to separate Postgres array data + try { + arr = JSON.parse('[' + valTrim + ']') + } catch (_) { + // WARNING: splitting on comma does not cover all edge cases + arr = valTrim ? valTrim.split(',') : [] + } + + return arr.map((val: BaseValue) => convertCell(type, val)) + } + + return value +} + +/** + * Fixes timestamp to be ISO-8601. Swaps the space between the date and time for a 'T' + * See https://github.com/supabase/supabase/issues/18 + * + * @example toTimestampString('2019-09-10 00:00:00') + * //=> '2019-09-10T00:00:00' + */ +export const toTimestampString = (value: RecordValue): RecordValue => { + if (typeof value === 'string') { + return value.replace(' ', 'T') + } + + return value +} + +export const httpEndpointURL = (socketUrl: string): string => { + const wsUrl = new URL(socketUrl) + + wsUrl.protocol = wsUrl.protocol.replace(/^ws/i, 'http') + + wsUrl.pathname = wsUrl.pathname + .replace(/\/+$/, '') // remove all trailing slashes + .replace(/\/socket\/websocket$/i, '') // remove the socket/websocket path + .replace(/\/socket$/i, '') // remove the socket path + .replace(/\/websocket$/i, '') // remove the websocket path + + if (wsUrl.pathname === '' || wsUrl.pathname === '/') { + wsUrl.pathname = '/api/broadcast' + } else { + wsUrl.pathname = wsUrl.pathname + '/api/broadcast' + } + + return wsUrl.href +} diff --git a/backend/node_modules/@supabase/realtime-js/src/lib/version.ts b/backend/node_modules/@supabase/realtime-js/src/lib/version.ts new file mode 100644 index 0000000..57a6913 --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/src/lib/version.ts @@ -0,0 +1,7 @@ +// Generated automatically during releases by scripts/update-version-files.ts +// This file provides runtime access to the package version for: +// - HTTP request headers (e.g., X-Client-Info header for API requests) +// - Debugging and support (identifying which version is running) +// - Telemetry and logging (version reporting in errors/analytics) +// - Ensuring build artifacts match the published package version +export const version = '2.87.1' diff --git a/backend/node_modules/@supabase/realtime-js/src/lib/websocket-factory.ts b/backend/node_modules/@supabase/realtime-js/src/lib/websocket-factory.ts new file mode 100644 index 0000000..2289c5b --- /dev/null +++ b/backend/node_modules/@supabase/realtime-js/src/lib/websocket-factory.ts @@ -0,0 +1,191 @@ +export interface WebSocketLike { + readonly CONNECTING: number + readonly OPEN: number + readonly CLOSING: number + readonly CLOSED: number + readonly readyState: number + readonly url: string + readonly protocol: string + + /** + * Closes the socket, optionally providing a close code and reason. + */ + close(code?: number, reason?: string): void + /** + * Sends data through the socket using the underlying implementation. + */ + send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void + + onopen: ((this: any, ev: Event) => any) | null + onmessage: ((this: any, ev: MessageEvent) => any) | null + onclose: ((this: any, ev: CloseEvent) => any) | null + onerror: ((this: any, ev: Event) => any) | null + + /** + * Registers an event listener on the socket (compatible with browser WebSocket API). + */ + addEventListener(type: string, listener: EventListener): void + /** + * Removes a previously registered event listener. + */ + removeEventListener(type: string, listener: EventListener): void + + // Add additional properties that may exist on WebSocket implementations + binaryType?: string + bufferedAmount?: number + extensions?: string + dispatchEvent?: (event: Event) => boolean +} + +export interface WebSocketEnvironment { + type: 'native' | 'ws' | 'cloudflare' | 'unsupported' + constructor?: any + error?: string + workaround?: string +} + +/** + * Utilities for creating WebSocket instances across runtimes. + */ +export class WebSocketFactory { + /** + * Static-only utility – prevent instantiation. + */ + private constructor() {} + private static detectEnvironment(): WebSocketEnvironment { + if (typeof WebSocket !== 'undefined') { + return { type: 'native', constructor: WebSocket } + } + + if (typeof globalThis !== 'undefined' && typeof (globalThis as any).WebSocket !== 'undefined') { + return { type: 'native', constructor: (globalThis as any).WebSocket } + } + + if (typeof global !== 'undefined' && typeof (global as any).WebSocket !== 'undefined') { + return { type: 'native', constructor: (global as any).WebSocket } + } + + if ( + typeof globalThis !== 'undefined' && + typeof (globalThis as any).WebSocketPair !== 'undefined' && + typeof globalThis.WebSocket === 'undefined' + ) { + return { + type: 'cloudflare', + error: + 'Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.', + workaround: + 'Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime.', + } + } + + if ( + (typeof globalThis !== 'undefined' && (globalThis as any).EdgeRuntime) || + (typeof navigator !== 'undefined' && navigator.userAgent?.includes('Vercel-Edge')) + ) { + return { + type: 'unsupported', + error: + 'Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.', + workaround: + 'Use serverless functions or a different deployment target for WebSocket functionality.', + } + } + + if (typeof process !== 'undefined') { + // Use dynamic property access to avoid Next.js Edge Runtime static analysis warnings + const processVersions = (process as any)['versions'] + if (processVersions && processVersions['node']) { + // Remove 'v' prefix if present and parse the major version + const versionString = processVersions['node'] + const nodeVersion = parseInt(versionString.replace(/^v/, '').split('.')[0]) + + // Node.js 22+ should have native WebSocket + if (nodeVersion >= 22) { + // Check if native WebSocket is available (should be in Node.js 22+) + if (typeof globalThis.WebSocket !== 'undefined') { + return { type: 'native', constructor: globalThis.WebSocket } + } + // If not available, user needs to provide it + return { + type: 'unsupported', + error: `Node.js ${nodeVersion} detected but native WebSocket not found.`, + workaround: 'Provide a WebSocket implementation via the transport option.', + } + } + + // Node.js < 22 doesn't have native WebSocket + return { + type: 'unsupported', + error: `Node.js ${nodeVersion} detected without native WebSocket support.`, + workaround: + 'For Node.js < 22, install "ws" package and provide it via the transport option:\n' + + 'import ws from "ws"\n' + + 'new RealtimeClient(url, { transport: ws })', + } + } + } + + return { + type: 'unsupported', + error: 'Unknown JavaScript runtime without WebSocket support.', + workaround: + "Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation.", + } + } + + /** + * Returns the best available WebSocket constructor for the current runtime. + * + * @example + * ```ts + * const WS = WebSocketFactory.getWebSocketConstructor() + * const socket = new WS('wss://realtime.supabase.co/socket') + * ``` + */ + public static getWebSocketConstructor(): typeof WebSocket { + const env = this.detectEnvironment() + if (env.constructor) { + return env.constructor + } + let errorMessage = env.error || 'WebSocket not supported in this environment.' + if (env.workaround) { + errorMessage += `\n\nSuggested solution: ${env.workaround}` + } + throw new Error(errorMessage) + } + + /** + * Creates a WebSocket using the detected constructor. + * + * @example + * ```ts + * const socket = WebSocketFactory.createWebSocket('wss://realtime.supabase.co/socket') + * ``` + */ + public static createWebSocket(url: string | URL, protocols?: string | string[]): WebSocketLike { + const WS = this.getWebSocketConstructor() + return new WS(url, protocols) + } + + /** + * Detects whether the runtime can establish WebSocket connections. + * + * @example + * ```ts + * if (!WebSocketFactory.isWebSocketSupported()) { + * console.warn('Falling back to long polling') + * } + * ``` + */ + public static isWebSocketSupported(): boolean { + try { + const env = this.detectEnvironment() + return env.type === 'native' || env.type === 'ws' + } catch { + return false + } + } +} + +export default WebSocketFactory diff --git a/backend/node_modules/@supabase/storage-js/README.md b/backend/node_modules/@supabase/storage-js/README.md new file mode 100644 index 0000000..a76629d --- /dev/null +++ b/backend/node_modules/@supabase/storage-js/README.md @@ -0,0 +1,1399 @@ +
+

+ + + + + Supabase Logo + + + +

Supabase Storage JS SDK

+ +

JavaScript SDK to interact with Supabase Storage, including file storage and vector embeddings.

+ +

+ Guides + · + Reference Docs + · + TypeDoc +

+

+ +
+ +[![Build](https://github.com/supabase/supabase-js/workflows/CI/badge.svg)](https://github.com/supabase/supabase-js/actions?query=branch%3Amaster) +[![Package](https://img.shields.io/npm/v/@supabase/storage-js)](https://www.npmjs.com/package/@supabase/storage-js) +[![License: MIT](https://img.shields.io/npm/l/@supabase/supabase-js)](#license) +[![pkg.pr.new](https://pkg.pr.new/badge/supabase/storage-js)](https://pkg.pr.new/~/supabase/storage-js) + +
+ +## Requirements + +- **Node.js 20 or later** (Node.js 18 support dropped as of October 31, 2025) +- For browser support, all modern browsers are supported + +> ⚠️ **Node.js 18 Deprecation Notice** +> +> Node.js 18 reached end-of-life on April 30, 2025. As announced in [our deprecation notice](https://github.com/orgs/supabase/discussions/37217), support for Node.js 18 was dropped on October 31, 2025. + +## Features + +- **File Storage**: Upload, download, list, move, and delete files +- **Access Control**: Public and private buckets with fine-grained permissions +- **Signed URLs**: Generate time-limited URLs for secure file access +- **Image Transformations**: On-the-fly image resizing and optimization +- **Vector Embeddings**: Store and query high-dimensional embeddings with similarity search +- **Analytics Buckets**: Iceberg table-based buckets optimized for analytical queries and data processing + +## Quick Start Guide + +### Installing the module + +```bash +npm install @supabase/storage-js +``` + +### Connecting to the storage backend + +There are two ways to use the Storage SDK: + +#### Option 1: Via Supabase Client (Recommended) + +If you're already using `@supabase/supabase-js`, access storage through the client: + +```js +import { createClient } from '@supabase/supabase-js' + +// Use publishable/anon key for frontend applications +const supabase = createClient('https://.supabase.co', '') + +// Access storage +const storage = supabase.storage + +// Access different bucket types +const regularBucket = storage.from('my-bucket') +const vectorBucket = storage.vectors.from('embeddings-bucket') +const analyticsBucket = storage.analytics // Analytics API +``` + +#### Option 2: Standalone StorageClient + +For backend applications or when you need to bypass Row Level Security: + +```js +import { StorageClient } from '@supabase/storage-js' + +const STORAGE_URL = 'https://.supabase.co/storage/v1' +const SERVICE_KEY = '' // Use secret key for backend operations + +const storageClient = new StorageClient(STORAGE_URL, { + apikey: SERVICE_KEY, + Authorization: `Bearer ${SERVICE_KEY}`, +}) + +// Access different bucket types +const regularBucket = storageClient.from('my-bucket') +const vectorBucket = storageClient.vectors.from('embeddings-bucket') +const analyticsBucket = storageClient.analytics // Analytics API +``` + +> **When to use each approach:** +> +> - Use `supabase.storage` when working with other Supabase features (auth, database, etc.) in frontend applications +> - Use `new StorageClient()` for backend applications, Edge Functions, or when you need to bypass RLS policies + +> **Note:** Refer to the [Storage Access Control guide](https://supabase.com/docs/guides/storage/access-control) for detailed information on creating RLS policies. + +### Understanding Bucket Types + +Supabase Storage supports three types of buckets, each optimized for different use cases: + +#### 1. Regular Storage Buckets (File Storage) + +Standard buckets for storing files, images, videos, and other assets. + +```js +// Create regular storage bucket +const { data, error } = await storageClient.createBucket('my-files', { + public: false, +}) + +// Upload files +await storageClient.from('my-files').upload('avatar.png', file) +``` + +**Use cases:** User uploads, media assets, documents, backups + +#### 2. Vector Buckets (Embeddings Storage) + +Specialized buckets for storing and querying high-dimensional vector embeddings. + +```js +// Create vector bucket +await storageClient.vectors.createBucket('embeddings-prod') + +// Create index and insert vectors +const bucket = storageClient.vectors.from('embeddings-prod') +await bucket.createIndex({ + indexName: 'documents', + dimension: 1536, + distanceMetric: 'cosine', +}) +``` + +**Use cases:** Semantic search, AI-powered recommendations, similarity matching + +**[See full Vector Embeddings documentation below](#vector-embeddings)** + +#### 3. Analytics Buckets + +Specialized buckets using Apache Iceberg table format, optimized for analytical queries and large-scale data processing. + +```js +// Create analytics bucket +await storageClient.analytics.createBucket('analytics-data') + +// List analytics buckets +const { data, error } = await storageClient.analytics.listBuckets() + +// Delete analytics bucket +await storageClient.analytics.deleteBucket('analytics-data') +``` + +**Use cases:** Time-series data, analytical queries, data lakes, large-scale data processing, business intelligence + +**[See full Analytics Buckets documentation below](#analytics-buckets)** + +--- + +### Handling resources + +#### Handling Storage Buckets + +- Create a new Storage bucket: + + ```js + const { data, error } = await storageClient.createBucket( + 'test_bucket', // Bucket name (must be unique) + { public: false } // Bucket options + ) + ``` + +- Retrieve the details of an existing Storage bucket: + + ```js + const { data, error } = await storageClient.getBucket('test_bucket') + ``` + +- Update a new Storage bucket: + + ```js + const { data, error } = await storageClient.updateBucket( + 'test_bucket', // Bucket name + { public: false } // Bucket options + ) + ``` + +- Remove all objects inside a single bucket: + + ```js + const { data, error } = await storageClient.emptyBucket('test_bucket') + ``` + +- Delete an existing bucket (a bucket can't be deleted with existing objects inside it): + + ```js + const { data, error } = await storageClient.deleteBucket('test_bucket') + ``` + +- Retrieve the details of all Storage buckets within an existing project: + + ```js + // List all buckets + const { data, error } = await storageClient.listBuckets() + + // List buckets with options (pagination, sorting, search) + const { data, error } = await storageClient.listBuckets({ + limit: 10, + offset: 0, + sortColumn: 'created_at', + sortOrder: 'desc', + search: 'prod', + }) + ``` + +#### Handling Files + +- Upload a file to an existing bucket: + + ```js + const fileBody = ... // load your file here + + const { data, error } = await storageClient.from('bucket').upload('path/to/file', fileBody) + ``` + + > Note: + > The path in `data.Key` is prefixed by the bucket ID and is not the value which should be passed to the `download` method in order to fetch the file. + > To fetch the file via the `download` method, use `data.path` and `data.bucketId` as follows: + > + > ```javascript + > const { data, error } = await storageClient.from('bucket').upload('/folder/file.txt', fileBody) + > // check for errors + > const { data2, error2 } = await storageClient.from(data.bucketId).download(data.path) + > ``` + + > Note: The `upload` method also accepts a map of optional parameters. For a complete list see the [Supabase API reference](https://supabase.com/docs/reference/javascript/storage-from-upload). + +- Download a file from an exisiting bucket: + + ```js + const { data, error } = await storageClient.from('bucket').download('path/to/file') + ``` + +- List all the files within a bucket: + + ```js + const { data, error } = await storageClient.from('bucket').list('folder') + ``` + + > Note: The `list` method also accepts a map of optional parameters. For a complete list see the [Supabase API reference](https://supabase.com/docs/reference/javascript/storage-from-list). + +- Replace an existing file at the specified path with a new one: + + ```js + const fileBody = ... // load your file here + + const { data, error } = await storageClient + .from('bucket') + .update('path/to/file', fileBody) + ``` + + > Note: The `upload` method also accepts a map of optional parameters. For a complete list see the [Supabase API reference](https://supabase.com/docs/reference/javascript/storage-from-upload). + +- Move an existing file: + + ```js + const { data, error } = await storageClient + .from('bucket') + .move('old/path/to/file', 'new/path/to/file') + ``` + +- Delete files within the same bucket: + + ```js + const { data, error } = await storageClient.from('bucket').remove(['path/to/file']) + ``` + +- Create signed URL to download file without requiring permissions: + + ```js + const expireIn = 60 + + const { data, error } = await storageClient + .from('bucket') + .createSignedUrl('path/to/file', expireIn) + ``` + +- Retrieve URLs for assets in public buckets: + + ```js + const { data, error } = await storageClient.from('public-bucket').getPublicUrl('path/to/file') + ``` + +## Analytics Buckets + +Supabase Storage provides specialized analytics buckets using Apache Iceberg table format, optimized for analytical workloads and large-scale data processing. These buckets are designed for data lake architectures, time-series data, and business intelligence applications. + +### What are Analytics Buckets? + +Analytics buckets use the Apache Iceberg open table format, providing: + +- **ACID transactions** for data consistency +- **Schema evolution** without data rewrites +- **Time travel** to query historical data +- **Efficient metadata management** for large datasets +- **Optimized for analytical queries** rather than individual file operations + +### When to Use Analytics Buckets + +**Use analytics buckets for:** + +- Time-series data (logs, metrics, events) +- Data lake architectures +- Business intelligence and reporting +- Large-scale batch processing +- Analytical workloads requiring ACID guarantees + +**Use regular storage buckets for:** + +- User file uploads (images, documents, videos) +- Individual file management +- Content delivery +- Simple object storage needs + +### Quick Start + +You can access analytics functionality through the `analytics` property on your storage client: + +#### Via Supabase Client + +```typescript +import { createClient } from '@supabase/supabase-js' + +const supabase = createClient('https://your-project.supabase.co', 'your-publishable-key') + +// Access analytics operations +const analytics = supabase.storage.analytics + +// Create an analytics bucket +const { data, error } = await analytics.createBucket('analytics-data') +if (error) { + console.error('Failed to create analytics bucket:', error.message) +} else { + console.log('Created bucket:', data.name) +} +``` + +#### Via StorageClient + +```typescript +import { StorageClient } from '@supabase/storage-js' + +const storageClient = new StorageClient('https://your-project.supabase.co/storage/v1', { + apikey: 'YOUR_API_KEY', + Authorization: 'Bearer YOUR_TOKEN', +}) + +// Access analytics operations +const analytics = storageClient.analytics + +// Create an analytics bucket +await analytics.createBucket('analytics-data') +``` + +### API Reference + +#### Create Analytics Bucket + +Creates a new analytics bucket using Iceberg table format: + +```typescript +const { data, error } = await analytics.createBucket('my-analytics-bucket') + +if (error) { + console.error('Error:', error.message) +} else { + console.log('Created bucket:', data) +} +``` + +**Returns:** + +```typescript +{ + data: { + id: string + type: 'ANALYTICS' + format: string + created_at: string + updated_at: string + } | null + error: StorageError | null +} +``` + +#### List Analytics Buckets + +Retrieves all analytics buckets in your project with optional filtering and pagination: + +```typescript +const { data, error } = await analytics.listBuckets({ + limit: 10, + offset: 0, + sortColumn: 'created_at', + sortOrder: 'desc', + search: 'prod', +}) + +if (data) { + console.log(`Found ${data.length} analytics buckets`) + data.forEach((bucket) => { + console.log(`- ${bucket.id} (created: ${bucket.created_at})`) + }) +} +``` + +**Parameters:** + +- `limit?: number` - Maximum number of buckets to return +- `offset?: number` - Number of buckets to skip (for pagination) +- `sortColumn?: 'id' | 'name' | 'created_at' | 'updated_at'` - Column to sort by +- `sortOrder?: 'asc' | 'desc'` - Sort direction +- `search?: string` - Search term to filter bucket names + +**Returns:** + +```typescript +{ + data: AnalyticBucket[] | null + error: StorageError | null +} +``` + +**Example with Pagination:** + +```typescript +// Fetch first page +const firstPage = await analytics.listBuckets({ + limit: 100, + offset: 0, + sortColumn: 'created_at', + sortOrder: 'desc', +}) + +// Fetch second page +const secondPage = await analytics.listBuckets({ + limit: 100, + offset: 100, + sortColumn: 'created_at', + sortOrder: 'desc', +}) +``` + +#### Delete Analytics Bucket + +Deletes an analytics bucket. The bucket must be empty before deletion. + +```typescript +const { data, error } = await analytics.deleteBucket('old-analytics-bucket') + +if (error) { + console.error('Failed to delete:', error.message) +} else { + console.log('Bucket deleted:', data.message) +} +``` + +**Returns:** + +```typescript +{ + data: { message: string } | null + error: StorageError | null +} +``` + +> **Note:** A bucket cannot be deleted if it contains data. You must empty the bucket first. + +#### Get Iceberg Catalog for Advanced Operations + +For advanced operations like creating tables, namespaces, and querying Iceberg metadata, use the `from()` method to get a configured [iceberg-js](https://github.com/supabase/iceberg-js) client: + +```typescript +// Get an Iceberg REST Catalog client for your analytics bucket +const catalog = analytics.from('analytics-data') + +// Create a namespace +await catalog.createNamespace({ namespace: ['default'] }, { properties: { owner: 'data-team' } }) + +// Create a table with schema +await catalog.createTable( + { namespace: ['default'] }, + { + name: 'events', + schema: { + type: 'struct', + fields: [ + { id: 1, name: 'id', type: 'long', required: true }, + { id: 2, name: 'timestamp', type: 'timestamp', required: true }, + { id: 3, name: 'user_id', type: 'string', required: false }, + ], + 'schema-id': 0, + 'identifier-field-ids': [1], + }, + 'partition-spec': { + 'spec-id': 0, + fields: [], + }, + 'write-order': { + 'order-id': 0, + fields: [], + }, + properties: { + 'write.format.default': 'parquet', + }, + } +) + +// List tables in namespace +const tables = await catalog.listTables({ namespace: ['default'] }) +console.log(tables) // [{ namespace: ['default'], name: 'events' }] + +// Load table metadata +const table = await catalog.loadTable({ namespace: ['default'], name: 'events' }) + +// Update table properties +await catalog.updateTable( + { namespace: ['default'], name: 'events' }, + { properties: { 'read.split.target-size': '134217728' } } +) + +// Drop table +await catalog.dropTable({ namespace: ['default'], name: 'events' }) + +// Drop namespace +await catalog.dropNamespace({ namespace: ['default'] }) +``` + +**Returns:** `IcebergRestCatalog` instance from [iceberg-js](https://github.com/supabase/iceberg-js) + +> **Note:** The `from()` method returns an Iceberg REST Catalog client that provides full access to the Apache Iceberg REST API. For complete documentation of available operations, see the [iceberg-js documentation](https://supabase.github.io/iceberg-js/). + +### Error Handling + +Analytics buckets use the same error handling pattern as the rest of the Storage SDK: + +```typescript +const { data, error } = await analytics.createBucket('my-bucket') + +if (error) { + console.error('Error:', error.message) + console.error('Status:', error.status) + console.error('Status Code:', error.statusCode) + // Handle error appropriately +} +``` + +#### Throwing Errors + +You can configure the client to throw errors instead of returning them: + +```typescript +const analytics = storageClient.analytics +analytics.throwOnError() + +try { + const { data } = await analytics.createBucket('my-bucket') + // data is guaranteed to be present + console.log('Success:', data) +} catch (error) { + if (error instanceof StorageApiError) { + console.error('API Error:', error.statusCode, error.message) + } +} +``` + +### TypeScript Types + +The library exports TypeScript types for analytics buckets: + +```typescript +import type { AnalyticBucket, BucketType, StorageError } from '@supabase/storage-js' + +// AnalyticBucket type +interface AnalyticBucket { + id: string + type: 'ANALYTICS' + format: string + created_at: string + updated_at: string +} +``` + +### Common Patterns + +#### Checking if a Bucket Exists + +```typescript +async function bucketExists(bucketName: string): Promise { + const { data, error } = await analytics.listBuckets({ + search: bucketName, + }) + + if (error) { + console.error('Error checking bucket:', error.message) + return false + } + + return data?.some((bucket) => bucket.id === bucketName) ?? false +} +``` + +#### Creating Bucket with Error Handling + +```typescript +async function ensureAnalyticsBucket(bucketName: string) { + // Try to create the bucket + const { data, error } = await analytics.createBucket(bucketName) + + if (error) { + // Check if bucket already exists (conflict error) + if (error.statusCode === '409') { + console.log(`Bucket '${bucketName}' already exists`) + return { success: true, created: false } + } + + // Other error occurred + console.error('Failed to create bucket:', error.message) + return { success: false, error } + } + + console.log(`Created new bucket: '${bucketName}'`) + return { success: true, created: true, data } +} +``` + +#### Listing All Buckets with Pagination + +```typescript +async function getAllAnalyticsBuckets() { + const allBuckets: AnalyticBucket[] = [] + let offset = 0 + const limit = 100 + + while (true) { + const { data, error } = await analytics.listBuckets({ + limit, + offset, + sortColumn: 'created_at', + sortOrder: 'desc', + }) + + if (error) { + console.error('Error fetching buckets:', error.message) + break + } + + if (!data || data.length === 0) { + break + } + + allBuckets.push(...data) + + // If we got fewer results than the limit, we've reached the end + if (data.length < limit) { + break + } + + offset += limit + } + + return allBuckets +} +``` + +## Vector Embeddings + +Supabase Storage provides built-in support for storing and querying high-dimensional vector embeddings, powered by S3 Vectors. This enables semantic search, similarity matching, and AI-powered applications without needing a separate vector database. + +> **Note:** Vector embeddings functionality is available in `@supabase/storage-js` v2.76 and later. + +### Features + +- **Vector Buckets**: Organize vector indexes into logical containers +- **Vector Indexes**: Define schemas with configurable dimensions and distance metrics +- **Batch Operations**: Insert/update/delete up to 500 vectors per request +- **Similarity Search**: Query for nearest neighbors using cosine, euclidean, or dot product distance +- **Metadata Filtering**: Store and filter vectors by arbitrary JSON metadata +- **Pagination**: Efficiently scan large vector datasets +- **Parallel Scanning**: Distribute scans across multiple workers for high throughput +- **Cross-platform**: Works in Node.js, browsers, and edge runtimes + +### Quick Start + +You can access vector functionality in three ways, depending on your use case: + +#### Option 1: Via Supabase Client (Most Common) + +If you're using the full Supabase client: + +```typescript +import { createClient } from '@supabase/supabase-js' + +const supabase = createClient('https://your-project.supabase.co', 'your-publishable-key') + +// Access vector operations through storage +const vectors = supabase.storage.vectors + +// Create a vector bucket +await vectors.createBucket('embeddings-prod') + +// Create an index +const bucket = vectors.from('embeddings-prod') +await bucket.createIndex({ + indexName: 'documents-openai', + dataType: 'float32', + dimension: 1536, + distanceMetric: 'cosine', +}) + +// Insert vectors +const index = bucket.index('documents-openai') +await index.putVectors({ + vectors: [ + { + key: 'doc-1', + data: { float32: [0.1, 0.2, 0.3 /* ...1536 dimensions */] }, + metadata: { title: 'Introduction', category: 'docs' }, + }, + ], +}) + +// Query similar vectors +const { data, error } = await index.queryVectors({ + queryVector: { float32: [0.15, 0.25, 0.35 /* ...1536 dimensions */] }, + topK: 5, + returnDistance: true, + returnMetadata: true, +}) + +if (data) { + data.matches.forEach((match) => { + console.log(`${match.key}: distance=${match.distance}`) + console.log('Metadata:', match.metadata) + }) +} +``` + +#### Option 2: Via StorageClient + +If you're using the standalone `StorageClient` for storage operations, access vectors through the `vectors` property: + +```typescript +import { StorageClient } from '@supabase/storage-js' + +const storageClient = new StorageClient('https://your-project.supabase.co/storage/v1', { + apikey: 'YOUR_API_KEY', + Authorization: 'Bearer YOUR_TOKEN', +}) + +// Access vector operations +const vectors = storageClient.vectors + +// Use the same API as shown in Option 1 +await vectors.createBucket('embeddings-prod') +const bucket = vectors.from('embeddings-prod') +// ... rest of operations +``` + +#### Option 3: Standalone Vector Client + +For vector-only applications that don't need regular file storage operations: + +```typescript +import { StorageVectorsClient } from '@supabase/storage-js' + +// Initialize standalone vector client +const vectorClient = new StorageVectorsClient('https://your-project.supabase.co/storage/v1', { + headers: { Authorization: 'Bearer YOUR_TOKEN' }, +}) + +// Use the same API as shown in Option 1 +await vectorClient.createBucket('embeddings-prod') +const bucket = vectorClient.from('embeddings-prod') +// ... rest of operations +``` + +> **When to use each approach:** +> +> - **Option 1**: When using other Supabase features (auth, database, realtime) +> - **Option 2**: When working with both file storage and vectors +> - **Option 3**: For dedicated vector-only applications without file storage + +### API Reference + +#### Client Initialization + +```typescript +const vectorClient = new StorageVectorsClient(url, options?) +``` + +**Options:** + +- `headers?: Record` - Custom HTTP headers (e.g., Authorization) +- `fetch?: Fetch` - Custom fetch implementation + +#### Vector Buckets + +Vector buckets are top-level containers for organizing vector indexes. + +##### Create Bucket + +```typescript +const { data, error } = await vectorClient.createBucket('my-bucket') +``` + +##### Get Bucket + +```typescript +const { data, error } = await vectorClient.getBucket('my-bucket') +console.log('Created at:', new Date(data.vectorBucket.creationTime! * 1000)) +``` + +##### List Buckets + +```typescript +const { data, error } = await vectorClient.listBuckets({ + prefix: 'prod-', + maxResults: 100, +}) + +// Pagination +if (data?.nextToken) { + const next = await vectorClient.listBuckets({ nextToken: data.nextToken }) +} +``` + +##### Delete Bucket + +```typescript +// Bucket must be empty (all indexes deleted first) +const { error } = await vectorClient.deleteBucket('my-bucket') +``` + +#### Vector Indexes + +Vector indexes define the schema for embeddings including dimension and distance metric. + +##### Create Index + +```typescript +const bucket = vectorClient.from('my-bucket') + +await bucket.createIndex({ + indexName: 'my-index', + dataType: 'float32', + dimension: 1536, + distanceMetric: 'cosine', // 'cosine' | 'euclidean' | 'dotproduct' + metadataConfiguration: { + nonFilterableMetadataKeys: ['raw_text', 'internal_id'], + }, +}) +``` + +**Distance Metrics:** + +- `cosine` - Cosine similarity (normalized dot product) +- `euclidean` - Euclidean distance (L2 norm) +- `dotproduct` - Dot product similarity + +##### Get Index + +```typescript +const { data, error } = await bucket.getIndex('my-index') +console.log('Dimension:', data?.index.dimension) +console.log('Distance metric:', data?.index.distanceMetric) +``` + +##### List Indexes + +```typescript +const { data, error } = await bucket.listIndexes({ + prefix: 'documents-', + maxResults: 100, +}) +``` + +##### Delete Index + +```typescript +// Deletes index and all its vectors +await bucket.deleteIndex('my-index') +``` + +#### Vector Operations + +##### Insert/Update Vectors (Upsert) + +```typescript +const index = vectorClient.from('my-bucket').index('my-index') + +await index.putVectors({ + vectors: [ + { + key: 'unique-id-1', + data: { + float32: [ + /* 1536 numbers */ + ], + }, + metadata: { + title: 'Document Title', + category: 'technical', + page: 1, + }, + }, + // ... up to 500 vectors per request + ], +}) +``` + +**Limitations:** + +- 1-500 vectors per request +- Vectors must match index dimension +- Keys must be unique within index + +##### Get Vectors by Key + +```typescript +const { data, error } = await index.getVectors({ + keys: ['doc-1', 'doc-2', 'doc-3'], + returnData: true, // Include embeddings + returnMetadata: true, // Include metadata +}) + +data?.vectors.forEach((v) => { + console.log(v.key, v.metadata) +}) +``` + +##### Query Similar Vectors (ANN Search) + +```typescript +const { data, error } = await index.queryVectors({ + queryVector: { + float32: [ + /* 1536 numbers */ + ], + }, + topK: 10, + filter: { + category: 'technical', + published: true, + }, + returnDistance: true, + returnMetadata: true, +}) + +// Results ordered by similarity +data?.matches.forEach((match) => { + console.log(`${match.key}: distance=${match.distance}`) +}) +``` + +**Filter Syntax:** +The `filter` parameter accepts arbitrary JSON for metadata filtering. Non-filterable keys (configured at index creation) cannot be used in filters but can still be returned. + +##### List/Scan Vectors + +```typescript +// Simple pagination +let nextToken: string | undefined +do { + const { data } = await index.listVectors({ + maxResults: 500, + nextToken, + returnMetadata: true, + }) + + console.log('Batch:', data?.vectors.length) + nextToken = data?.nextToken +} while (nextToken) + +// Parallel scanning (4 workers) +const workers = [0, 1, 2, 3].map(async (segmentIndex) => { + const { data } = await index.listVectors({ + segmentCount: 4, + segmentIndex, + returnMetadata: true, + }) + return data?.vectors || [] +}) + +const results = await Promise.all(workers) +const allVectors = results.flat() +``` + +**Limitations:** + +- `maxResults`: 1-1000 (default: 500) +- `segmentCount`: 1-16 +- Response may be limited by 1MB size + +##### Delete Vectors + +```typescript +await index.deleteVectors({ + keys: ['doc-1', 'doc-2', 'doc-3'], + // ... up to 500 keys per request +}) +``` + +### Error Handling + +The library uses a consistent error handling pattern: + +```typescript +const { data, error } = await vectorClient.createBucket('my-bucket') + +if (error) { + console.error('Error:', error.message) + console.error('Status:', error.status) + console.error('Code:', error.statusCode) +} +``` + +#### Error Codes + +| Code | HTTP | Description | +| ---------------------------- | ---- | ----------------------- | +| `InternalError` | 500 | Internal server error | +| `S3VectorConflictException` | 409 | Resource already exists | +| `S3VectorNotFoundException` | 404 | Resource not found | +| `S3VectorBucketNotEmpty` | 400 | Bucket contains indexes | +| `S3VectorMaxBucketsExceeded` | 400 | Bucket quota exceeded | +| `S3VectorMaxIndexesExceeded` | 400 | Index quota exceeded | + +#### Throwing Errors + +You can configure the client to throw errors instead: + +```typescript +const vectorClient = new StorageVectorsClient(url, options) +vectorClient.throwOnError() + +try { + const { data } = await vectorClient.createBucket('my-bucket') + // data is guaranteed to be present +} catch (error) { + if (error instanceof StorageVectorsApiError) { + console.error('API Error:', error.statusCode) + } +} +``` + +### Advanced Usage + +#### Scoped Clients + +Create scoped clients for cleaner code: + +```typescript +// Bucket-scoped operations +const bucket = vectorClient.from('embeddings-prod') +await bucket.createIndex({ + /* ... */ +}) +await bucket.listIndexes() + +// Index-scoped operations +const index = bucket.index('documents-openai') +await index.putVectors({ + /* ... */ +}) +await index.queryVectors({ + /* ... */ +}) +``` + +#### Custom Fetch + +Provide a custom fetch implementation: + +```typescript +import { StorageVectorsClient } from '@supabase/storage-js' + +const vectorClient = new StorageVectorsClient(url, { + fetch: customFetch, + headers: { + /* ... */ + }, +}) +``` + +#### Batch Processing + +Process large datasets in batches: + +```typescript +async function insertLargeDataset(vectors: VectorObject[]) { + const batchSize = 500 + + for (let i = 0; i < vectors.length; i += batchSize) { + const batch = vectors.slice(i, i + batchSize) + await index.putVectors({ vectors: batch }) + console.log(`Inserted ${i + batch.length}/${vectors.length}`) + } +} +``` + +#### Float32 Validation + +Ensure vectors are properly normalized to float32: + +```typescript +import { normalizeToFloat32 } from '@supabase/storage-js' + +const vector = normalizeToFloat32([0.1, 0.2, 0.3 /* ... */]) +``` + +### Type Definitions + +The library exports comprehensive TypeScript types: + +```typescript +import type { + VectorBucket, + VectorIndex, + VectorData, + VectorObject, + VectorMatch, + VectorMetadata, + DistanceMetric, + ApiResponse, + StorageVectorsError, +} from '@supabase/storage-js' +``` + +## Development + +This package is part of the [Supabase JavaScript monorepo](https://github.com/supabase/supabase-js). To work on this package: + +### Building + +#### Build Scripts Overview + +The storage-js package uses multiple build scripts to generate different module formats for various JavaScript environments: + +| Script | Description | Output | +| -------------- | --------------------------- | --------------------------------------------------------------- | +| `build` | **Complete build pipeline** | Runs all build steps in sequence | +| `build:main` | **CommonJS build** | `dist/main/` - Node.js compatible CommonJS modules | +| `build:module` | **ES Modules build** | `dist/module/` - Modern ES6 modules with TypeScript definitions | +| `build:umd` | **UMD build** | `dist/umd/` - Universal Module Definition for browsers/CDN | +| `clean` | **Clean build artifacts** | Removes `dist/` and `docs/v2/` directories | + +#### Running Builds + +##### Complete Build (Recommended) + +```bash +# From the monorepo root +npx nx build storage-js +``` + +This command executes the full build pipeline: + +1. **Cleans** - Removes any existing build artifacts +2. **Formats** - Ensures consistent code formatting +3. **Builds CommonJS** - For Node.js environments (`dist/main/`) +4. **Builds ES Modules** - For modern bundlers (`dist/module/`) +5. **Builds UMD** - For browser script tags (`dist/umd/`) + +##### Development Build with Watch Mode + +```bash +# Continuously rebuild on file changes (from monorepo root) +npx nx build storage-js --watch +``` + +##### Individual Build Targets + +For specific build outputs during development: + +```bash +# Build CommonJS only (Node.js) +npx nx build:main storage-js + +# Build ES Modules only (Modern bundlers) +npx nx build:module storage-js + +# Build UMD only (Browser/CDN) +npx nx build:umd storage-js +``` + +##### Other Useful Commands + +```bash +# Clean build artifacts +npx nx clean storage-js + +# Format code +npx nx format storage-js + +# Type checking +npx nx typecheck storage-js + +# Generate documentation +npx nx docs storage-js +``` + +#### Build Outputs Explained + +##### CommonJS (`dist/main/`) + +- **Used by:** Node.js applications, older build tools +- **Entry point:** `dist/main/index.js` +- **Module format:** `require()` and `module.exports` +- **TypeScript definitions:** Included + +##### ES Modules (`dist/module/`) + +- **Used by:** Modern bundlers (Webpack, Rollup, Vite) +- **Entry point:** `dist/module/index.js` +- **Module format:** `import` and `export` +- **TypeScript definitions:** `dist/module/index.d.ts` +- **Benefits:** Tree-shaking, better static analysis + +##### UMD (`dist/umd/`) + +- **Used by:** Browser ` + + ``` + +#### Package Exports + +The package.json exports are configured to provide the right format for each environment: + +```json +{ + "main": "dist/main/index.js", + "module": "dist/module/index.js", + "types": "dist/module/index.d.ts", + "jsdelivr": "dist/umd/supabase.js", + "unpkg": "dist/umd/supabase.js" +} +``` + +- **main** → Node.js environments (CommonJS format) +- **module** → Modern bundlers like Webpack, Vite, Rollup (ES Modules) +- **types** → TypeScript type definitions +- **jsdelivr/unpkg** → CDN usage via ` +``` + +or even: + +```html + +``` + +Then you can use it from a global `supabase` variable: + +```html + +``` + +### ESM + +You can use ` +``` + +### Deno + +You can use supabase-js in the Deno runtime via [JSR](https://jsr.io/@supabase/supabase-js): + +```js +import { createClient } from 'jsr:@supabase/supabase-js@2' +``` + +### Custom `fetch` implementation + +`supabase-js` uses the [`cross-fetch`](https://www.npmjs.com/package/cross-fetch) library to make HTTP requests, but an alternative `fetch` implementation can be provided as an option. This is most useful in environments where `cross-fetch` is not compatible, for instance Cloudflare Workers: + +```js +import { createClient } from '@supabase/supabase-js' + +// Provide a custom `fetch` implementation as an option +const supabase = createClient('https://xyzcompany.supabase.co', 'public-anon-key', { + global: { + fetch: (...args) => fetch(...args), + }, +}) +``` + +## Support Policy + +This section outlines the scope of support for various runtime environments in Supabase JavaScript client. + +### Node.js + +We only support Node.js versions that are in **Active LTS** or **Maintenance** status as defined by the [official Node.js release schedule](https://nodejs.org/en/about/previous-releases#release-schedule). This means we support versions that are currently receiving long-term support and critical bug fixes. + +When a Node.js version reaches end-of-life and is no longer in Active LTS or Maintenance status, Supabase will drop it in a **minor release**, and **this won't be considered a breaking change**. + +> ⚠️ **Node.js 18 Deprecation Notice** +> +> Node.js 18 reached end-of-life on April 30, 2025. As announced in [our deprecation notice](https://github.com/orgs/supabase/discussions/37217), support for Node.js 18 was dropped in version `2.79.0`. +> +> If you must use Node.js 18, please use version `2.78.0`, which is the last version that supported Node.js 18. + +### Deno + +We support Deno versions that are currently receiving active development and security updates. We follow the [official Deno release schedule](https://docs.deno.com/runtime/fundamentals/stability_and_releases/) and only support versions from the `stable` and `lts` release channels. + +When a Deno version reaches end-of-life and is no longer receiving security updates, Supabase will drop it in a **minor release**, and **this won't be considered a breaking change**. + +### Browsers + +All modern browsers are supported. We support browsers that provide native `fetch` API. For Realtime features, browsers must also support native `WebSocket` API. + +### Bun + +We support Bun runtime environments. Bun provides native fetch support and is compatible with Node.js APIs. Since Bun does not follow a structured release schedule like Node.js or Deno, we support current stable versions of Bun and may drop support for older versions in minor releases without considering it a breaking change. + +### React Native + +We support React Native environments with fetch polyfills provided by the framework. Since React Native does not follow a structured release schedule, we support current stable versions and may drop support for older versions in minor releases without considering it a breaking change. + +### Cloudflare Workers + +We support Cloudflare Workers runtime environments. Cloudflare Workers provides native fetch support. Since Cloudflare Workers does not follow a structured release schedule, we support current stable versions and may drop support for older versions in minor releases without considering it a breaking change. + +### Important Notes + +- **Experimental features**: Features marked as experimental may be removed or changed without notice + +## Contributing + +We welcome contributions! Please see our [Contributing Guide](../../../CONTRIBUTING.md) for details on how to get started. + +For major changes or if you're unsure about something, please open an issue first to discuss your proposed changes. + +### Building + +```bash +# From the monorepo root +npx nx build supabase-js + +# Or with watch mode for development +npx nx build supabase-js --watch +``` + +### Testing + +There's a complete guide on how to set up your environment for running locally the `supabase-js` integration tests. Please refer to [TESTING.md](./TESTING.md). + +## Badges + +[![Coverage Status](https://coveralls.io/repos/github/supabase/supabase-js/badge.svg?branch=master)](https://coveralls.io/github/supabase/supabase-js?branch=master) diff --git a/backend/node_modules/@supabase/supabase-js/dist/esm/wrapper.mjs b/backend/node_modules/@supabase/supabase-js/dist/esm/wrapper.mjs new file mode 100644 index 0000000..7941204 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/esm/wrapper.mjs @@ -0,0 +1,94 @@ +import * as index from '../main/index.js' +const { + PostgrestError, + FunctionsHttpError, + FunctionsFetchError, + FunctionsRelayError, + FunctionsError, + FunctionRegion, + SupabaseClient, + createClient, + GoTrueAdminApi, + GoTrueClient, + AuthAdminApi, + AuthClient, + navigatorLock, + NavigatorLockAcquireTimeoutError, + lockInternals, + processLock, + SIGN_OUT_SCOPES, + AuthError, + AuthApiError, + AuthUnknownError, + CustomAuthError, + AuthSessionMissingError, + AuthInvalidTokenResponseError, + AuthInvalidCredentialsError, + AuthImplicitGrantRedirectError, + AuthPKCEGrantCodeExchangeError, + AuthRetryableFetchError, + AuthWeakPasswordError, + AuthInvalidJwtError, + isAuthError, + isAuthApiError, + isAuthSessionMissingError, + isAuthImplicitGrantRedirectError, + isAuthRetryableFetchError, + isAuthWeakPasswordError, + RealtimePresence, + RealtimeChannel, + RealtimeClient, + REALTIME_LISTEN_TYPES, + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT, + REALTIME_PRESENCE_LISTEN_EVENTS, + REALTIME_SUBSCRIBE_STATES, + REALTIME_CHANNEL_STATES, +} = index.default || index + +export { + PostgrestError, + FunctionsHttpError, + FunctionsFetchError, + FunctionsRelayError, + FunctionsError, + FunctionRegion, + SupabaseClient, + createClient, + GoTrueAdminApi, + GoTrueClient, + AuthAdminApi, + AuthClient, + navigatorLock, + NavigatorLockAcquireTimeoutError, + lockInternals, + processLock, + SIGN_OUT_SCOPES, + AuthError, + AuthApiError, + AuthUnknownError, + CustomAuthError, + AuthSessionMissingError, + AuthInvalidTokenResponseError, + AuthInvalidCredentialsError, + AuthImplicitGrantRedirectError, + AuthPKCEGrantCodeExchangeError, + AuthRetryableFetchError, + AuthWeakPasswordError, + AuthInvalidJwtError, + isAuthError, + isAuthApiError, + isAuthSessionMissingError, + isAuthImplicitGrantRedirectError, + isAuthRetryableFetchError, + isAuthWeakPasswordError, + RealtimePresence, + RealtimeChannel, + RealtimeClient, + REALTIME_LISTEN_TYPES, + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT, + REALTIME_PRESENCE_LISTEN_EVENTS, + REALTIME_SUBSCRIBE_STATES, + REALTIME_CHANNEL_STATES, +} + +export default index.default || index diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/SupabaseClient.d.ts b/backend/node_modules/@supabase/supabase-js/dist/main/SupabaseClient.d.ts new file mode 100644 index 0000000..7af1b51 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/SupabaseClient.d.ts @@ -0,0 +1,139 @@ +import { FunctionsClient } from '@supabase/functions-js'; +import { PostgrestClient, type PostgrestFilterBuilder, type PostgrestQueryBuilder } from '@supabase/postgrest-js'; +import { type RealtimeChannel, type RealtimeChannelOptions, RealtimeClient } from '@supabase/realtime-js'; +import { StorageClient as SupabaseStorageClient } from '@supabase/storage-js'; +import { SupabaseAuthClient } from './lib/SupabaseAuthClient'; +import type { Fetch, GenericSchema, SupabaseClientOptions } from './lib/types'; +import { GetRpcFunctionFilterBuilderByArgs } from './lib/rest/types/common/rpc'; +/** + * Supabase Client. + * + * An isomorphic Javascript client for interacting with Postgres. + */ +export default class SupabaseClient) | { + PostgrestVersion: string; +} = 'public' extends keyof Omit ? 'public' : string & keyof Omit, SchemaName extends string & keyof Omit = SchemaNameOrClientOptions extends string & keyof Omit ? SchemaNameOrClientOptions : 'public' extends keyof Omit ? 'public' : string & keyof Omit, '__InternalSupabase'>, Schema extends Omit[SchemaName] extends GenericSchema ? Omit[SchemaName] : never = Omit[SchemaName] extends GenericSchema ? Omit[SchemaName] : never, ClientOptions extends { + PostgrestVersion: string; +} = SchemaNameOrClientOptions extends string & keyof Omit ? Database extends { + __InternalSupabase: { + PostgrestVersion: string; + }; +} ? Database['__InternalSupabase'] : { + PostgrestVersion: '12'; +} : SchemaNameOrClientOptions extends { + PostgrestVersion: string; +} ? SchemaNameOrClientOptions : never> { + protected supabaseUrl: string; + protected supabaseKey: string; + /** + * Supabase Auth allows you to create and manage user sessions for access to data that is secured by access policies. + */ + auth: SupabaseAuthClient; + realtime: RealtimeClient; + /** + * Supabase Storage allows you to manage user-generated content, such as photos or videos. + */ + storage: SupabaseStorageClient; + protected realtimeUrl: URL; + protected authUrl: URL; + protected storageUrl: URL; + protected functionsUrl: URL; + protected rest: PostgrestClient; + protected storageKey: string; + protected fetch?: Fetch; + protected changedAccessToken?: string; + protected accessToken?: () => Promise; + protected headers: Record; + /** + * Create a new client for use in the browser. + * @param supabaseUrl The unique Supabase URL which is supplied when you create a new project in your project dashboard. + * @param supabaseKey The unique Supabase Key which is supplied when you create a new project in your project dashboard. + * @param options.db.schema You can switch in between schemas. The schema needs to be on the list of exposed schemas inside Supabase. + * @param options.auth.autoRefreshToken Set to "true" if you want to automatically refresh the token before expiring. + * @param options.auth.persistSession Set to "true" if you want to automatically save the user session into local storage. + * @param options.auth.detectSessionInUrl Set to "true" if you want to automatically detects OAuth grants in the URL and signs in the user. + * @param options.realtime Options passed along to realtime-js constructor. + * @param options.storage Options passed along to the storage-js constructor. + * @param options.global.fetch A custom fetch implementation. + * @param options.global.headers Any additional headers to send with each network request. + * @example + * ```ts + * import { createClient } from '@supabase/supabase-js' + * + * const supabase = createClient('https://xyzcompany.supabase.co', 'public-anon-key') + * const { data } = await supabase.from('profiles').select('*') + * ``` + */ + constructor(supabaseUrl: string, supabaseKey: string, options?: SupabaseClientOptions); + /** + * Supabase Functions allows you to deploy and invoke edge functions. + */ + get functions(): FunctionsClient; + from(relation: TableName): PostgrestQueryBuilder; + from(relation: ViewName): PostgrestQueryBuilder; + /** + * Select a schema to query or perform an function (rpc) call. + * + * The schema needs to be on the list of exposed schemas inside Supabase. + * + * @param schema - The schema to query + */ + schema>(schema: DynamicSchema): PostgrestClient; + /** + * Perform a function call. + * + * @param fn - The function name to call + * @param args - The arguments to pass to the function call + * @param options - Named parameters + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * @param options.get - When set to `true`, the function will be called with + * read-only access mode. + * @param options.count - Count algorithm to use to count rows returned by the + * function. Only applicable for [set-returning + * functions](https://www.postgresql.org/docs/current/functions-srf.html). + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + rpc = GetRpcFunctionFilterBuilderByArgs>(fn: FnName, args?: Args, options?: { + head?: boolean; + get?: boolean; + count?: 'exact' | 'planned' | 'estimated'; + }): PostgrestFilterBuilder; + /** + * Creates a Realtime channel with Broadcast, Presence, and Postgres Changes. + * + * @param {string} name - The name of the Realtime channel. + * @param {Object} opts - The options to pass to the Realtime channel. + * + */ + channel(name: string, opts?: RealtimeChannelOptions): RealtimeChannel; + /** + * Returns all Realtime channels. + */ + getChannels(): RealtimeChannel[]; + /** + * Unsubscribes and removes Realtime channel from Realtime client. + * + * @param {RealtimeChannel} channel - The name of the Realtime channel. + * + */ + removeChannel(channel: RealtimeChannel): Promise<'ok' | 'timed out' | 'error'>; + /** + * Unsubscribes and removes all Realtime channels from Realtime client. + */ + removeAllChannels(): Promise<('ok' | 'timed out' | 'error')[]>; + private _getAccessToken; + private _initSupabaseAuthClient; + private _initRealtimeClient; + private _listenForAuthEvents; + private _handleTokenChanged; +} +//# sourceMappingURL=SupabaseClient.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/SupabaseClient.d.ts.map b/backend/node_modules/@supabase/supabase-js/dist/main/SupabaseClient.d.ts.map new file mode 100644 index 0000000..a90e30f --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/SupabaseClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"SupabaseClient.d.ts","sourceRoot":"","sources":["../../src/SupabaseClient.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAA;AACxD,OAAO,EACL,eAAe,EACf,KAAK,sBAAsB,EAC3B,KAAK,qBAAqB,EAC3B,MAAM,wBAAwB,CAAA;AAC/B,OAAO,EACL,KAAK,eAAe,EACpB,KAAK,sBAAsB,EAC3B,cAAc,EAEf,MAAM,uBAAuB,CAAA;AAC9B,OAAO,EAAE,aAAa,IAAI,qBAAqB,EAAE,MAAM,sBAAsB,CAAA;AAS7E,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAA;AAC7D,OAAO,KAAK,EACV,KAAK,EACL,aAAa,EAEb,qBAAqB,EACtB,MAAM,aAAa,CAAA;AACpB,OAAO,EAAE,iCAAiC,EAAE,MAAM,6BAA6B,CAAA;AAE/E;;;;GAIG;AACH,MAAM,CAAC,OAAO,OAAO,cAAc,CACjC,QAAQ,GAAG,GAAG,EAId,yBAAyB,SACrB,CAAC,MAAM,GAAG,MAAM,IAAI,CAAC,QAAQ,EAAE,oBAAoB,CAAC,CAAC,GACrD;IAAE,gBAAgB,EAAE,MAAM,CAAA;CAAE,GAAG,QAAQ,SAAS,MAAM,IAAI,CAAC,QAAQ,EAAE,oBAAoB,CAAC,GAC1F,QAAQ,GACR,MAAM,GAAG,MAAM,IAAI,CAAC,QAAQ,EAAE,oBAAoB,CAAC,EACvD,UAAU,SAAS,MAAM,GACvB,MAAM,IAAI,CAAC,QAAQ,EAAE,oBAAoB,CAAC,GAAG,yBAAyB,SAAS,MAAM,GACrF,MAAM,IAAI,CAAC,QAAQ,EAAE,oBAAoB,CAAC,GACxC,yBAAyB,GACzB,QAAQ,SAAS,MAAM,IAAI,CAAC,QAAQ,E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ff --git a/backend/node_modules/@supabase/supabase-js/dist/main/SupabaseClient.js b/backend/node_modules/@supabase/supabase-js/dist/main/SupabaseClient.js new file mode 100644 index 0000000..549c9dd --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/SupabaseClient.js @@ -0,0 +1,235 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const functions_js_1 = require("@supabase/functions-js"); +const postgrest_js_1 = require("@supabase/postgrest-js"); +const realtime_js_1 = require("@supabase/realtime-js"); +const storage_js_1 = require("@supabase/storage-js"); +const constants_1 = require("./lib/constants"); +const fetch_1 = require("./lib/fetch"); +const helpers_1 = require("./lib/helpers"); +const SupabaseAuthClient_1 = require("./lib/SupabaseAuthClient"); +/** + * Supabase Client. + * + * An isomorphic Javascript client for interacting with Postgres. + */ +class SupabaseClient { + /** + * Create a new client for use in the browser. + * @param supabaseUrl The unique Supabase URL which is supplied when you create a new project in your project dashboard. + * @param supabaseKey The unique Supabase Key which is supplied when you create a new project in your project dashboard. + * @param options.db.schema You can switch in between schemas. The schema needs to be on the list of exposed schemas inside Supabase. + * @param options.auth.autoRefreshToken Set to "true" if you want to automatically refresh the token before expiring. + * @param options.auth.persistSession Set to "true" if you want to automatically save the user session into local storage. + * @param options.auth.detectSessionInUrl Set to "true" if you want to automatically detects OAuth grants in the URL and signs in the user. + * @param options.realtime Options passed along to realtime-js constructor. + * @param options.storage Options passed along to the storage-js constructor. + * @param options.global.fetch A custom fetch implementation. + * @param options.global.headers Any additional headers to send with each network request. + * @example + * ```ts + * import { createClient } from '@supabase/supabase-js' + * + * const supabase = createClient('https://xyzcompany.supabase.co', 'public-anon-key') + * const { data } = await supabase.from('profiles').select('*') + * ``` + */ + constructor(supabaseUrl, supabaseKey, options) { + var _a, _b, _c; + this.supabaseUrl = supabaseUrl; + this.supabaseKey = supabaseKey; + const baseUrl = (0, helpers_1.validateSupabaseUrl)(supabaseUrl); + if (!supabaseKey) + throw new Error('supabaseKey is required.'); + this.realtimeUrl = new URL('realtime/v1', baseUrl); + this.realtimeUrl.protocol = this.realtimeUrl.protocol.replace('http', 'ws'); + this.authUrl = new URL('auth/v1', baseUrl); + this.storageUrl = new URL('storage/v1', baseUrl); + this.functionsUrl = new URL('functions/v1', baseUrl); + // default storage key uses the supabase project ref as a namespace + const defaultStorageKey = `sb-${baseUrl.hostname.split('.')[0]}-auth-token`; + const DEFAULTS = { + db: constants_1.DEFAULT_DB_OPTIONS, + realtime: constants_1.DEFAULT_REALTIME_OPTIONS, + auth: Object.assign(Object.assign({}, constants_1.DEFAULT_AUTH_OPTIONS), { storageKey: defaultStorageKey }), + global: constants_1.DEFAULT_GLOBAL_OPTIONS, + }; + const settings = (0, helpers_1.applySettingDefaults)(options !== null && options !== void 0 ? options : {}, DEFAULTS); + this.storageKey = (_a = settings.auth.storageKey) !== null && _a !== void 0 ? _a : ''; + this.headers = (_b = settings.global.headers) !== null && _b !== void 0 ? _b : {}; + if (!settings.accessToken) { + this.auth = this._initSupabaseAuthClient((_c = settings.auth) !== null && _c !== void 0 ? _c : {}, this.headers, settings.global.fetch); + } + else { + this.accessToken = settings.accessToken; + this.auth = new Proxy({}, { + get: (_, prop) => { + throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(prop)} is not possible`); + }, + }); + } + this.fetch = (0, fetch_1.fetchWithAuth)(supabaseKey, this._getAccessToken.bind(this), settings.global.fetch); + this.realtime = this._initRealtimeClient(Object.assign({ headers: this.headers, accessToken: this._getAccessToken.bind(this) }, settings.realtime)); + if (this.accessToken) { + // Start auth immediately to avoid race condition with channel subscriptions + this.accessToken() + .then((token) => this.realtime.setAuth(token)) + .catch((e) => console.warn('Failed to set initial Realtime auth token:', e)); + } + this.rest = new postgrest_js_1.PostgrestClient(new URL('rest/v1', baseUrl).href, { + headers: this.headers, + schema: settings.db.schema, + fetch: this.fetch, + }); + this.storage = new storage_js_1.StorageClient(this.storageUrl.href, this.headers, this.fetch, options === null || options === void 0 ? void 0 : options.storage); + if (!settings.accessToken) { + this._listenForAuthEvents(); + } + } + /** + * Supabase Functions allows you to deploy and invoke edge functions. + */ + get functions() { + return new functions_js_1.FunctionsClient(this.functionsUrl.href, { + headers: this.headers, + customFetch: this.fetch, + }); + } + /** + * Perform a query on a table or a view. + * + * @param relation - The table or view name to query + */ + from(relation) { + return this.rest.from(relation); + } + // NOTE: signatures must be kept in sync with PostgrestClient.schema + /** + * Select a schema to query or perform an function (rpc) call. + * + * The schema needs to be on the list of exposed schemas inside Supabase. + * + * @param schema - The schema to query + */ + schema(schema) { + return this.rest.schema(schema); + } + // NOTE: signatures must be kept in sync with PostgrestClient.rpc + /** + * Perform a function call. + * + * @param fn - The function name to call + * @param args - The arguments to pass to the function call + * @param options - Named parameters + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * @param options.get - When set to `true`, the function will be called with + * read-only access mode. + * @param options.count - Count algorithm to use to count rows returned by the + * function. Only applicable for [set-returning + * functions](https://www.postgresql.org/docs/current/functions-srf.html). + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + rpc(fn, args = {}, options = { + head: false, + get: false, + count: undefined, + }) { + return this.rest.rpc(fn, args, options); + } + /** + * Creates a Realtime channel with Broadcast, Presence, and Postgres Changes. + * + * @param {string} name - The name of the Realtime channel. + * @param {Object} opts - The options to pass to the Realtime channel. + * + */ + channel(name, opts = { config: {} }) { + return this.realtime.channel(name, opts); + } + /** + * Returns all Realtime channels. + */ + getChannels() { + return this.realtime.getChannels(); + } + /** + * Unsubscribes and removes Realtime channel from Realtime client. + * + * @param {RealtimeChannel} channel - The name of the Realtime channel. + * + */ + removeChannel(channel) { + return this.realtime.removeChannel(channel); + } + /** + * Unsubscribes and removes all Realtime channels from Realtime client. + */ + removeAllChannels() { + return this.realtime.removeAllChannels(); + } + async _getAccessToken() { + var _a, _b; + if (this.accessToken) { + return await this.accessToken(); + } + const { data } = await this.auth.getSession(); + return (_b = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) !== null && _b !== void 0 ? _b : this.supabaseKey; + } + _initSupabaseAuthClient({ autoRefreshToken, persistSession, detectSessionInUrl, storage, userStorage, storageKey, flowType, lock, debug, throwOnError, }, headers, fetch) { + const authHeaders = { + Authorization: `Bearer ${this.supabaseKey}`, + apikey: `${this.supabaseKey}`, + }; + return new SupabaseAuthClient_1.SupabaseAuthClient({ + url: this.authUrl.href, + headers: Object.assign(Object.assign({}, authHeaders), headers), + storageKey: storageKey, + autoRefreshToken, + persistSession, + detectSessionInUrl, + storage, + userStorage, + flowType, + lock, + debug, + throwOnError, + fetch, + // auth checks if there is a custom authorizaiton header using this flag + // so it knows whether to return an error when getUser is called with no session + hasCustomAuthorizationHeader: Object.keys(this.headers).some((key) => key.toLowerCase() === 'authorization'), + }); + } + _initRealtimeClient(options) { + return new realtime_js_1.RealtimeClient(this.realtimeUrl.href, Object.assign(Object.assign({}, options), { params: Object.assign({ apikey: this.supabaseKey }, options === null || options === void 0 ? void 0 : options.params) })); + } + _listenForAuthEvents() { + const data = this.auth.onAuthStateChange((event, session) => { + this._handleTokenChanged(event, 'CLIENT', session === null || session === void 0 ? void 0 : session.access_token); + }); + return data; + } + _handleTokenChanged(event, source, token) { + if ((event === 'TOKEN_REFRESHED' || event === 'SIGNED_IN') && + this.changedAccessToken !== token) { + this.changedAccessToken = token; + this.realtime.setAuth(token); + } + else if (event === 'SIGNED_OUT') { + this.realtime.setAuth(); + if (source == 'STORAGE') + this.auth.signOut(); + this.changedAccessToken = undefined; + } + } +} +exports.default = SupabaseClient; +//# sourceMappingURL=SupabaseClient.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/SupabaseClient.js.map b/backend/node_modules/@supabase/supabase-js/dist/main/SupabaseClient.js.map new file mode 100644 index 0000000..e0203ed --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/SupabaseClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SupabaseClient.js","sourceRoot":"","sources":["../../src/SupabaseClient.ts"],"names":[],"mappings":";;AACA,yDAAwD;AACxD,yDAI+B;AAC/B,uDAK8B;AAC9B,qDAA6E;AAC7E,+CAKwB;AACxB,uCAA2C;AAC3C,2CAAyE;AACzE,iEAA6D;AAS7D;;;;GAIG;AACH,MAAqB,cAAc;IAuDjC;;;;;;;;;;;;;;;;;;;OAmBG;IACH,YACY,WAAmB,EACnB,WAAmB,EAC7B,OAA2C;;QAFjC,gBAAW,GAAX,WAAW,CAAQ;QACnB,gBAAW,GAAX,WAAW,CAAQ;QAG7B,MAAM,OAAO,GAAG,IAAA,6BAAmB,EAAC,WAAW,CAAC,CAAA;QAChD,IAAI,CAAC,WAAW;YAAE,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAA;QAE7D,IAAI,CAAC,WAAW,GAAG,IAAI,GAAG,CAAC,aAAa,EAAE,OAAO,CAAC,CAAA;QAClD,IAAI,CAAC,WAAW,CAAC,QAAQ,GAAG,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,OAAO,CAAC,MAAM,EAAE,IAAI,CAAC,CAAA;QAC3E,IAAI,CAAC,OAAO,GAAG,IAAI,GAAG,CAAC,SAAS,EAAE,OAAO,CAAC,CAAA;QAC1C,IAAI,CAAC,UAAU,GAAG,IAAI,GAAG,CAAC,YAAY,EAAE,OAAO,CAAC,CAAA;QAChD,IAAI,CAAC,YAAY,GAAG,IAAI,GAAG,CAAC,cAAc,EAAE,OAAO,CAAC,CAAA;QAEpD,mEAAmE;QACnE,MAAM,iBAAiB,GAAG,MAAM,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,aAAa,CAAA;QAC3E,MAAM,QAAQ,GAAG;YACf,EAAE,EAAE,8BAAkB;YACtB,QAAQ,EAAE,oCAAwB;YAClC,IAAI,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AAA;QACF,OAAO,IAAI,CAAA;IACb,CAAC;IAEO,mBAAmB,CACzB,KAAsB,EACtB,MAA4B,EAC5B,KAAc;QAEd,IACE,CAAC,KAAK,KAAK,iBAAiB,IAAI,KAAK,KAAK,WAAW,CAAC;YACtD,IAAI,CAAC,kBAAkB,KAAK,KAAK,EACjC,CAAC;YACD,IAAI,CAAC,kBAAkB,GAAG,KAAK,CAAA;YAC/B,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,CAAA;QAC9B,CAAC;aAAM,IAAI,KAAK,KAAK,YAAY,EAAE,CAAC;YAClC,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAA;YACvB,IAAI,MAAM,IAAI,SAAS;gBAAE,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAA;YAC5C,IAAI,CAAC,kBAAkB,GAAG,SAAS,CAAA;QACrC,CAAC;IACH,CAAC;CACF;AA9XD,iCA8XC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/index.d.ts b/backend/node_modules/@supabase/supabase-js/dist/main/index.d.ts new file mode 100644 index 0000000..fb5f5dc --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/index.d.ts @@ -0,0 +1,24 @@ +import SupabaseClient from './SupabaseClient'; +import type { SupabaseClientOptions } from './lib/types'; +export * from '@supabase/auth-js'; +export type { User as AuthUser, Session as AuthSession } from '@supabase/auth-js'; +export { type PostgrestResponse, type PostgrestSingleResponse, type PostgrestMaybeSingleResponse, PostgrestError, } from '@supabase/postgrest-js'; +export { FunctionsHttpError, FunctionsFetchError, FunctionsRelayError, FunctionsError, type FunctionInvokeOptions, FunctionRegion, } from '@supabase/functions-js'; +export * from '@supabase/realtime-js'; +export { default as SupabaseClient } from './SupabaseClient'; +export type { SupabaseClientOptions, QueryResult, QueryData, QueryError } from './lib/types'; +/** + * Creates a new Supabase Client. + * + * @example + * ```ts + * import { createClient } from '@supabase/supabase-js' + * + * const supabase = createClient('https://xyzcompany.supabase.co', 'public-anon-key') + * const { data, error } = await supabase.from('profiles').select('*') + * ``` + */ +export declare const createClient: ) | { + PostgrestVersion: string; +} = "public" extends keyof Omit ? "public" : string & keyof Omit, SchemaName extends string & keyof Omit = SchemaNameOrClientOptions extends string & keyof Omit ? SchemaNameOrClientOptions : "public" extends keyof Omit ? "public" : string & keyof Omit, "__InternalSupabase">>(supabaseUrl: string, supabaseKey: string, options?: SupabaseClientOptions) => SupabaseClient; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/index.d.ts.map b/backend/node_modules/@supabase/supabase-js/dist/main/index.d.ts.map new file mode 100644 index 0000000..3926737 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,kBAAkB,CAAA;AAC7C,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAA;AAExD,cAAc,mBAAmB,CAAA;AACjC,YAAY,EAAE,IAAI,IAAI,QAAQ,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,mBAAmB,CAAA;AACjF,OAAO,EACL,KAAK,iBAAiB,EACtB,KAAK,uBAAuB,EAC5B,KAAK,4BAA4B,EACjC,cAAc,GACf,MAAM,wBAAwB,CAAA;AAC/B,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,mBAAmB,EACnB,cAAc,EACd,KAAK,qBAAqB,EAC1B,cAAc,GACf,MAAM,wBAAwB,CAAA;AAC/B,cAAc,uBAAuB,CAAA;AACrC,OAAO,EAAE,OAAO,IAAI,cAAc,EAAE,MAAM,kBAAkB,CAAA;AAC5D,YAAY,EAAE,qBAAqB,EAAE,WAAW,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AAE5F;;;;;;;;;;GAUG;AACH,eAAO,MAAM,YAAY,GACvB,QAAQ,GAAG,GAAG,EACd,yBAAyB,SACrB,CAAC,MAAM,GAAG,MAAM,IAAI,CAAC,QAAQ,EAAE,oBAAoB,CAAC,CAAC,GACrD;IAAE,gBAAgB,EAAE,MAAM,CAAA;CAAE,GAAG,QAAQ,SAAS,MAAM,IAAI,CAAC,QAAQ,EAAE,oBAAoB,CAAC,GAC1F,QAAQ,GACR,MAAM,GAAG,MAAM,IAAI,CAAC,QAAQ,EAAE,oBAAoB,CAAC,EACvD,UAAU,SAAS,MAAM,GACvB,MAAM,IAAI,CAAC,QAAQ,EAAE,oBAAoB,CAAC,GAAG,yBAAyB,SAAS,MAAM,GACrF,MAAM,IAAI,CAAC,QAAQ,EAAE,oBAAoB,CAAC,GACxC,yBAAyB,GACzB,QAAQ,SAAS,MAAM,IAAI,CAAC,QAAQ,EAAE,oBAAoB,CAAC,GACzD,QAAQ,GACR,MAAM,GAAG,MAAM,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,oBAAoB,CAAC,EAAE,oBAAoB,CAAC,EAErF,aAAa,MAAM,EACnB,aAAa,MAAM,EACnB,UAAU,qBAAqB,CAAC,UAAU,CAAC,KAC1C,cAAc,CAAC,QAAQ,EAAE,yBAAyB,EAAE,UAAU,CAMhE,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/index.js b/backend/node_modules/@supabase/supabase-js/dist/main/index.js new file mode 100644 index 0000000..38c81c0 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/index.js @@ -0,0 +1,76 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createClient = exports.SupabaseClient = exports.FunctionRegion = exports.FunctionsError = exports.FunctionsRelayError = exports.FunctionsFetchError = exports.FunctionsHttpError = exports.PostgrestError = void 0; +const SupabaseClient_1 = __importDefault(require("./SupabaseClient")); +__exportStar(require("@supabase/auth-js"), exports); +var postgrest_js_1 = require("@supabase/postgrest-js"); +Object.defineProperty(exports, "PostgrestError", { enumerable: true, get: function () { return postgrest_js_1.PostgrestError; } }); +var functions_js_1 = require("@supabase/functions-js"); +Object.defineProperty(exports, "FunctionsHttpError", { enumerable: true, get: function () { return functions_js_1.FunctionsHttpError; } }); +Object.defineProperty(exports, "FunctionsFetchError", { enumerable: true, get: function () { return functions_js_1.FunctionsFetchError; } }); +Object.defineProperty(exports, "FunctionsRelayError", { enumerable: true, get: function () { return functions_js_1.FunctionsRelayError; } }); +Object.defineProperty(exports, "FunctionsError", { enumerable: true, get: function () { return functions_js_1.FunctionsError; } }); +Object.defineProperty(exports, "FunctionRegion", { enumerable: true, get: function () { return functions_js_1.FunctionRegion; } }); +__exportStar(require("@supabase/realtime-js"), exports); +var SupabaseClient_2 = require("./SupabaseClient"); +Object.defineProperty(exports, "SupabaseClient", { enumerable: true, get: function () { return __importDefault(SupabaseClient_2).default; } }); +/** + * Creates a new Supabase Client. + * + * @example + * ```ts + * import { createClient } from '@supabase/supabase-js' + * + * const supabase = createClient('https://xyzcompany.supabase.co', 'public-anon-key') + * const { data, error } = await supabase.from('profiles').select('*') + * ``` + */ +const createClient = (supabaseUrl, supabaseKey, options) => { + return new SupabaseClient_1.default(supabaseUrl, supabaseKey, options); +}; +exports.createClient = createClient; +// Check for Node.js <= 18 deprecation +function shouldShowDeprecationWarning() { + // Skip in browser environments + if (typeof window !== 'undefined') { + return false; + } + // Skip if process is not available (e.g., Edge Runtime) + if (typeof process === 'undefined') { + return false; + } + // Use dynamic property access to avoid Next.js Edge Runtime static analysis warnings + const processVersion = process['version']; + if (processVersion === undefined || processVersion === null) { + return false; + } + const versionMatch = processVersion.match(/^v(\d+)\./); + if (!versionMatch) { + return false; + } + const majorVersion = parseInt(versionMatch[1], 10); + return majorVersion <= 18; +} +if (shouldShowDeprecationWarning()) { + console.warn(`⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. ` + + `Please upgrade to Node.js 20 or later. ` + + `For more information, visit: https://github.com/orgs/supabase/discussions/37217`); +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/index.js.map b/backend/node_modules/@supabase/supabase-js/dist/main/index.js.map new file mode 100644 index 0000000..5e12715 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,sEAA6C;AAG7C,oDAAiC;AAEjC,uDAK+B;AAD7B,8GAAA,cAAc,OAAA;AAEhB,uDAO+B;AAN7B,kHAAA,kBAAkB,OAAA;AAClB,mHAAA,mBAAmB,OAAA;AACnB,mHAAA,mBAAmB,OAAA;AACnB,8GAAA,cAAc,OAAA;AAEd,8GAAA,cAAc,OAAA;AAEhB,wDAAqC;AACrC,mDAA4D;AAAnD,iIAAA,OAAO,OAAkB;AAGlC;;;;;;;;;;GAUG;AACI,MAAM,YAAY,GAAG,CAe1B,WAAmB,EACnB,WAAmB,EACnB,OAA2C,EACsB,EAAE;IACnE,OAAO,IAAI,wBAAc,CACvB,WAAW,EACX,WAAW,EACX,OAAO,CACR,CAAA;AACH,CAAC,CAAA;AAxBY,QAAA,YAAY,gBAwBxB;AAED,sCAAsC;AACtC,SAAS,4BAA4B;IACnC,+BAA+B;IAC/B,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE,CAAC;QAClC,OAAO,KAAK,CAAA;IACd,CAAC;IAED,wDAAwD;IACxD,IAAI,OAAO,OAAO,KAAK,WAAW,EAAE,CAAC;QACnC,OAAO,KAAK,CAAA;IACd,CAAC;IAED,qFAAqF;IACrF,MAAM,cAAc,GAAI,OAAe,CAAC,SAAS,CAAC,CAAA;IAClD,IAAI,cAAc,KAAK,SAAS,IAAI,cAAc,KAAK,IAAI,EAAE,CAAC;QAC5D,OAAO,KAAK,CAAA;IACd,CAAC;IAED,MAAM,YAAY,GAAG,cAAc,CAAC,KAAK,CAAC,WAAW,CAAC,CAAA;IACtD,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,OAAO,KAAK,CAAA;IACd,CAAC;IAED,MAAM,YAAY,GAAG,QAAQ,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAA;IAClD,OAAO,YAAY,IAAI,EAAE,CAAA;AAC3B,CAAC;AAED,IAAI,4BAA4B,EAAE,EAAE,CAAC;IACnC,OAAO,CAAC,IAAI,CACV,uHAAuH;QACrH,yCAAyC;QACzC,iFAAiF,CACpF,CAAA;AACH,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/lib/SupabaseAuthClient.d.ts b/backend/node_modules/@supabase/supabase-js/dist/main/lib/SupabaseAuthClient.d.ts new file mode 100644 index 0000000..a83dd57 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/lib/SupabaseAuthClient.d.ts @@ -0,0 +1,6 @@ +import { AuthClient } from '@supabase/auth-js'; +import { SupabaseAuthClientOptions } from './types'; +export declare class SupabaseAuthClient extends AuthClient { + constructor(options: SupabaseAuthClientOptions); +} +//# sourceMappingURL=SupabaseAuthClient.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/lib/SupabaseAuthClient.d.ts.map b/backend/node_modules/@supabase/supabase-js/dist/main/lib/SupabaseAuthClient.d.ts.map new file mode 100644 index 0000000..7d17122 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/lib/SupabaseAuthClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"SupabaseAuthClient.d.ts","sourceRoot":"","sources":["../../../src/lib/SupabaseAuthClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAA;AAC9C,OAAO,EAAE,yBAAyB,EAAE,MAAM,SAAS,CAAA;AAEnD,qBAAa,kBAAmB,SAAQ,UAAU;gBACpC,OAAO,EAAE,yBAAyB;CAG/C"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/lib/SupabaseAuthClient.js b/backend/node_modules/@supabase/supabase-js/dist/main/lib/SupabaseAuthClient.js new file mode 100644 index 0000000..9f8a94e --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/lib/SupabaseAuthClient.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SupabaseAuthClient = void 0; +const auth_js_1 = require("@supabase/auth-js"); +class SupabaseAuthClient extends auth_js_1.AuthClient { + constructor(options) { + super(options); + } +} +exports.SupabaseAuthClient = SupabaseAuthClient; +//# sourceMappingURL=SupabaseAuthClient.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/lib/SupabaseAuthClient.js.map b/backend/node_modules/@supabase/supabase-js/dist/main/lib/SupabaseAuthClient.js.map new file mode 100644 index 0000000..34d75b4 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/lib/SupabaseAuthClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SupabaseAuthClient.js","sourceRoot":"","sources":["../../../src/lib/SupabaseAuthClient.ts"],"names":[],"mappings":";;;AAAA,+CAA8C;AAG9C,MAAa,kBAAmB,SAAQ,oBAAU;IAChD,YAAY,OAAkC;QAC5C,KAAK,CAAC,OAAO,CAAC,CAAA;IAChB,CAAC;CACF;AAJD,gDAIC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/lib/constants.d.ts b/backend/node_modules/@supabase/supabase-js/dist/main/lib/constants.d.ts new file mode 100644 index 0000000..fbea59d --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/lib/constants.d.ts @@ -0,0 +1,16 @@ +import { RealtimeClientOptions } from '@supabase/realtime-js'; +import { SupabaseAuthClientOptions } from './types'; +export declare const DEFAULT_HEADERS: { + 'X-Client-Info': string; +}; +export declare const DEFAULT_GLOBAL_OPTIONS: { + headers: { + 'X-Client-Info': string; + }; +}; +export declare const DEFAULT_DB_OPTIONS: { + schema: string; +}; +export declare const DEFAULT_AUTH_OPTIONS: SupabaseAuthClientOptions; +export declare const DEFAULT_REALTIME_OPTIONS: RealtimeClientOptions; +//# sourceMappingURL=constants.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/lib/constants.d.ts.map b/backend/node_modules/@supabase/supabase-js/dist/main/lib/constants.d.ts.map new file mode 100644 index 0000000..1d8e842 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/lib/constants.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAA;AAC7D,OAAO,EAAE,yBAAyB,EAAE,MAAM,SAAS,CAAA;AAenD,eAAO,MAAM,eAAe;;CAA0D,CAAA;AAEtF,eAAO,MAAM,sBAAsB;;;;CAElC,CAAA;AAED,eAAO,MAAM,kBAAkB;;CAE9B,CAAA;AAED,eAAO,MAAM,oBAAoB,EAAE,yBAKlC,CAAA;AAED,eAAO,MAAM,wBAAwB,EAAE,qBAA0B,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/lib/constants.js b/backend/node_modules/@supabase/supabase-js/dist/main/lib/constants.js new file mode 100644 index 0000000..d3c4328 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/lib/constants.js @@ -0,0 +1,33 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DEFAULT_REALTIME_OPTIONS = exports.DEFAULT_AUTH_OPTIONS = exports.DEFAULT_DB_OPTIONS = exports.DEFAULT_GLOBAL_OPTIONS = exports.DEFAULT_HEADERS = void 0; +const version_1 = require("./version"); +let JS_ENV = ''; +// @ts-ignore +if (typeof Deno !== 'undefined') { + JS_ENV = 'deno'; +} +else if (typeof document !== 'undefined') { + JS_ENV = 'web'; +} +else if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') { + JS_ENV = 'react-native'; +} +else { + JS_ENV = 'node'; +} +exports.DEFAULT_HEADERS = { 'X-Client-Info': `supabase-js-${JS_ENV}/${version_1.version}` }; +exports.DEFAULT_GLOBAL_OPTIONS = { + headers: exports.DEFAULT_HEADERS, +}; +exports.DEFAULT_DB_OPTIONS = { + schema: 'public', +}; +exports.DEFAULT_AUTH_OPTIONS = { + autoRefreshToken: true, + persistSession: true, + detectSessionInUrl: true, + flowType: 'implicit', +}; +exports.DEFAULT_REALTIME_OPTIONS = {}; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/lib/constants.js.map b/backend/node_modules/@supabase/supabase-js/dist/main/lib/constants.js.map new file mode 100644 index 0000000..35a58bb --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/lib/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":";;;AAGA,uCAAmC;AAEnC,IAAI,MAAM,GAAG,EAAE,CAAA;AACf,aAAa;AACb,IAAI,OAAO,IAAI,KAAK,WAAW,EAAE,CAAC;IAChC,MAAM,GAAG,MAAM,CAAA;AACjB,CAAC;KAAM,IAAI,OAAO,QAAQ,KAAK,WAAW,EAAE,CAAC;IAC3C,MAAM,GAAG,KAAK,CAAA;AAChB,CAAC;KAAM,IAAI,OAAO,SAAS,KAAK,WAAW,IAAI,SAAS,CAAC,OAAO,KAAK,aAAa,EAAE,CAAC;IACnF,MAAM,GAAG,cAAc,CAAA;AACzB,CAAC;KAAM,CAAC;IACN,MAAM,GAAG,MAAM,CAAA;AACjB,CAAC;AAEY,QAAA,eAAe,GAAG,EAAE,eAAe,EAAE,eAAe,MAAM,IAAI,iBAAO,EAAE,EAAE,CAAA;AAEzE,QAAA,sBAAsB,GAAG;IACpC,OAAO,EAAE,uBAAe;CACzB,CAAA;AAEY,QAAA,kBAAkB,GAAG;IAChC,MAAM,EAAE,QAAQ;CACjB,CAAA;AAEY,QAAA,oBAAoB,GAA8B;IAC7D,gBAAgB,EAAE,IAAI;IACtB,cAAc,EAAE,IAAI;IACpB,kBAAkB,EAAE,IAAI;IACxB,QAAQ,EAAE,UAAU;CACrB,CAAA;AAEY,QAAA,wBAAwB,GAA0B,EAAE,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/lib/fetch.d.ts b/backend/node_modules/@supabase/supabase-js/dist/main/lib/fetch.d.ts new file mode 100644 index 0000000..363e38d --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/lib/fetch.d.ts @@ -0,0 +1,9 @@ +type Fetch = typeof fetch; +export declare const resolveFetch: (customFetch?: Fetch) => Fetch; +export declare const resolveHeadersConstructor: () => { + new (init?: HeadersInit): Headers; + prototype: Headers; +}; +export declare const fetchWithAuth: (supabaseKey: string, getAccessToken: () => Promise, customFetch?: Fetch) => Fetch; +export {}; +//# sourceMappingURL=fetch.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/lib/fetch.d.ts.map b/backend/node_modules/@supabase/supabase-js/dist/main/lib/fetch.d.ts.map new file mode 100644 index 0000000..16826ba --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/lib/fetch.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../../../src/lib/fetch.ts"],"names":[],"mappings":"AAAA,KAAK,KAAK,GAAG,OAAO,KAAK,CAAA;AAEzB,eAAO,MAAM,YAAY,GAAI,cAAc,KAAK,KAAG,KAKlD,CAAA;AAED,eAAO,MAAM,yBAAyB;;;CAErC,CAAA;AAED,eAAO,MAAM,aAAa,GACxB,aAAa,MAAM,EACnB,gBAAgB,MAAM,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,EAC5C,cAAc,KAAK,KAClB,KAkBF,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/lib/fetch.js b/backend/node_modules/@supabase/supabase-js/dist/main/lib/fetch.js new file mode 100644 index 0000000..118d01a --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/lib/fetch.js @@ -0,0 +1,32 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fetchWithAuth = exports.resolveHeadersConstructor = exports.resolveFetch = void 0; +const resolveFetch = (customFetch) => { + if (customFetch) { + return (...args) => customFetch(...args); + } + return (...args) => fetch(...args); +}; +exports.resolveFetch = resolveFetch; +const resolveHeadersConstructor = () => { + return Headers; +}; +exports.resolveHeadersConstructor = resolveHeadersConstructor; +const fetchWithAuth = (supabaseKey, getAccessToken, customFetch) => { + const fetch = (0, exports.resolveFetch)(customFetch); + const HeadersConstructor = (0, exports.resolveHeadersConstructor)(); + return async (input, init) => { + var _a; + const accessToken = (_a = (await getAccessToken())) !== null && _a !== void 0 ? _a : supabaseKey; + let headers = new HeadersConstructor(init === null || init === void 0 ? void 0 : init.headers); + if (!headers.has('apikey')) { + headers.set('apikey', supabaseKey); + } + if (!headers.has('Authorization')) { + headers.set('Authorization', `Bearer ${accessToken}`); + } + return fetch(input, Object.assign(Object.assign({}, init), { headers })); + }; +}; +exports.fetchWithAuth = fetchWithAuth; +//# sourceMappingURL=fetch.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/lib/fetch.js.map b/backend/node_modules/@supabase/supabase-js/dist/main/lib/fetch.js.map new file mode 100644 index 0000000..87634ec --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/lib/fetch.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fetch.js","sourceRoot":"","sources":["../../../src/lib/fetch.ts"],"names":[],"mappings":";;;AAEO,MAAM,YAAY,GAAG,CAAC,WAAmB,EAAS,EAAE;IACzD,IAAI,WAAW,EAAE,CAAC;QAChB,OAAO,CAAC,GAAG,IAAuB,EAAE,EAAE,CAAC,WAAW,CAAC,GAAG,IAAI,CAAC,CAAA;IAC7D,CAAC;IACD,OAAO,CAAC,GAAG,IAAuB,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,CAAA;AACvD,CAAC,CAAA;AALY,QAAA,YAAY,gBAKxB;AAEM,MAAM,yBAAyB,GAAG,GAAG,EAAE;IAC5C,OAAO,OAAO,CAAA;AAChB,CAAC,CAAA;AAFY,QAAA,yBAAyB,6BAErC;AAEM,MAAM,aAAa,GAAG,CAC3B,WAAmB,EACnB,cAA4C,EAC5C,WAAmB,EACZ,EAAE;IACT,MAAM,KAAK,GAAG,IAAA,oBAAY,EAAC,WAAW,CAAC,CAAA;IACvC,MAAM,kBAAkB,GAAG,IAAA,iCAAyB,GAAE,CAAA;IAEtD,OAAO,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,EAAE;;QAC3B,MAAM,WAAW,GAAG,MAAA,CAAC,MAAM,cAAc,EAAE,CAAC,mCAAI,WAAW,CAAA;QAC3D,IAAI,OAAO,GAAG,IAAI,kBAAkB,CAAC,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,OAAO,CAAC,CAAA;QAEnD,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC;YAC3B,OAAO,CAAC,GAAG,CAAC,QAAQ,EAAE,WAAW,CAAC,CAAA;QACpC,CAAC;QAED,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,EAAE,CAAC;YAClC,OAAO,CAAC,GAAG,CAAC,eAAe,EAAE,UAAU,WAAW,EAAE,CAAC,CAAA;QACvD,CAAC;QAED,OAAO,KAAK,CAAC,KAAK,kCAAO,IAAI,KAAE,OAAO,IAAG,CAAA;IAC3C,CAAC,CAAA;AACH,CAAC,CAAA;AAtBY,QAAA,aAAa,iBAsBzB"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/lib/helpers.d.ts b/backend/node_modules/@supabase/supabase-js/dist/main/lib/helpers.d.ts new file mode 100644 index 0000000..ea48441 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/lib/helpers.d.ts @@ -0,0 +1,14 @@ +import { SupabaseClientOptions } from './types'; +export declare function uuid(): string; +export declare function ensureTrailingSlash(url: string): string; +export declare const isBrowser: () => boolean; +export declare function applySettingDefaults(options: SupabaseClientOptions, defaults: SupabaseClientOptions): Required>; +/** + * Validates a Supabase client URL + * + * @param {string} supabaseUrl - The Supabase client URL string. + * @returns {URL} - The validated base URL. + * @throws {Error} + */ +export declare function validateSupabaseUrl(supabaseUrl: string): URL; +//# sourceMappingURL=helpers.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/lib/helpers.d.ts.map b/backend/node_modules/@supabase/supabase-js/dist/main/lib/helpers.d.ts.map new file mode 100644 index 0000000..c551894 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/lib/helpers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../../../src/lib/helpers.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,SAAS,CAAA;AAE/C,wBAAgB,IAAI,WAMnB;AAED,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAEvD;AAED,eAAO,MAAM,SAAS,eAAsC,CAAA;AAE5D,wBAAgB,oBAAoB,CAClC,QAAQ,GAAG,GAAG,EACd,UAAU,SAAS,MAAM,GAAG,MAAM,QAAQ,GAAG,QAAQ,SAAS,MAAM,QAAQ,GACxE,QAAQ,GACR,MAAM,GAAG,MAAM,QAAQ,EAE3B,OAAO,EAAE,qBAAqB,CAAC,UAAU,CAAC,EAC1C,QAAQ,EAAE,qBAAqB,CAAC,GAAG,CAAC,GACnC,QAAQ,CAAC,qBAAqB,CAAC,UAAU,CAAC,CAAC,CA+C7C;AAED;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CAAC,WAAW,EAAE,MAAM,GAAG,GAAG,CAgB5D"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/lib/helpers.js b/backend/node_modules/@supabase/supabase-js/dist/main/lib/helpers.js new file mode 100644 index 0000000..2e36bb0 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/lib/helpers.js @@ -0,0 +1,62 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isBrowser = void 0; +exports.uuid = uuid; +exports.ensureTrailingSlash = ensureTrailingSlash; +exports.applySettingDefaults = applySettingDefaults; +exports.validateSupabaseUrl = validateSupabaseUrl; +function uuid() { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { + var r = (Math.random() * 16) | 0, v = c == 'x' ? r : (r & 0x3) | 0x8; + return v.toString(16); + }); +} +function ensureTrailingSlash(url) { + return url.endsWith('/') ? url : url + '/'; +} +const isBrowser = () => typeof window !== 'undefined'; +exports.isBrowser = isBrowser; +function applySettingDefaults(options, defaults) { + var _a, _b; + const { db: dbOptions, auth: authOptions, realtime: realtimeOptions, global: globalOptions, } = options; + const { db: DEFAULT_DB_OPTIONS, auth: DEFAULT_AUTH_OPTIONS, realtime: DEFAULT_REALTIME_OPTIONS, global: DEFAULT_GLOBAL_OPTIONS, } = defaults; + const result = { + db: Object.assign(Object.assign({}, DEFAULT_DB_OPTIONS), dbOptions), + auth: Object.assign(Object.assign({}, DEFAULT_AUTH_OPTIONS), authOptions), + realtime: Object.assign(Object.assign({}, DEFAULT_REALTIME_OPTIONS), realtimeOptions), + storage: {}, + global: Object.assign(Object.assign(Object.assign({}, DEFAULT_GLOBAL_OPTIONS), globalOptions), { headers: Object.assign(Object.assign({}, ((_a = DEFAULT_GLOBAL_OPTIONS === null || DEFAULT_GLOBAL_OPTIONS === void 0 ? void 0 : DEFAULT_GLOBAL_OPTIONS.headers) !== null && _a !== void 0 ? _a : {})), ((_b = globalOptions === null || globalOptions === void 0 ? void 0 : globalOptions.headers) !== null && _b !== void 0 ? _b : {})) }), + accessToken: async () => '', + }; + if (options.accessToken) { + result.accessToken = options.accessToken; + } + else { + // hack around Required<> + delete result.accessToken; + } + return result; +} +/** + * Validates a Supabase client URL + * + * @param {string} supabaseUrl - The Supabase client URL string. + * @returns {URL} - The validated base URL. + * @throws {Error} + */ +function validateSupabaseUrl(supabaseUrl) { + const trimmedUrl = supabaseUrl === null || supabaseUrl === void 0 ? void 0 : supabaseUrl.trim(); + if (!trimmedUrl) { + throw new Error('supabaseUrl is required.'); + } + if (!trimmedUrl.match(/^https?:\/\//i)) { + throw new Error('Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.'); + } + try { + return new URL(ensureTrailingSlash(trimmedUrl)); + } + catch (_a) { + throw Error('Invalid supabaseUrl: Provided URL is malformed.'); + } +} +//# sourceMappingURL=helpers.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/lib/helpers.js.map b/backend/node_modules/@supabase/supabase-js/dist/main/lib/helpers.js.map new file mode 100644 index 0000000..602783b --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/lib/helpers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"helpers.js","sourceRoot":"","sources":["../../../src/lib/helpers.ts"],"names":[],"mappings":";;;AAGA,oBAMC;AA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,KAChB,OAAO,kCACF,CAAC,MAAA,sBAAsB,aAAtB,sBAAsB,uBAAtB,sBAAsB,CAAE,OAAO,mCAAI,EAAE,CAAC,GACvC,CAAC,MAAA,aAAa,aAAb,aAAa,uBAAb,aAAa,CAAE,OAAO,mCAAI,EAAE,CAAC,IAEpC;QACD,WAAW,EAAE,KAAK,IAAI,EAAE,CAAC,EAAE;KAC5B,CAAA;IAED,IAAI,OAAO,CAAC,WAAW,EAAE,CAAC;QACxB,MAAM,CAAC,WAAW,GAAG,OAAO,CAAC,WAAW,CAAA;IAC1C,CAAC;SAAM,CAAC;QACN,yBAAyB;QACzB,OAAQ,MAAc,CAAC,WAAW,CAAA;IACpC,CAAC;IAED,OAAO,MAAM,CAAA;AACf,CAAC;AAED;;;;;;GAMG;AACH,SAAgB,mBAAmB,CAAC,WAAmB;IACrD,MAAM,UAAU,GAAG,WAAW,aAAX,WAAW,uBAAX,WAAW,CAAE,IAAI,EAAE,CAAA;IAEtC,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAA;IAC7C,CAAC;IAED,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,eAAe,CAAC,EAAE,CAAC;QACvC,MAAM,IAAI,KAAK,CAAC,yDAAyD,CAAC,CAAA;IAC5E,CAAC;IAED,IAAI,CAAC;QACH,OAAO,IAAI,GAAG,CAAC,mBAAmB,CAAC,UAAU,CAAC,CAAC,CAAA;IACjD,CAAC;IAAC,WAAM,CAAC;QACP,MAAM,KAAK,CAAC,iDAAiD,CAAC,CAAA;IAChE,CAAC;AACH,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/lib/rest/types/common/common.d.ts b/backend/node_modules/@supabase/supabase-js/dist/main/lib/rest/types/common/common.d.ts new file mode 100644 index 0000000..3ef2294 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/lib/rest/types/common/common.d.ts @@ -0,0 +1,55 @@ +/** + * AUTO-GENERATED FILE - DO NOT EDIT + * + * This file is automatically synchronized from @supabase/postgrest-js + * Source: packages/core/postgrest-js/src/types/common/ + * + * To update this file, modify the source in postgrest-js and run: + * npm run codegen + */ +export type Fetch = typeof fetch; +export type GenericRelationship = { + foreignKeyName: string; + columns: string[]; + isOneToOne?: boolean; + referencedRelation: string; + referencedColumns: string[]; +}; +export type GenericTable = { + Row: Record; + Insert: Record; + Update: Record; + Relationships: GenericRelationship[]; +}; +export type GenericUpdatableView = { + Row: Record; + Insert: Record; + Update: Record; + Relationships: GenericRelationship[]; +}; +export type GenericNonUpdatableView = { + Row: Record; + Relationships: GenericRelationship[]; +}; +export type GenericView = GenericUpdatableView | GenericNonUpdatableView; +export type GenericSetofOption = { + isSetofReturn?: boolean | undefined; + isOneToOne?: boolean | undefined; + isNotNullable?: boolean | undefined; + to: string; + from: string; +}; +export type GenericFunction = { + Args: Record | never; + Returns: unknown; + SetofOptions?: GenericSetofOption; +}; +export type GenericSchema = { + Tables: Record; + Views: Record; + Functions: Record; +}; +export type ClientServerOptions = { + PostgrestVersion?: string; +}; +//# sourceMappingURL=common.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/lib/rest/types/common/common.d.ts.map b/backend/node_modules/@supabase/supabase-js/dist/main/lib/rest/types/common/common.d.ts.map new file mode 100644 index 0000000..edaeb4c --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/lib/rest/types/common/common.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"common.d.ts","sourceRoot":"","sources":["../../../../../../src/lib/rest/types/common/common.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAIH,MAAM,MAAM,KAAK,GAAG,OAAO,KAAK,CAAA;AAEhC,MAAM,MAAM,mBAAmB,GAAG;IAChC,cAAc,EAAE,MAAM,CAAA;IACtB,OAAO,EAAE,MAAM,EAAE,CAAA;IACjB,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB,kBAAkB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;AAED,MAAM,MAAM,aAAa,GAAG;IAC1B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,CAAA;IACpC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAA;IAClC,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,eAAe,CAAC,CAAA;CAC3C,CAAA;AAED,MAAM,MAAM,mBAAmB,GAAG;IAChC,gBAAgB,CAAC,EAAE,MAAM,CAAA;CAC1B,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/lib/rest/types/common/common.js b/backend/node_modules/@supabase/supabase-js/dist/main/lib/rest/types/common/common.js new file mode 100644 index 0000000..c0b442f --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/lib/rest/types/common/common.js @@ -0,0 +1,12 @@ +"use strict"; +/** + * AUTO-GENERATED FILE - DO NOT EDIT + * + * This file is automatically synchronized from @supabase/postgrest-js + * Source: packages/core/postgrest-js/src/types/common/ + * + * To update this file, modify the source in postgrest-js and run: + * npm run codegen + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=common.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/lib/rest/types/common/common.js.map b/backend/node_modules/@supabase/supabase-js/dist/main/lib/rest/types/common/common.js.map new file mode 100644 index 0000000..971855b --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/lib/rest/types/common/common.js.map @@ -0,0 +1 @@ +{"version":3,"file":"common.js","sourceRoot":"","sources":["../../../../../../src/lib/rest/types/common/common.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/lib/rest/types/common/rpc.d.ts b/backend/node_modules/@supabase/supabase-js/dist/main/lib/rest/types/common/rpc.d.ts new file mode 100644 index 0000000..b64297d --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/lib/rest/types/common/rpc.d.ts @@ -0,0 +1,49 @@ +/** + * AUTO-GENERATED FILE - DO NOT EDIT + * + * This file is automatically synchronized from @supabase/postgrest-js + * Source: packages/core/postgrest-js/src/types/common/ + * + * To update this file, modify the source in postgrest-js and run: + * npm run codegen + */ +import type { GenericFunction, GenericSchema, GenericSetofOption } from './common'; +type IsMatchingArgs = [FnArgs] extends [Record] ? PassedArgs extends Record ? true : false : keyof PassedArgs extends keyof FnArgs ? PassedArgs extends FnArgs ? true : false : false; +type MatchingFunctionArgs = Fn extends { + Args: infer A extends GenericFunction['Args']; +} ? IsMatchingArgs extends true ? Fn : never : false; +type FindMatchingFunctionByArgs = FnUnion extends infer Fn extends GenericFunction ? MatchingFunctionArgs : false; +type TablesAndViews = Schema['Tables'] & Exclude; +type UnionToIntersection = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never; +type LastOf = UnionToIntersection T : never> extends () => infer R ? R : never; +type IsAny = 0 extends 1 & T ? true : false; +type ExactMatch = [T] extends [S] ? ([S] extends [T] ? true : false) : false; +type ExtractExactFunction = Fns extends infer F ? F extends GenericFunction ? ExactMatch extends true ? F : never : never : never; +type IsNever = [T] extends [never] ? true : false; +type RpcFunctionNotFound = { + Row: any; + Result: { + error: true; + } & "Couldn't infer function definition matching provided arguments"; + RelationName: FnName; + Relationships: null; +}; +type CrossSchemaError = { + error: true; +} & `Function returns SETOF from a different schema ('${TableRef}'). Use .overrideTypes() to specify the return type explicitly.`; +export type GetRpcFunctionFilterBuilderByArgs = { + 0: Schema['Functions'][FnName]; + 1: IsAny extends true ? any : IsNever extends true ? IsNever> extends true ? LastOf : ExtractExactFunction : Args extends Record ? LastOf : Args extends GenericFunction['Args'] ? IsNever>> extends true ? LastOf : LastOf> : ExtractExactFunction extends GenericFunction ? ExtractExactFunction : any; +}[1] extends infer Fn ? IsAny extends true ? { + Row: any; + Result: any; + RelationName: FnName; + Relationships: null; +} : Fn extends GenericFunction ? { + Row: Fn['SetofOptions'] extends GenericSetofOption ? Fn['SetofOptions']['to'] extends keyof TablesAndViews ? TablesAndViews[Fn['SetofOptions']['to']]['Row'] : Fn['Returns'] extends any[] ? Fn['Returns'][number] extends Record ? Fn['Returns'][number] : CrossSchemaError : Fn['Returns'] extends Record ? Fn['Returns'] : CrossSchemaError : Fn['Returns'] extends any[] ? Fn['Returns'][number] extends Record ? Fn['Returns'][number] : never : Fn['Returns'] extends Record ? Fn['Returns'] : never; + Result: Fn['SetofOptions'] extends GenericSetofOption ? Fn['SetofOptions']['isSetofReturn'] extends true ? Fn['SetofOptions']['isOneToOne'] extends true ? Fn['Returns'][] : Fn['Returns'] : Fn['Returns'] : Fn['Returns']; + RelationName: Fn['SetofOptions'] extends GenericSetofOption ? Fn['SetofOptions']['to'] : FnName; + Relationships: Fn['SetofOptions'] extends GenericSetofOption ? Fn['SetofOptions']['to'] extends keyof Schema['Tables'] ? Schema['Tables'][Fn['SetofOptions']['to']]['Relationships'] : Fn['SetofOptions']['to'] extends keyof Schema['Views'] ? Schema['Views'][Fn['SetofOptions']['to']]['Relationships'] : null : null; +} : Fn extends false ? RpcFunctionNotFound : RpcFunctionNotFound : RpcFunctionNotFound; +export {}; +//# sourceMappingURL=rpc.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/lib/rest/types/common/rpc.d.ts.map b/backend/node_modules/@supabase/supabase-js/dist/main/lib/rest/types/common/rpc.d.ts.map new file mode 100644 index 0000000..ae050cc --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/lib/rest/types/common/rpc.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rpc.d.ts","sourceRoot":"","sources":["../../../../../../src/lib/rest/types/common/rpc.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,eAAe,EAAE,aAAa,EAAE,kBAAkB,EAAE,MAAM,UAAU,CAAA;AAGlF,KAAK,cAAc,CACjB,MAAM,SAAS,eAAe,CAAC,MAAM,CAAC,EACtC,UAAU,SAA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AC,SAAS,CAAC,GACf,EAAE,CAAC,SAAS,CAAC,CAAA;IACjB,YAAY,EAAE,EAAE,CAAC,cAAc,CAAC,SAAS,kBAAkB,GACvD,EAAE,CAAC,cAAc,CAAC,CAAC,IAAI,CAAC,GACxB,MAAM,CAAA;IACV,aAAa,EAAE,EAAE,CAAC,cAAc,CAAC,SAAS,kBAAkB,GACxD,EAAE,CAAC,cAAc,CAAC,CAAC,IAAI,CAAC,SAAS,MAAM,MAAM,CAAC,QAAQ,CAAC,GACrD,MAAM,CAAC,QAAQ,CAAC,CAAC,EAAE,CAAC,cAAc,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,eAAe,CAAC,GAC3D,EAAE,CAAC,cAAc,CAAC,CAAC,IAAI,CAAC,SAAS,MAAM,MAAM,CAAC,OAAO,CAAC,GACpD,MAAM,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,cAAc,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,eAAe,CAAC,GAC1D,IAAI,GACR,IAAI,CAAA;CACT,GAED,EAAE,SAAS,KAAK,GACd,mBAAmB,CAAC,MAAM,CAAC,GAC3B,mBAAmB,CAAC,MAAM,CAAC,GACjC,mBAAmB,CAAC,MAAM,CAAC,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/lib/rest/types/common/rpc.js b/backend/node_modules/@supabase/supabase-js/dist/main/lib/rest/types/common/rpc.js new file mode 100644 index 0000000..d1350e5 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/lib/rest/types/common/rpc.js @@ -0,0 +1,12 @@ +"use strict"; +/** + * AUTO-GENERATED FILE - DO NOT EDIT + * + * This file is automatically synchronized from @supabase/postgrest-js + * Source: packages/core/postgrest-js/src/types/common/ + * + * To update this file, modify the source in postgrest-js and run: + * npm run codegen + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=rpc.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/lib/rest/types/common/rpc.js.map b/backend/node_modules/@supabase/supabase-js/dist/main/lib/rest/types/common/rpc.js.map new file mode 100644 index 0000000..5352e94 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/lib/rest/types/common/rpc.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rpc.js","sourceRoot":"","sources":["../../../../../../src/lib/rest/types/common/rpc.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/lib/types.d.ts b/backend/node_modules/@supabase/supabase-js/dist/main/lib/types.d.ts new file mode 100644 index 0000000..c7cd372 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/lib/types.d.ts @@ -0,0 +1,102 @@ +import { GoTrueClientOptions } from '@supabase/auth-js'; +import { RealtimeClientOptions } from '@supabase/realtime-js'; +import { PostgrestError } from '@supabase/postgrest-js'; +import type { StorageClientOptions } from '@supabase/storage-js'; +import type { GenericSchema, GenericRelationship, GenericTable, GenericUpdatableView, GenericNonUpdatableView, GenericView, GenericFunction } from './rest/types/common/common'; +export type { GenericSchema, GenericRelationship, GenericTable, GenericUpdatableView, GenericNonUpdatableView, GenericView, GenericFunction, }; +export interface SupabaseAuthClientOptions extends GoTrueClientOptions { +} +export type Fetch = typeof fetch; +export type SupabaseClientOptions = { + /** + * The Postgres schema which your tables belong to. Must be on the list of exposed schemas in Supabase. Defaults to `public`. + */ + db?: { + schema?: SchemaName; + }; + auth?: { + /** + * Automatically refreshes the token for logged-in users. Defaults to true. + */ + autoRefreshToken?: boolean; + /** + * Optional key name used for storing tokens in local storage. + */ + storageKey?: string; + /** + * Whether to persist a logged-in session to storage. Defaults to true. + */ + persistSession?: boolean; + /** + * Detect a session from the URL. Used for OAuth login callbacks. Defaults to true. + */ + detectSessionInUrl?: boolean; + /** + * A storage provider. Used to store the logged-in session. + */ + storage?: SupabaseAuthClientOptions['storage']; + /** + * A storage provider to store the user profile separately from the session. + * Useful when you need to store the session information in cookies, + * without bloating the data with the redundant user object. + * + * @experimental + */ + userStorage?: SupabaseAuthClientOptions['userStorage']; + /** + * OAuth flow to use - defaults to implicit flow. PKCE is recommended for mobile and server-side applications. + */ + flowType?: SupabaseAuthClientOptions['flowType']; + /** + * If debug messages for authentication client are emitted. Can be used to inspect the behavior of the library. + */ + debug?: SupabaseAuthClientOptions['debug']; + /** + * Provide your own locking mechanism based on the environment. By default no locking is done at this time. + * + * @experimental + */ + lock?: SupabaseAuthClientOptions['lock']; + /** + * If there is an error with the query, throwOnError will reject the promise by + * throwing the error instead of returning it as part of a successful response. + */ + throwOnError?: SupabaseAuthClientOptions['throwOnError']; + }; + /** + * Options passed to the realtime-js instance + */ + realtime?: RealtimeClientOptions; + storage?: StorageClientOptions; + global?: { + /** + * A custom `fetch` implementation. + */ + fetch?: Fetch; + /** + * Optional headers for initializing the client. + */ + headers?: Record; + }; + /** + * Optional function for using a third-party authentication system with + * Supabase. The function should return an access token or ID token (JWT) by + * obtaining it from the third-party auth SDK. Note that this + * function may be called concurrently and many times. Use memoization and + * locking techniques if this is not supported by the SDKs. + * + * When set, the `auth` namespace of the Supabase client cannot be used. + * Create another client if you wish to use Supabase Auth and third-party + * authentications concurrently in the same application. + */ + accessToken?: () => Promise; +}; +/** + * Helper types for query results. + */ +export type QueryResult = T extends PromiseLike ? U : never; +export type QueryData = T extends PromiseLike<{ + data: infer U; +}> ? Exclude : never; +export type QueryError = PostgrestError; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/lib/types.d.ts.map b/backend/node_modules/@supabase/supabase-js/dist/main/lib/types.d.ts.map new file mode 100644 index 0000000..7c2be81 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/lib/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/lib/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM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;WAGG;QACH,YAAY,CAAC,EAAE,yBAAyB,CAAC,cAAc,CAAC,CAAA;KACzD,CAAA;IACD;;OAEG;IACH,QAAQ,CAAC,EAAE,qBAAqB,CAAA;IAChC,OAAO,CAAC,EAAE,oBAAoB,CAAA;IAC9B,MAAM,CAAC,EAAE;QACP;;WAEG;QACH,KAAK,CAAC,EAAE,KAAK,CAAA;QACb;;WAEG;QACH,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;KACjC,CAAA;IACD;;;;;;;;;;OAUG;IACH,WAAW,CAAC,EAAE,MAAM,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAA;CAC3C,CAAA;AAED;;GAEG;AACH,MAAM,MAAM,WAAW,CAAC,CAAC,IAAI,CAAC,SAAS,WAAW,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,GAAG,KAAK,CAAA;AACvE,MAAM,MAAM,SAAS,CAAC,CAAC,IAAI,CAAC,SAAS,WAAW,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC,CAAA;CAAE,CAAC,GAAG,OAAO,CAAC,CAAC,EAAE,IAAI,CAAC,GAAG,KAAK,CAAA;AAC9F,MAAM,MAAM,UAAU,GAAG,cAAc,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/lib/types.js b/backend/node_modules/@supabase/supabase-js/dist/main/lib/types.js new file mode 100644 index 0000000..11e638d --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/lib/types.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/lib/types.js.map b/backend/node_modules/@supabase/supabase-js/dist/main/lib/types.js.map new file mode 100644 index 0000000..5bb5e4d --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/lib/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/lib/types.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/lib/version.d.ts b/backend/node_modules/@supabase/supabase-js/dist/main/lib/version.d.ts new file mode 100644 index 0000000..da11aac --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/lib/version.d.ts @@ -0,0 +1,2 @@ +export declare const version = "2.87.1"; +//# sourceMappingURL=version.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/lib/version.d.ts.map b/backend/node_modules/@supabase/supabase-js/dist/main/lib/version.d.ts.map new file mode 100644 index 0000000..a4c2b72 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/lib/version.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,OAAO,WAAW,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/lib/version.js b/backend/node_modules/@supabase/supabase-js/dist/main/lib/version.js new file mode 100644 index 0000000..31bcb0a --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/lib/version.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.version = void 0; +// Generated automatically during releases by scripts/update-version-files.ts +// This file provides runtime access to the package version for: +// - HTTP request headers (e.g., X-Client-Info header for API requests) +// - Debugging and support (identifying which version is running) +// - Telemetry and logging (version reporting in errors/analytics) +// - Ensuring build artifacts match the published package version +exports.version = '2.87.1'; +//# sourceMappingURL=version.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/main/lib/version.js.map b/backend/node_modules/@supabase/supabase-js/dist/main/lib/version.js.map new file mode 100644 index 0000000..e9f984c --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/main/lib/version.js.map @@ -0,0 +1 @@ +{"version":3,"file":"version.js","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":";;;AAAA,6EAA6E;AAC7E,gEAAgE;AAChE,uEAAuE;AACvE,iEAAiE;AACjE,kEAAkE;AAClE,iEAAiE;AACpD,QAAA,OAAO,GAAG,QAAQ,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/SupabaseClient.d.ts b/backend/node_modules/@supabase/supabase-js/dist/module/SupabaseClient.d.ts new file mode 100644 index 0000000..7af1b51 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/SupabaseClient.d.ts @@ -0,0 +1,139 @@ +import { FunctionsClient } from '@supabase/functions-js'; +import { PostgrestClient, type PostgrestFilterBuilder, type PostgrestQueryBuilder } from '@supabase/postgrest-js'; +import { type RealtimeChannel, type RealtimeChannelOptions, RealtimeClient } from '@supabase/realtime-js'; +import { StorageClient as SupabaseStorageClient } from '@supabase/storage-js'; +import { SupabaseAuthClient } from './lib/SupabaseAuthClient'; +import type { Fetch, GenericSchema, SupabaseClientOptions } from './lib/types'; +import { GetRpcFunctionFilterBuilderByArgs } from './lib/rest/types/common/rpc'; +/** + * Supabase Client. + * + * An isomorphic Javascript client for interacting with Postgres. + */ +export default class SupabaseClient) | { + PostgrestVersion: string; +} = 'public' extends keyof Omit ? 'public' : string & keyof Omit, SchemaName extends string & keyof Omit = SchemaNameOrClientOptions extends string & keyof Omit ? SchemaNameOrClientOptions : 'public' extends keyof Omit ? 'public' : string & keyof Omit, '__InternalSupabase'>, Schema extends Omit[SchemaName] extends GenericSchema ? Omit[SchemaName] : never = Omit[SchemaName] extends GenericSchema ? Omit[SchemaName] : never, ClientOptions extends { + PostgrestVersion: string; +} = SchemaNameOrClientOptions extends string & keyof Omit ? Database extends { + __InternalSupabase: { + PostgrestVersion: string; + }; +} ? Database['__InternalSupabase'] : { + PostgrestVersion: '12'; +} : SchemaNameOrClientOptions extends { + PostgrestVersion: string; +} ? SchemaNameOrClientOptions : never> { + protected supabaseUrl: string; + protected supabaseKey: string; + /** + * Supabase Auth allows you to create and manage user sessions for access to data that is secured by access policies. + */ + auth: SupabaseAuthClient; + realtime: RealtimeClient; + /** + * Supabase Storage allows you to manage user-generated content, such as photos or videos. + */ + storage: SupabaseStorageClient; + protected realtimeUrl: URL; + protected authUrl: URL; + protected storageUrl: URL; + protected functionsUrl: URL; + protected rest: PostgrestClient; + protected storageKey: string; + protected fetch?: Fetch; + protected changedAccessToken?: string; + protected accessToken?: () => Promise; + protected headers: Record; + /** + * Create a new client for use in the browser. + * @param supabaseUrl The unique Supabase URL which is supplied when you create a new project in your project dashboard. + * @param supabaseKey The unique Supabase Key which is supplied when you create a new project in your project dashboard. + * @param options.db.schema You can switch in between schemas. The schema needs to be on the list of exposed schemas inside Supabase. + * @param options.auth.autoRefreshToken Set to "true" if you want to automatically refresh the token before expiring. + * @param options.auth.persistSession Set to "true" if you want to automatically save the user session into local storage. + * @param options.auth.detectSessionInUrl Set to "true" if you want to automatically detects OAuth grants in the URL and signs in the user. + * @param options.realtime Options passed along to realtime-js constructor. + * @param options.storage Options passed along to the storage-js constructor. + * @param options.global.fetch A custom fetch implementation. + * @param options.global.headers Any additional headers to send with each network request. + * @example + * ```ts + * import { createClient } from '@supabase/supabase-js' + * + * const supabase = createClient('https://xyzcompany.supabase.co', 'public-anon-key') + * const { data } = await supabase.from('profiles').select('*') + * ``` + */ + constructor(supabaseUrl: string, supabaseKey: string, options?: SupabaseClientOptions); + /** + * Supabase Functions allows you to deploy and invoke edge functions. + */ + get functions(): FunctionsClient; + from(relation: TableName): PostgrestQueryBuilder; + from(relation: ViewName): PostgrestQueryBuilder; + /** + * Select a schema to query or perform an function (rpc) call. + * + * The schema needs to be on the list of exposed schemas inside Supabase. + * + * @param schema - The schema to query + */ + schema>(schema: DynamicSchema): PostgrestClient; + /** + * Perform a function call. + * + * @param fn - The function name to call + * @param args - The arguments to pass to the function call + * @param options - Named parameters + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * @param options.get - When set to `true`, the function will be called with + * read-only access mode. + * @param options.count - Count algorithm to use to count rows returned by the + * function. Only applicable for [set-returning + * functions](https://www.postgresql.org/docs/current/functions-srf.html). + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + rpc = GetRpcFunctionFilterBuilderByArgs>(fn: FnName, args?: Args, options?: { + head?: boolean; + get?: boolean; + count?: 'exact' | 'planned' | 'estimated'; + }): PostgrestFilterBuilder; + /** + * Creates a Realtime channel with Broadcast, Presence, and Postgres Changes. + * + * @param {string} name - The name of the Realtime channel. + * @param {Object} opts - The options to pass to the Realtime channel. + * + */ + channel(name: string, opts?: RealtimeChannelOptions): RealtimeChannel; + /** + * Returns all Realtime channels. + */ + getChannels(): RealtimeChannel[]; + /** + * Unsubscribes and removes Realtime channel from Realtime client. + * + * @param {RealtimeChannel} channel - The name of the Realtime channel. + * + */ + removeChannel(channel: RealtimeChannel): Promise<'ok' | 'timed out' | 'error'>; + /** + * Unsubscribes and removes all Realtime channels from Realtime client. + */ + removeAllChannels(): Promise<('ok' | 'timed out' | 'error')[]>; + private _getAccessToken; + private _initSupabaseAuthClient; + private _initRealtimeClient; + private _listenForAuthEvents; + private _handleTokenChanged; +} +//# sourceMappingURL=SupabaseClient.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/SupabaseClient.d.ts.map b/backend/node_modules/@supabase/supabase-js/dist/module/SupabaseClient.d.ts.map new file mode 100644 index 0000000..a90e30f --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/SupabaseClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"SupabaseClient.d.ts","sourceRoot":"","sources":["../../src/SupabaseClient.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAA;AACxD,OAAO,EACL,e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aAAa,SAAS,iCAAiC,CACrD,MAAM,EACN,MAAM,EACN,IAAI,CACL,GAAG,iCAAiC,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,CAAC,EAE3D,EAAE,EAAE,MAAM,EACV,IAAI,GAAE,IAAiB,EACvB,OAAO,GAAE;QACP,IAAI,CAAC,EAAE,OAAO,CAAA;QACd,GAAG,CAAC,EAAE,OAAO,CAAA;QACb,KAAK,CAAC,EAAE,OAAO,GAAG,SAAS,GAAG,WAAW,CAAA;KAK1C,GACA,sBAAsB,CACvB,aAAa,EACb,MAAM,EACN,aAAa,CAAC,KAAK,CAAC,EACpB,aAAa,CAAC,QAAQ,CAAC,EACvB,aAAa,CAAC,cAAc,CAAC,EAC7B,aAAa,CAAC,eAAe,CAAC,EAC9B,KAAK,CACN;IAYD;;;;;;OAMG;IACH,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,GAAE,sBAAuC,GAAG,eAAe;IAIrF;;OAEG;IACH,WAAW,IAAI,eAAe,EAAE;IAIhC;;;;;OAKG;IACH,aAAa,CAAC,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,GAAG,WAAW,GAAG,OAAO,CAAC;IAI9E;;OAEG;IACH,iBAAiB,IAAI,OAAO,CAAC,CAAC,IAAI,GAAG,WAAW,GAAG,OAAO,CAAC,EAAE,CAAC;YAIhD,eAAe;IAU7B,OAAO,CAAC,uBAAuB;IA0C/B,OAAO,CAAC,mBAAmB;IAO3B,OAAO,CAAC,oBAAoB;IAO5B,OAAO,CAAC,mBAAmB;CAiB5B"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/SupabaseClient.js b/backend/node_modules/@supabase/supabase-js/dist/module/SupabaseClient.js new file mode 100644 index 0000000..aae2558 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/SupabaseClient.js @@ -0,0 +1,232 @@ +import { FunctionsClient } from '@supabase/functions-js'; +import { PostgrestClient, } from '@supabase/postgrest-js'; +import { RealtimeClient, } from '@supabase/realtime-js'; +import { StorageClient as SupabaseStorageClient } from '@supabase/storage-js'; +import { DEFAULT_AUTH_OPTIONS, DEFAULT_DB_OPTIONS, DEFAULT_GLOBAL_OPTIONS, DEFAULT_REALTIME_OPTIONS, } from './lib/constants'; +import { fetchWithAuth } from './lib/fetch'; +import { applySettingDefaults, validateSupabaseUrl } from './lib/helpers'; +import { SupabaseAuthClient } from './lib/SupabaseAuthClient'; +/** + * Supabase Client. + * + * An isomorphic Javascript client for interacting with Postgres. + */ +export default class SupabaseClient { + /** + * Create a new client for use in the browser. + * @param supabaseUrl The unique Supabase URL which is supplied when you create a new project in your project dashboard. + * @param supabaseKey The unique Supabase Key which is supplied when you create a new project in your project dashboard. + * @param options.db.schema You can switch in between schemas. The schema needs to be on the list of exposed schemas inside Supabase. + * @param options.auth.autoRefreshToken Set to "true" if you want to automatically refresh the token before expiring. + * @param options.auth.persistSession Set to "true" if you want to automatically save the user session into local storage. + * @param options.auth.detectSessionInUrl Set to "true" if you want to automatically detects OAuth grants in the URL and signs in the user. + * @param options.realtime Options passed along to realtime-js constructor. + * @param options.storage Options passed along to the storage-js constructor. + * @param options.global.fetch A custom fetch implementation. + * @param options.global.headers Any additional headers to send with each network request. + * @example + * ```ts + * import { createClient } from '@supabase/supabase-js' + * + * const supabase = createClient('https://xyzcompany.supabase.co', 'public-anon-key') + * const { data } = await supabase.from('profiles').select('*') + * ``` + */ + constructor(supabaseUrl, supabaseKey, options) { + var _a, _b, _c; + this.supabaseUrl = supabaseUrl; + this.supabaseKey = supabaseKey; + const baseUrl = validateSupabaseUrl(supabaseUrl); + if (!supabaseKey) + throw new Error('supabaseKey is required.'); + this.realtimeUrl = new URL('realtime/v1', baseUrl); + this.realtimeUrl.protocol = this.realtimeUrl.protocol.replace('http', 'ws'); + this.authUrl = new URL('auth/v1', baseUrl); + this.storageUrl = new URL('storage/v1', baseUrl); + this.functionsUrl = new URL('functions/v1', baseUrl); + // default storage key uses the supabase project ref as a namespace + const defaultStorageKey = `sb-${baseUrl.hostname.split('.')[0]}-auth-token`; + const DEFAULTS = { + db: DEFAULT_DB_OPTIONS, + realtime: DEFAULT_REALTIME_OPTIONS, + auth: Object.assign(Object.assign({}, DEFAULT_AUTH_OPTIONS), { storageKey: defaultStorageKey }), + global: DEFAULT_GLOBAL_OPTIONS, + }; + const settings = applySettingDefaults(options !== null && options !== void 0 ? options : {}, DEFAULTS); + this.storageKey = (_a = settings.auth.storageKey) !== null && _a !== void 0 ? _a : ''; + this.headers = (_b = settings.global.headers) !== null && _b !== void 0 ? _b : {}; + if (!settings.accessToken) { + this.auth = this._initSupabaseAuthClient((_c = settings.auth) !== null && _c !== void 0 ? _c : {}, this.headers, settings.global.fetch); + } + else { + this.accessToken = settings.accessToken; + this.auth = new Proxy({}, { + get: (_, prop) => { + throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(prop)} is not possible`); + }, + }); + } + this.fetch = fetchWithAuth(supabaseKey, this._getAccessToken.bind(this), settings.global.fetch); + this.realtime = this._initRealtimeClient(Object.assign({ headers: this.headers, accessToken: this._getAccessToken.bind(this) }, settings.realtime)); + if (this.accessToken) { + // Start auth immediately to avoid race condition with channel subscriptions + this.accessToken() + .then((token) => this.realtime.setAuth(token)) + .catch((e) => console.warn('Failed to set initial Realtime auth token:', e)); + } + this.rest = new PostgrestClient(new URL('rest/v1', baseUrl).href, { + headers: this.headers, + schema: settings.db.schema, + fetch: this.fetch, + }); + this.storage = new SupabaseStorageClient(this.storageUrl.href, this.headers, this.fetch, options === null || options === void 0 ? void 0 : options.storage); + if (!settings.accessToken) { + this._listenForAuthEvents(); + } + } + /** + * Supabase Functions allows you to deploy and invoke edge functions. + */ + get functions() { + return new FunctionsClient(this.functionsUrl.href, { + headers: this.headers, + customFetch: this.fetch, + }); + } + /** + * Perform a query on a table or a view. + * + * @param relation - The table or view name to query + */ + from(relation) { + return this.rest.from(relation); + } + // NOTE: signatures must be kept in sync with PostgrestClient.schema + /** + * Select a schema to query or perform an function (rpc) call. + * + * The schema needs to be on the list of exposed schemas inside Supabase. + * + * @param schema - The schema to query + */ + schema(schema) { + return this.rest.schema(schema); + } + // NOTE: signatures must be kept in sync with PostgrestClient.rpc + /** + * Perform a function call. + * + * @param fn - The function name to call + * @param args - The arguments to pass to the function call + * @param options - Named parameters + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * @param options.get - When set to `true`, the function will be called with + * read-only access mode. + * @param options.count - Count algorithm to use to count rows returned by the + * function. Only applicable for [set-returning + * functions](https://www.postgresql.org/docs/current/functions-srf.html). + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + rpc(fn, args = {}, options = { + head: false, + get: false, + count: undefined, + }) { + return this.rest.rpc(fn, args, options); + } + /** + * Creates a Realtime channel with Broadcast, Presence, and Postgres Changes. + * + * @param {string} name - The name of the Realtime channel. + * @param {Object} opts - The options to pass to the Realtime channel. + * + */ + channel(name, opts = { config: {} }) { + return this.realtime.channel(name, opts); + } + /** + * Returns all Realtime channels. + */ + getChannels() { + return this.realtime.getChannels(); + } + /** + * Unsubscribes and removes Realtime channel from Realtime client. + * + * @param {RealtimeChannel} channel - The name of the Realtime channel. + * + */ + removeChannel(channel) { + return this.realtime.removeChannel(channel); + } + /** + * Unsubscribes and removes all Realtime channels from Realtime client. + */ + removeAllChannels() { + return this.realtime.removeAllChannels(); + } + async _getAccessToken() { + var _a, _b; + if (this.accessToken) { + return await this.accessToken(); + } + const { data } = await this.auth.getSession(); + return (_b = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) !== null && _b !== void 0 ? _b : this.supabaseKey; + } + _initSupabaseAuthClient({ autoRefreshToken, persistSession, detectSessionInUrl, storage, userStorage, storageKey, flowType, lock, debug, throwOnError, }, headers, fetch) { + const authHeaders = { + Authorization: `Bearer ${this.supabaseKey}`, + apikey: `${this.supabaseKey}`, + }; + return new SupabaseAuthClient({ + url: this.authUrl.href, + headers: Object.assign(Object.assign({}, authHeaders), headers), + storageKey: storageKey, + autoRefreshToken, + persistSession, + detectSessionInUrl, + storage, + userStorage, + flowType, + lock, + debug, + throwOnError, + fetch, + // auth checks if there is a custom authorizaiton header using this flag + // so it knows whether to return an error when getUser is called with no session + hasCustomAuthorizationHeader: Object.keys(this.headers).some((key) => key.toLowerCase() === 'authorization'), + }); + } + _initRealtimeClient(options) { + return new RealtimeClient(this.realtimeUrl.href, Object.assign(Object.assign({}, options), { params: Object.assign({ apikey: this.supabaseKey }, options === null || options === void 0 ? void 0 : options.params) })); + } + _listenForAuthEvents() { + const data = this.auth.onAuthStateChange((event, session) => { + this._handleTokenChanged(event, 'CLIENT', session === null || session === void 0 ? void 0 : session.access_token); + }); + return data; + } + _handleTokenChanged(event, source, token) { + if ((event === 'TOKEN_REFRESHED' || event === 'SIGNED_IN') && + this.changedAccessToken !== token) { + this.changedAccessToken = token; + this.realtime.setAuth(token); + } + else if (event === 'SIGNED_OUT') { + this.realtime.setAuth(); + if (source == 'STORAGE') + this.auth.signOut(); + this.changedAccessToken = undefined; + } + } +} +//# sourceMappingURL=SupabaseClient.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/SupabaseClient.js.map b/backend/node_modules/@supabase/supabase-js/dist/module/SupabaseClient.js.map new file mode 100644 index 0000000..d3e5023 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/SupabaseClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SupabaseClient.js","sourceRoot":"","sources":["../../src/SupabaseClient.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAA;AACxD,OAAO,EACL,eAAe,GAGhB,MAAM,wBAAwB,CAAA;AAC/B,OAAO,EAGL,cAAc,GAEf,MAAM,uBAAuB,CAAA;AAC9B,OA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OAAO,uBAAP,OAAO,CAAE,YAAY,CAAC,CAAA;QAClE,CAAC,CAAC,CAAA;QACF,OAAO,IAAI,CAAA;IACb,CAAC;IAEO,mBAAmB,CACzB,KAAsB,EACtB,MAA4B,EAC5B,KAAc;QAEd,IACE,CAAC,KAAK,KAAK,iBAAiB,IAAI,KAAK,KAAK,WAAW,CAAC;YACtD,IAAI,CAAC,kBAAkB,KAAK,KAAK,EACjC,CAAC;YACD,IAAI,CAAC,kBAAkB,GAAG,KAAK,CAAA;YAC/B,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,CAAA;QAC9B,CAAC;aAAM,IAAI,KAAK,KAAK,YAAY,EAAE,CAAC;YAClC,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAA;YACvB,IAAI,MAAM,IAAI,SAAS;gBAAE,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAA;YAC5C,IAAI,CAAC,kBAAkB,GAAG,SAAS,CAAA;QACrC,CAAC;IACH,CAAC;CACF"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/index.d.ts b/backend/node_modules/@supabase/supabase-js/dist/module/index.d.ts new file mode 100644 index 0000000..fb5f5dc --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/index.d.ts @@ -0,0 +1,24 @@ +import SupabaseClient from './SupabaseClient'; +import type { SupabaseClientOptions } from './lib/types'; +export * from '@supabase/auth-js'; +export type { User as AuthUser, Session as AuthSession } from '@supabase/auth-js'; +export { type PostgrestResponse, type PostgrestSingleResponse, type PostgrestMaybeSingleResponse, PostgrestError, } from '@supabase/postgrest-js'; +export { FunctionsHttpError, FunctionsFetchError, FunctionsRelayError, FunctionsError, type FunctionInvokeOptions, FunctionRegion, } from '@supabase/functions-js'; +export * from '@supabase/realtime-js'; +export { default as SupabaseClient } from './SupabaseClient'; +export type { SupabaseClientOptions, QueryResult, QueryData, QueryError } from './lib/types'; +/** + * Creates a new Supabase Client. + * + * @example + * ```ts + * import { createClient } from '@supabase/supabase-js' + * + * const supabase = createClient('https://xyzcompany.supabase.co', 'public-anon-key') + * const { data, error } = await supabase.from('profiles').select('*') + * ``` + */ +export declare const createClient: ) | { + PostgrestVersion: string; +} = "public" extends keyof Omit ? "public" : string & keyof Omit, SchemaName extends string & keyof Omit = SchemaNameOrClientOptions extends string & keyof Omit ? SchemaNameOrClientOptions : "public" extends keyof Omit ? "public" : string & keyof Omit, "__InternalSupabase">>(supabaseUrl: string, supabaseKey: string, options?: SupabaseClientOptions) => SupabaseClient; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/index.d.ts.map b/backend/node_modules/@supabase/supabase-js/dist/module/index.d.ts.map new file mode 100644 index 0000000..3926737 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,kBAAkB,CAAA;AAC7C,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAA;AAExD,cAAc,mBAAmB,CAAA;AACjC,YAAY,EAAE,IAAI,IAAI,QAAQ,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,mBAAmB,CAAA;AACjF,OAAO,EACL,KAAK,iBAAiB,EACtB,KAAK,uBAAuB,EAC5B,KAAK,4BAA4B,EACjC,cAAc,GACf,MAAM,wBAAwB,CAAA;AAC/B,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,mBAAmB,EACnB,cAAc,EACd,KAAK,qBAAqB,EAC1B,cAAc,GACf,MAAM,wBAAwB,CAAA;AAC/B,cAAc,uBAAuB,CAAA;AACrC,OAAO,EAAE,OAAO,IAAI,cAAc,EAAE,MAAM,kBAAkB,CAAA;AAC5D,YAAY,EAAE,qBAAqB,EAAE,WAAW,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AAE5F;;;;;;;;;;GAUG;AACH,eAAO,MAAM,YAAY,GACvB,QAAQ,GAAG,GAAG,EACd,yBAAyB,SACrB,CAAC,MAAM,GAAG,MAAM,IAAI,CAAC,QAAQ,EAAE,oBAAoB,CAAC,CAAC,GACrD;IAAE,gBAAgB,EAAE,MAAM,CAAA;CAAE,GAAG,QAAQ,SAAS,MAAM,IAAI,CAAC,QAAQ,EAAE,oBAAoB,CAAC,GAC1F,QAAQ,GACR,MAAM,GAAG,MAAM,IAAI,CAAC,QAAQ,EAAE,oBAAoB,CAAC,EACvD,UAAU,SAAS,MAAM,GACvB,MAAM,IAAI,CAAC,QAAQ,EAAE,oBAAoB,CAAC,GAAG,yBAAyB,SAAS,MAAM,GACrF,MAAM,IAAI,CAAC,QAAQ,EAAE,oBAAoB,CAAC,GACxC,yBAAyB,GACzB,QAAQ,SAAS,MAAM,IAAI,CAAC,QAAQ,EAAE,oBAAoB,CAAC,GACzD,QAAQ,GACR,MAAM,GAAG,MAAM,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,oBAAoB,CAAC,EAAE,oBAAoB,CAAC,EAErF,aAAa,MAAM,EACnB,aAAa,MAAM,EACnB,UAAU,qBAAqB,CAAC,UAAU,CAAC,KAC1C,cAAc,CAAC,QAAQ,EAAE,yBAAyB,EAAE,UAAU,CAMhE,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/index.js b/backend/node_modules/@supabase/supabase-js/dist/module/index.js new file mode 100644 index 0000000..ac2b6e4 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/index.js @@ -0,0 +1,48 @@ +import SupabaseClient from './SupabaseClient'; +export * from '@supabase/auth-js'; +export { PostgrestError, } from '@supabase/postgrest-js'; +export { FunctionsHttpError, FunctionsFetchError, FunctionsRelayError, FunctionsError, FunctionRegion, } from '@supabase/functions-js'; +export * from '@supabase/realtime-js'; +export { default as SupabaseClient } from './SupabaseClient'; +/** + * Creates a new Supabase Client. + * + * @example + * ```ts + * import { createClient } from '@supabase/supabase-js' + * + * const supabase = createClient('https://xyzcompany.supabase.co', 'public-anon-key') + * const { data, error } = await supabase.from('profiles').select('*') + * ``` + */ +export const createClient = (supabaseUrl, supabaseKey, options) => { + return new SupabaseClient(supabaseUrl, supabaseKey, options); +}; +// Check for Node.js <= 18 deprecation +function shouldShowDeprecationWarning() { + // Skip in browser environments + if (typeof window !== 'undefined') { + return false; + } + // Skip if process is not available (e.g., Edge Runtime) + if (typeof process === 'undefined') { + return false; + } + // Use dynamic property access to avoid Next.js Edge Runtime static analysis warnings + const processVersion = process['version']; + if (processVersion === undefined || processVersion === null) { + return false; + } + const versionMatch = processVersion.match(/^v(\d+)\./); + if (!versionMatch) { + return false; + } + const majorVersion = parseInt(versionMatch[1], 10); + return majorVersion <= 18; +} +if (shouldShowDeprecationWarning()) { + console.warn(`⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. ` + + `Please upgrade to Node.js 20 or later. ` + + `For more information, visit: https://github.com/orgs/supabase/discussions/37217`); +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/index.js.map b/backend/node_modules/@supabase/supabase-js/dist/module/index.js.map new file mode 100644 index 0000000..6a4b814 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,kBAAkB,CAAA;AAG7C,cAAc,mBAAmB,CAAA;AAEjC,OAAO,EAIL,cAAc,GACf,MAAM,wBAAwB,CAAA;AAC/B,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,mBAAmB,EACnB,cAAc,EAEd,cAAc,GACf,MAAM,wBAAwB,CAAA;AAC/B,cAAc,uBAAuB,CAAA;AACrC,OAAO,EAAE,OAAO,IAAI,cAAc,EAAE,MAAM,kBAAkB,CAAA;AAG5D;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,CAe1B,WAAmB,EACnB,WAAmB,EACnB,OAA2C,EACsB,EAAE;IACnE,OAAO,IAAI,cAAc,CACvB,WAAW,EACX,WAAW,EACX,OAAO,CACR,CAAA;AACH,CAAC,CAAA;AAED,sCAAsC;AACtC,SAAS,4BAA4B;IACnC,+BAA+B;IAC/B,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE,CAAC;QAClC,OAAO,KAAK,CAAA;IACd,CAAC;IAED,wDAAwD;IACxD,IAAI,OAAO,OAAO,KAAK,WAAW,EAAE,CAAC;QACnC,OAAO,KAAK,CAAA;IACd,CAAC;IAED,qFAAqF;IACrF,MAAM,cAAc,GAAI,OAAe,CAAC,SAAS,CAAC,CAAA;IAClD,IAAI,cAAc,KAAK,SAAS,IAAI,cAAc,KAAK,IAAI,EAAE,CAAC;QAC5D,OAAO,KAAK,CAAA;IACd,CAAC;IAED,MAAM,YAAY,GAAG,cAAc,CAAC,KAAK,CAAC,WAAW,CAAC,CAAA;IACtD,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,OAAO,KAAK,CAAA;IACd,CAAC;IAED,MAAM,YAAY,GAAG,QAAQ,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAA;IAClD,OAAO,YAAY,IAAI,EAAE,CAAA;AAC3B,CAAC;AAED,IAAI,4BAA4B,EAAE,EAAE,CAAC;IACnC,OAAO,CAAC,IAAI,CACV,uHAAuH;QACrH,yCAAyC;QACzC,iFAAiF,CACpF,CAAA;AACH,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/lib/SupabaseAuthClient.d.ts b/backend/node_modules/@supabase/supabase-js/dist/module/lib/SupabaseAuthClient.d.ts new file mode 100644 index 0000000..a83dd57 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/lib/SupabaseAuthClient.d.ts @@ -0,0 +1,6 @@ +import { AuthClient } from '@supabase/auth-js'; +import { SupabaseAuthClientOptions } from './types'; +export declare class SupabaseAuthClient extends AuthClient { + constructor(options: SupabaseAuthClientOptions); +} +//# sourceMappingURL=SupabaseAuthClient.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/lib/SupabaseAuthClient.d.ts.map b/backend/node_modules/@supabase/supabase-js/dist/module/lib/SupabaseAuthClient.d.ts.map new file mode 100644 index 0000000..7d17122 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/lib/SupabaseAuthClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"SupabaseAuthClient.d.ts","sourceRoot":"","sources":["../../../src/lib/SupabaseAuthClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAA;AAC9C,OAAO,EAAE,yBAAyB,EAAE,MAAM,SAAS,CAAA;AAEnD,qBAAa,kBAAmB,SAAQ,UAAU;gBACpC,OAAO,EAAE,yBAAyB;CAG/C"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/lib/SupabaseAuthClient.js b/backend/node_modules/@supabase/supabase-js/dist/module/lib/SupabaseAuthClient.js new file mode 100644 index 0000000..16fc8c1 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/lib/SupabaseAuthClient.js @@ -0,0 +1,7 @@ +import { AuthClient } from '@supabase/auth-js'; +export class SupabaseAuthClient extends AuthClient { + constructor(options) { + super(options); + } +} +//# sourceMappingURL=SupabaseAuthClient.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/lib/SupabaseAuthClient.js.map b/backend/node_modules/@supabase/supabase-js/dist/module/lib/SupabaseAuthClient.js.map new file mode 100644 index 0000000..b747047 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/lib/SupabaseAuthClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SupabaseAuthClient.js","sourceRoot":"","sources":["../../../src/lib/SupabaseAuthClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAA;AAG9C,MAAM,OAAO,kBAAmB,SAAQ,UAAU;IAChD,YAAY,OAAkC;QAC5C,KAAK,CAAC,OAAO,CAAC,CAAA;IAChB,CAAC;CACF"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/lib/constants.d.ts b/backend/node_modules/@supabase/supabase-js/dist/module/lib/constants.d.ts new file mode 100644 index 0000000..fbea59d --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/lib/constants.d.ts @@ -0,0 +1,16 @@ +import { RealtimeClientOptions } from '@supabase/realtime-js'; +import { SupabaseAuthClientOptions } from './types'; +export declare const DEFAULT_HEADERS: { + 'X-Client-Info': string; +}; +export declare const DEFAULT_GLOBAL_OPTIONS: { + headers: { + 'X-Client-Info': string; + }; +}; +export declare const DEFAULT_DB_OPTIONS: { + schema: string; +}; +export declare const DEFAULT_AUTH_OPTIONS: SupabaseAuthClientOptions; +export declare const DEFAULT_REALTIME_OPTIONS: RealtimeClientOptions; +//# sourceMappingURL=constants.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/lib/constants.d.ts.map b/backend/node_modules/@supabase/supabase-js/dist/module/lib/constants.d.ts.map new file mode 100644 index 0000000..1d8e842 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/lib/constants.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAA;AAC7D,OAAO,EAAE,yBAAyB,EAAE,MAAM,SAAS,CAAA;AAenD,eAAO,MAAM,eAAe;;CAA0D,CAAA;AAEtF,eAAO,MAAM,sBAAsB;;;;CAElC,CAAA;AAED,eAAO,MAAM,kBAAkB;;CAE9B,CAAA;AAED,eAAO,MAAM,oBAAoB,EAAE,yBAKlC,CAAA;AAED,eAAO,MAAM,wBAAwB,EAAE,qBAA0B,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/lib/constants.js b/backend/node_modules/@supabase/supabase-js/dist/module/lib/constants.js new file mode 100644 index 0000000..13953f8 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/lib/constants.js @@ -0,0 +1,30 @@ +import { version } from './version'; +let JS_ENV = ''; +// @ts-ignore +if (typeof Deno !== 'undefined') { + JS_ENV = 'deno'; +} +else if (typeof document !== 'undefined') { + JS_ENV = 'web'; +} +else if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') { + JS_ENV = 'react-native'; +} +else { + JS_ENV = 'node'; +} +export const DEFAULT_HEADERS = { 'X-Client-Info': `supabase-js-${JS_ENV}/${version}` }; +export const DEFAULT_GLOBAL_OPTIONS = { + headers: DEFAULT_HEADERS, +}; +export const DEFAULT_DB_OPTIONS = { + schema: 'public', +}; +export const DEFAULT_AUTH_OPTIONS = { + autoRefreshToken: true, + persistSession: true, + detectSessionInUrl: true, + flowType: 'implicit', +}; +export const DEFAULT_REALTIME_OPTIONS = {}; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/lib/constants.js.map b/backend/node_modules/@supabase/supabase-js/dist/module/lib/constants.js.map new file mode 100644 index 0000000..e3ade90 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/lib/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AAEnC,IAAI,MAAM,GAAG,EAAE,CAAA;AACf,aAAa;AACb,IAAI,OAAO,IAAI,KAAK,WAAW,EAAE,CAAC;IAChC,MAAM,GAAG,MAAM,CAAA;AACjB,CAAC;KAAM,IAAI,OAAO,QAAQ,KAAK,WAAW,EAAE,CAAC;IAC3C,MAAM,GAAG,KAAK,CAAA;AAChB,CAAC;KAAM,IAAI,OAAO,SAAS,KAAK,WAAW,IAAI,SAAS,CAAC,OAAO,KAAK,aAAa,EAAE,CAAC;IACnF,MAAM,GAAG,cAAc,CAAA;AACzB,CAAC;KAAM,CAAC;IACN,MAAM,GAAG,MAAM,CAAA;AACjB,CAAC;AAED,MAAM,CAAC,MAAM,eAAe,GAAG,EAAE,eAAe,EAAE,eAAe,MAAM,IAAI,OAAO,EAAE,EAAE,CAAA;AAEtF,MAAM,CAAC,MAAM,sBAAsB,GAAG;IACpC,OAAO,EAAE,eAAe;CACzB,CAAA;AAED,MAAM,CAAC,MAAM,kBAAkB,GAAG;IAChC,MAAM,EAAE,QAAQ;CACjB,CAAA;AAED,MAAM,CAAC,MAAM,oBAAoB,GAA8B;IAC7D,gBAAgB,EAAE,IAAI;IACtB,cAAc,EAAE,IAAI;IACpB,kBAAkB,EAAE,IAAI;IACxB,QAAQ,EAAE,UAAU;CACrB,CAAA;AAED,MAAM,CAAC,MAAM,wBAAwB,GAA0B,EAAE,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/lib/fetch.d.ts b/backend/node_modules/@supabase/supabase-js/dist/module/lib/fetch.d.ts new file mode 100644 index 0000000..363e38d --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/lib/fetch.d.ts @@ -0,0 +1,9 @@ +type Fetch = typeof fetch; +export declare const resolveFetch: (customFetch?: Fetch) => Fetch; +export declare const resolveHeadersConstructor: () => { + new (init?: HeadersInit): Headers; + prototype: Headers; +}; +export declare const fetchWithAuth: (supabaseKey: string, getAccessToken: () => Promise, customFetch?: Fetch) => Fetch; +export {}; +//# sourceMappingURL=fetch.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/lib/fetch.d.ts.map b/backend/node_modules/@supabase/supabase-js/dist/module/lib/fetch.d.ts.map new file mode 100644 index 0000000..16826ba --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/lib/fetch.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../../../src/lib/fetch.ts"],"names":[],"mappings":"AAAA,KAAK,KAAK,GAAG,OAAO,KAAK,CAAA;AAEzB,eAAO,MAAM,YAAY,GAAI,cAAc,KAAK,KAAG,KAKlD,CAAA;AAED,eAAO,MAAM,yBAAyB;;;CAErC,CAAA;AAED,eAAO,MAAM,aAAa,GACxB,aAAa,MAAM,EACnB,gBAAgB,MAAM,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,EAC5C,cAAc,KAAK,KAClB,KAkBF,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/lib/fetch.js b/backend/node_modules/@supabase/supabase-js/dist/module/lib/fetch.js new file mode 100644 index 0000000..137f392 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/lib/fetch.js @@ -0,0 +1,26 @@ +export const resolveFetch = (customFetch) => { + if (customFetch) { + return (...args) => customFetch(...args); + } + return (...args) => fetch(...args); +}; +export const resolveHeadersConstructor = () => { + return Headers; +}; +export const fetchWithAuth = (supabaseKey, getAccessToken, customFetch) => { + const fetch = resolveFetch(customFetch); + const HeadersConstructor = resolveHeadersConstructor(); + return async (input, init) => { + var _a; + const accessToken = (_a = (await getAccessToken())) !== null && _a !== void 0 ? _a : supabaseKey; + let headers = new HeadersConstructor(init === null || init === void 0 ? void 0 : init.headers); + if (!headers.has('apikey')) { + headers.set('apikey', supabaseKey); + } + if (!headers.has('Authorization')) { + headers.set('Authorization', `Bearer ${accessToken}`); + } + return fetch(input, Object.assign(Object.assign({}, init), { headers })); + }; +}; +//# sourceMappingURL=fetch.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/lib/fetch.js.map b/backend/node_modules/@supabase/supabase-js/dist/module/lib/fetch.js.map new file mode 100644 index 0000000..666eeaf --- /dev/null +++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AAC;QAED,OAAO,KAAK,CAAC,KAAK,kCAAO,IAAI,KAAE,OAAO,IAAG,CAAA;IAC3C,CAAC,CAAA;AACH,CAAC,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/lib/helpers.d.ts b/backend/node_modules/@supabase/supabase-js/dist/module/lib/helpers.d.ts new file mode 100644 index 0000000..ea48441 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/lib/helpers.d.ts @@ -0,0 +1,14 @@ +import { SupabaseClientOptions } from './types'; +export declare function uuid(): string; +export declare function ensureTrailingSlash(url: string): string; +export declare const isBrowser: () => boolean; +export declare function applySettingDefaults(options: SupabaseClientOptions, defaults: SupabaseClientOptions): Required>; +/** + * Validates a Supabase client URL + * + * @param {string} supabaseUrl - The Supabase client URL string. + * @returns {URL} - The validated base URL. + * @throws {Error} + */ +export declare function validateSupabaseUrl(supabaseUrl: string): URL; +//# sourceMappingURL=helpers.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/lib/helpers.d.ts.map b/backend/node_modules/@supabase/supabase-js/dist/module/lib/helpers.d.ts.map new file mode 100644 index 0000000..c551894 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/lib/helpers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../../../src/lib/helpers.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,SAAS,CAAA;AAE/C,wBAAgB,IAAI,WAMnB;AAED,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAEvD;AAED,eAAO,MAAM,SAAS,eAAsC,CAAA;AAE5D,wBAAgB,oBAAoB,CAClC,QAAQ,GAAG,GAAG,EACd,UAAU,SAAS,MAAM,GAAG,MAAM,QAAQ,GAAG,QAAQ,SAAS,MAAM,QAAQ,GACxE,QAAQ,GACR,MAAM,GAAG,MAAM,QAAQ,EAE3B,OAAO,EAAE,qBAAqB,CAAC,UAAU,CAAC,EAC1C,QAAQ,EAAE,qBAAqB,CAAC,GAAG,CAAC,GACnC,QAAQ,CAAC,qBAAqB,CAAC,UAAU,CAAC,CAAC,CA+C7C;AAED;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CAAC,WAAW,EAAE,MAAM,GAAG,GAAG,CAgB5D"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/lib/helpers.js b/backend/node_modules/@supabase/supabase-js/dist/module/lib/helpers.js new file mode 100644 index 0000000..cdde9d8 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/lib/helpers.js @@ -0,0 +1,54 @@ +export function uuid() { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { + var r = (Math.random() * 16) | 0, v = c == 'x' ? r : (r & 0x3) | 0x8; + return v.toString(16); + }); +} +export function ensureTrailingSlash(url) { + return url.endsWith('/') ? url : url + '/'; +} +export const isBrowser = () => typeof window !== 'undefined'; +export function applySettingDefaults(options, defaults) { + var _a, _b; + const { db: dbOptions, auth: authOptions, realtime: realtimeOptions, global: globalOptions, } = options; + const { db: DEFAULT_DB_OPTIONS, auth: DEFAULT_AUTH_OPTIONS, realtime: DEFAULT_REALTIME_OPTIONS, global: DEFAULT_GLOBAL_OPTIONS, } = defaults; + const result = { + db: Object.assign(Object.assign({}, DEFAULT_DB_OPTIONS), dbOptions), + auth: Object.assign(Object.assign({}, DEFAULT_AUTH_OPTIONS), authOptions), + realtime: Object.assign(Object.assign({}, DEFAULT_REALTIME_OPTIONS), realtimeOptions), + storage: {}, + global: Object.assign(Object.assign(Object.assign({}, DEFAULT_GLOBAL_OPTIONS), globalOptions), { headers: Object.assign(Object.assign({}, ((_a = DEFAULT_GLOBAL_OPTIONS === null || DEFAULT_GLOBAL_OPTIONS === void 0 ? void 0 : DEFAULT_GLOBAL_OPTIONS.headers) !== null && _a !== void 0 ? _a : {})), ((_b = globalOptions === null || globalOptions === void 0 ? void 0 : globalOptions.headers) !== null && _b !== void 0 ? _b : {})) }), + accessToken: async () => '', + }; + if (options.accessToken) { + result.accessToken = options.accessToken; + } + else { + // hack around Required<> + delete result.accessToken; + } + return result; +} +/** + * Validates a Supabase client URL + * + * @param {string} supabaseUrl - The Supabase client URL string. + * @returns {URL} - The validated base URL. + * @throws {Error} + */ +export function validateSupabaseUrl(supabaseUrl) { + const trimmedUrl = supabaseUrl === null || supabaseUrl === void 0 ? void 0 : supabaseUrl.trim(); + if (!trimmedUrl) { + throw new Error('supabaseUrl is required.'); + } + if (!trimmedUrl.match(/^https?:\/\//i)) { + throw new Error('Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.'); + } + try { + return new URL(ensureTrailingSlash(trimmedUrl)); + } + catch (_a) { + throw Error('Invalid supabaseUrl: Provided URL is malformed.'); + } +} +//# sourceMappingURL=helpers.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/lib/helpers.js.map b/backend/node_modules/@supabase/supabase-js/dist/module/lib/helpers.js.map new file mode 100644 index 0000000..e13ef48 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/lib/helpers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"helpers.js","sourceRoot":"","sources":["../../../src/lib/helpers.ts"],"names":[],"mappings":"AAGA,MAAM,UAAU,IAAI;IAClB,OAAO,sCAAsC,CAAC,OAAO,CAAC,OAAO,EAAE,UAAU,CAAC;QACxE,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,EAC9B,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,GAAG,GAAG,CAAA;QACpC,OAAO,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAA;IACvB,CAAC,CAAC,CAAA;AACJ,CAAC;AAED,MAA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ED,OAAO,MAAM,CAAA;AACf,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,mBAAmB,CAAC,WAAmB;IACrD,MAAM,UAAU,GAAG,WAAW,aAAX,WAAW,uBAAX,WAAW,CAAE,IAAI,EAAE,CAAA;IAEtC,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAA;IAC7C,CAAC;IAED,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,eAAe,CAAC,EAAE,CAAC;QACvC,MAAM,IAAI,KAAK,CAAC,yDAAyD,CAAC,CAAA;IAC5E,CAAC;IAED,IAAI,CAAC;QACH,OAAO,IAAI,GAAG,CAAC,mBAAmB,CAAC,UAAU,CAAC,CAAC,CAAA;IACjD,CAAC;IAAC,WAAM,CAAC;QACP,MAAM,KAAK,CAAC,iDAAiD,CAAC,CAAA;IAChE,CAAC;AACH,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/lib/rest/types/common/common.d.ts b/backend/node_modules/@supabase/supabase-js/dist/module/lib/rest/types/common/common.d.ts new file mode 100644 index 0000000..3ef2294 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/lib/rest/types/common/common.d.ts @@ -0,0 +1,55 @@ +/** + * AUTO-GENERATED FILE - DO NOT EDIT + * + * This file is automatically synchronized from @supabase/postgrest-js + * Source: packages/core/postgrest-js/src/types/common/ + * + * To update this file, modify the source in postgrest-js and run: + * npm run codegen + */ +export type Fetch = typeof fetch; +export type GenericRelationship = { + foreignKeyName: string; + columns: string[]; + isOneToOne?: boolean; + referencedRelation: string; + referencedColumns: string[]; +}; +export type GenericTable = { + Row: Record; + Insert: Record; + Update: Record; + Relationships: GenericRelationship[]; +}; +export type GenericUpdatableView = { + Row: Record; + Insert: Record; + Update: Record; + Relationships: GenericRelationship[]; +}; +export type GenericNonUpdatableView = { + Row: Record; + Relationships: GenericRelationship[]; +}; +export type GenericView = GenericUpdatableView | GenericNonUpdatableView; +export type GenericSetofOption = { + isSetofReturn?: boolean | undefined; + isOneToOne?: boolean | undefined; + isNotNullable?: boolean | undefined; + to: string; + from: string; +}; +export type GenericFunction = { + Args: Record | never; + Returns: unknown; + SetofOptions?: GenericSetofOption; +}; +export type GenericSchema = { + Tables: Record; + Views: Record; + Functions: Record; +}; +export type ClientServerOptions = { + PostgrestVersion?: string; +}; +//# sourceMappingURL=common.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/lib/rest/types/common/common.d.ts.map b/backend/node_modules/@supabase/supabase-js/dist/module/lib/rest/types/common/common.d.ts.map new file mode 100644 index 0000000..edaeb4c --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/lib/rest/types/common/common.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"common.d.ts","sourceRoot":"","sources":["../../../../../../src/lib/rest/types/common/common.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAIH,MAAM,MAAM,KAAK,GAAG,OAAO,KAAK,CAAA;AAEhC,MAAM,MAAM,mBAAmB,GAAG;IAChC,cAAc,EAAE,MAAM,CAAA;IACtB,OAAO,EAAE,MAAM,EAAE,CAAA;IACjB,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB,kBAAkB,EAAE,MAAM,CAAA;IAC1B,iBAAiB,EAAE,MAAM,EAAE,CAAA;CAC5B,CAAA;AAED,MAAM,MAAM,YAAY,GAAG;IACzB,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC5B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC/B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC/B,aAAa,EAAE,mBAAmB,EAAE,CAAA;CACrC,CAAA;AAED,MAAM,MAAM,oBAAoB,GAAG;IACjC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC5B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC/B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC/B,aAAa,EAAE,mBAAmB,EAAE,CAAA;CACrC,CAAA;AAED,MAAM,MAAM,uBAAuB,GAAG;IACpC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC5B,aAAa,EAAE,mBAAmB,EAAE,CAAA;CACrC,CAAA;AAED,MAAM,MAAM,WAAW,GAAG,oBAAoB,GAAG,uBAAuB,CAAA;AAExE,MAAM,MAAM,kBAAkB,GAAG;IAC/B,aAAa,CAAC,EAAE,OAAO,GAAG,SAAS,CAAA;IACnC,UAAU,CAAC,EAAE,OAAO,GAAG,SAAS,CAAA;IAChC,aAAa,CAAC,EAAE,OAAO,GAAG,SAAS,CAAA;IACnC,EAAE,EAAE,MAAM,CAAA;IACV,IAAI,EAAE,MAAM,CAAA;CACb,CAAA;AAED,MAAM,MAAM,eAAe,GAAG;IAC5B,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,KAAK,CAAA;IACrC,OAAO,EAAE,OAAO,CAAA;IAChB,YAAY,CAAC,EAAE,kBAAkB,CAAA;CAClC,CAAA;AAED,MAAM,MAAM,aAAa,GAAG;IAC1B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,CAAA;IACpC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAA;IAClC,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,eAAe,CAAC,CAAA;CAC3C,CAAA;AAED,MAAM,MAAM,mBAAmB,GAAG;IAChC,gBAAgB,CAAC,EAAE,MAAM,CAAA;CAC1B,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/lib/rest/types/common/common.js b/backend/node_modules/@supabase/supabase-js/dist/module/lib/rest/types/common/common.js new file mode 100644 index 0000000..42dfdde --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/lib/rest/types/common/common.js @@ -0,0 +1,11 @@ +/** + * AUTO-GENERATED FILE - DO NOT EDIT + * + * This file is automatically synchronized from @supabase/postgrest-js + * Source: packages/core/postgrest-js/src/types/common/ + * + * To update this file, modify the source in postgrest-js and run: + * npm run codegen + */ +export {}; +//# sourceMappingURL=common.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/lib/rest/types/common/common.js.map b/backend/node_modules/@supabase/supabase-js/dist/module/lib/rest/types/common/common.js.map new file mode 100644 index 0000000..9e55652 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/lib/rest/types/common/common.js.map @@ -0,0 +1 @@ +{"version":3,"file":"common.js","sourceRoot":"","sources":["../../../../../../src/lib/rest/types/common/common.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/lib/rest/types/common/rpc.d.ts b/backend/node_modules/@supabase/supabase-js/dist/module/lib/rest/types/common/rpc.d.ts new file mode 100644 index 0000000..b64297d --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/lib/rest/types/common/rpc.d.ts @@ -0,0 +1,49 @@ +/** + * AUTO-GENERATED FILE - DO NOT EDIT + * + * This file is automatically synchronized from @supabase/postgrest-js + * Source: packages/core/postgrest-js/src/types/common/ + * + * To update this file, modify the source in postgrest-js and run: + * npm run codegen + */ +import type { GenericFunction, GenericSchema, GenericSetofOption } from './common'; +type IsMatchingArgs = [FnArgs] extends [Record] ? PassedArgs extends Record ? true : false : keyof PassedArgs extends keyof FnArgs ? PassedArgs extends FnArgs ? true : false : false; +type MatchingFunctionArgs = Fn extends { + Args: infer A extends GenericFunction['Args']; +} ? IsMatchingArgs extends true ? Fn : never : false; +type FindMatchingFunctionByArgs = FnUnion extends infer Fn extends GenericFunction ? MatchingFunctionArgs : false; +type TablesAndViews = Schema['Tables'] & Exclude; +type UnionToIntersection = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never; +type LastOf = UnionToIntersection T : never> extends () => infer R ? R : never; +type IsAny = 0 extends 1 & T ? true : false; +type ExactMatch = [T] extends [S] ? ([S] extends [T] ? true : false) : false; +type ExtractExactFunction = Fns extends infer F ? F extends GenericFunction ? ExactMatch extends true ? F : never : never : never; +type IsNever = [T] extends [never] ? true : false; +type RpcFunctionNotFound = { + Row: any; + Result: { + error: true; + } & "Couldn't infer function definition matching provided arguments"; + RelationName: FnName; + Relationships: null; +}; +type CrossSchemaError = { + error: true; +} & `Function returns SETOF from a different schema ('${TableRef}'). Use .overrideTypes() to specify the return type explicitly.`; +export type GetRpcFunctionFilterBuilderByArgs = { + 0: Schema['Functions'][FnName]; + 1: IsAny extends true ? any : IsNever extends true ? IsNever> extends true ? LastOf : ExtractExactFunction : Args extends Record ? LastOf : Args extends GenericFunction['Args'] ? IsNever>> extends true ? LastOf : LastOf> : ExtractExactFunction extends GenericFunction ? ExtractExactFunction : any; +}[1] extends infer Fn ? IsAny extends true ? { + Row: any; + Result: any; + RelationName: FnName; + Relationships: null; +} : Fn extends GenericFunction ? { + Row: Fn['SetofOptions'] extends GenericSetofOption ? Fn['SetofOptions']['to'] extends keyof TablesAndViews ? TablesAndViews[Fn['SetofOptions']['to']]['Row'] : Fn['Returns'] extends any[] ? Fn['Returns'][number] extends Record ? Fn['Returns'][number] : CrossSchemaError : Fn['Returns'] extends Record ? Fn['Returns'] : CrossSchemaError : Fn['Returns'] extends any[] ? Fn['Returns'][number] extends Record ? Fn['Returns'][number] : never : Fn['Returns'] extends Record ? Fn['Returns'] : never; + Result: Fn['SetofOptions'] extends GenericSetofOption ? Fn['SetofOptions']['isSetofReturn'] extends true ? Fn['SetofOptions']['isOneToOne'] extends true ? Fn['Returns'][] : Fn['Returns'] : Fn['Returns'] : Fn['Returns']; + RelationName: Fn['SetofOptions'] extends GenericSetofOption ? Fn['SetofOptions']['to'] : FnName; + Relationships: Fn['SetofOptions'] extends GenericSetofOption ? Fn['SetofOptions']['to'] extends keyof Schema['Tables'] ? Schema['Tables'][Fn['SetofOptions']['to']]['Relationships'] : Fn['SetofOptions']['to'] extends keyof Schema['Views'] ? Schema['Views'][Fn['SetofOptions']['to']]['Relationships'] : null : null; +} : Fn extends false ? RpcFunctionNotFound : RpcFunctionNotFound : RpcFunctionNotFound; +export {}; +//# sourceMappingURL=rpc.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/lib/rest/types/common/rpc.d.ts.map b/backend/node_modules/@supabase/supabase-js/dist/module/lib/rest/types/common/rpc.d.ts.map new file mode 100644 index 0000000..ae050cc --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/lib/rest/types/common/rpc.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rpc.d.ts","sourceRoot":"","sources":["../../../../../../src/lib/rest/types/common/rpc.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,eAAe,EAAE,aAAa,EAAE,kBAAkB,EAAE,MAAM,UAAU,CAAA;AAGlF,KAAK,cAAc,CACjB,MAAM,SAAS,eAAe,CAAC,MAAM,CAAC,EACtC,UAAU,SAAS,eAAe,CAAC,MAAM,CAAC,IACxC,CAAC,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,WAAW,EAAE,KAAK,CAAC,CAAC,GAC7C,UAAU,SAAS,MAAM,CAAC,WAAW,EAAE,KAAK,CAAC,GAC3C,IAAI,GACJ,KAAK,GACP,MAAM,UAAU,SAAS,MAAM,MAAM,GACnC,UAAU,SAAS,MAAM,GACvB,IAAI,GACJ,KAAK,GACP,KAAK,CAAA;AAEX,KAAK,oBAAoB,CACvB,EAAE,SAAS,eAAe,EAC1B,IAAI,SAAS,eAAe,CAAC,MAAM,CAAC,IAClC,EAAE,SAAS;IAAE,IAAI,EAAE,MAAM,CAAC,SAAS,eAAe,CAAC,MAAM,CAAC,CAAA;CAAE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AAC,SAAS,MAAM,MAAM,CAAC,OAAO,CAAC,GACpD,MAAM,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,cAAc,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,eAAe,CAAC,GAC1D,IAAI,GACR,IAAI,CAAA;CACT,GAED,EAAE,SAAS,KAAK,GACd,mBAAmB,CAAC,MAAM,CAAC,GAC3B,mBAAmB,CAAC,MAAM,CAAC,GACjC,mBAAmB,CAAC,MAAM,CAAC,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/lib/rest/types/common/rpc.js b/backend/node_modules/@supabase/supabase-js/dist/module/lib/rest/types/common/rpc.js new file mode 100644 index 0000000..8d9c150 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/lib/rest/types/common/rpc.js @@ -0,0 +1,11 @@ +/** + * AUTO-GENERATED FILE - DO NOT EDIT + * + * This file is automatically synchronized from @supabase/postgrest-js + * Source: packages/core/postgrest-js/src/types/common/ + * + * To update this file, modify the source in postgrest-js and run: + * npm run codegen + */ +export {}; +//# sourceMappingURL=rpc.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/lib/rest/types/common/rpc.js.map b/backend/node_modules/@supabase/supabase-js/dist/module/lib/rest/types/common/rpc.js.map new file mode 100644 index 0000000..5cd4873 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/lib/rest/types/common/rpc.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rpc.js","sourceRoot":"","sources":["../../../../../../src/lib/rest/types/common/rpc.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/lib/types.d.ts b/backend/node_modules/@supabase/supabase-js/dist/module/lib/types.d.ts new file mode 100644 index 0000000..c7cd372 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/lib/types.d.ts @@ -0,0 +1,102 @@ +import { GoTrueClientOptions } from '@supabase/auth-js'; +import { RealtimeClientOptions } from '@supabase/realtime-js'; +import { PostgrestError } from '@supabase/postgrest-js'; +import type { StorageClientOptions } from '@supabase/storage-js'; +import type { GenericSchema, GenericRelationship, GenericTable, GenericUpdatableView, GenericNonUpdatableView, GenericView, GenericFunction } from './rest/types/common/common'; +export type { GenericSchema, GenericRelationship, GenericTable, GenericUpdatableView, GenericNonUpdatableView, GenericView, GenericFunction, }; +export interface SupabaseAuthClientOptions extends GoTrueClientOptions { +} +export type Fetch = typeof fetch; +export type SupabaseClientOptions = { + /** + * The Postgres schema which your tables belong to. Must be on the list of exposed schemas in Supabase. Defaults to `public`. + */ + db?: { + schema?: SchemaName; + }; + auth?: { + /** + * Automatically refreshes the token for logged-in users. Defaults to true. + */ + autoRefreshToken?: boolean; + /** + * Optional key name used for storing tokens in local storage. + */ + storageKey?: string; + /** + * Whether to persist a logged-in session to storage. Defaults to true. + */ + persistSession?: boolean; + /** + * Detect a session from the URL. Used for OAuth login callbacks. Defaults to true. + */ + detectSessionInUrl?: boolean; + /** + * A storage provider. Used to store the logged-in session. + */ + storage?: SupabaseAuthClientOptions['storage']; + /** + * A storage provider to store the user profile separately from the session. + * Useful when you need to store the session information in cookies, + * without bloating the data with the redundant user object. + * + * @experimental + */ + userStorage?: SupabaseAuthClientOptions['userStorage']; + /** + * OAuth flow to use - defaults to implicit flow. PKCE is recommended for mobile and server-side applications. + */ + flowType?: SupabaseAuthClientOptions['flowType']; + /** + * If debug messages for authentication client are emitted. Can be used to inspect the behavior of the library. + */ + debug?: SupabaseAuthClientOptions['debug']; + /** + * Provide your own locking mechanism based on the environment. By default no locking is done at this time. + * + * @experimental + */ + lock?: SupabaseAuthClientOptions['lock']; + /** + * If there is an error with the query, throwOnError will reject the promise by + * throwing the error instead of returning it as part of a successful response. + */ + throwOnError?: SupabaseAuthClientOptions['throwOnError']; + }; + /** + * Options passed to the realtime-js instance + */ + realtime?: RealtimeClientOptions; + storage?: StorageClientOptions; + global?: { + /** + * A custom `fetch` implementation. + */ + fetch?: Fetch; + /** + * Optional headers for initializing the client. + */ + headers?: Record; + }; + /** + * Optional function for using a third-party authentication system with + * Supabase. The function should return an access token or ID token (JWT) by + * obtaining it from the third-party auth SDK. Note that this + * function may be called concurrently and many times. Use memoization and + * locking techniques if this is not supported by the SDKs. + * + * When set, the `auth` namespace of the Supabase client cannot be used. + * Create another client if you wish to use Supabase Auth and third-party + * authentications concurrently in the same application. + */ + accessToken?: () => Promise; +}; +/** + * Helper types for query results. + */ +export type QueryResult = T extends PromiseLike ? U : never; +export type QueryData = T extends PromiseLike<{ + data: infer U; +}> ? Exclude : never; +export type QueryError = PostgrestError; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/lib/types.d.ts.map b/backend/node_modules/@supabase/supabase-js/dist/module/lib/types.d.ts.map new file mode 100644 index 0000000..7c2be81 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/lib/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/lib/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAA;AACvD,OAAO,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAA;AAC7D,OAAO,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAA;AACvD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAA;AAChE,OAAO,KAAK,EACV,aAAa,EACb,mBAAmB,EACnB,YAAY,EACZ,oBAAoB,EACpB,uBAAuB,EACvB,WAAW,EACX,eAAe,EAChB,MAAM,4BAA4B,CAAA;AACnC,YAAY,EACV,aAAa,EACb,mBAAmB,EACnB,YAAY,EACZ,oBAAoB,EACpB,uBAAuB,EACvB,WAAW,EACX,eAAe,GAChB,CAAA;AAED,MAAM,WAAW,yBAA0B,SAAQ,mBAAmB;CAAG;AAEzE,MAAM,MAAM,KAA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S,WAAW,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,GAAG,KAAK,CAAA;AACvE,MAAM,MAAM,SAAS,CAAC,CAAC,IAAI,CAAC,SAAS,WAAW,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC,CAAA;CAAE,CAAC,GAAG,OAAO,CAAC,CAAC,EAAE,IAAI,CAAC,GAAG,KAAK,CAAA;AAC9F,MAAM,MAAM,UAAU,GAAG,cAAc,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/lib/types.js b/backend/node_modules/@supabase/supabase-js/dist/module/lib/types.js new file mode 100644 index 0000000..718fd38 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/lib/types.js @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/lib/types.js.map b/backend/node_modules/@supabase/supabase-js/dist/module/lib/types.js.map new file mode 100644 index 0000000..5bb5e4d --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/lib/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/lib/types.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/lib/version.d.ts b/backend/node_modules/@supabase/supabase-js/dist/module/lib/version.d.ts new file mode 100644 index 0000000..da11aac --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/lib/version.d.ts @@ -0,0 +1,2 @@ +export declare const version = "2.87.1"; +//# sourceMappingURL=version.d.ts.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/lib/version.d.ts.map b/backend/node_modules/@supabase/supabase-js/dist/module/lib/version.d.ts.map new file mode 100644 index 0000000..a4c2b72 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/lib/version.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,OAAO,WAAW,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/lib/version.js b/backend/node_modules/@supabase/supabase-js/dist/module/lib/version.js new file mode 100644 index 0000000..8a1c0bd --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/lib/version.js @@ -0,0 +1,8 @@ +// Generated automatically during releases by scripts/update-version-files.ts +// This file provides runtime access to the package version for: +// - HTTP request headers (e.g., X-Client-Info header for API requests) +// - Debugging and support (identifying which version is running) +// - Telemetry and logging (version reporting in errors/analytics) +// - Ensuring build artifacts match the published package version +export const version = '2.87.1'; +//# sourceMappingURL=version.js.map \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/module/lib/version.js.map b/backend/node_modules/@supabase/supabase-js/dist/module/lib/version.js.map new file mode 100644 index 0000000..b571c4f --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/module/lib/version.js.map @@ -0,0 +1 @@ +{"version":3,"file":"version.js","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,gEAAgE;AAChE,uEAAuE;AACvE,iEAAiE;AACjE,kEAAkE;AAClE,iEAAiE;AACjE,MAAM,CAAC,MAAM,OAAO,GAAG,QAAQ,CAAA"} \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/dist/umd/supabase.js b/backend/node_modules/@supabase/supabase-js/dist/umd/supabase.js new file mode 100644 index 0000000..a18d56e --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/dist/umd/supabase.js @@ -0,0 +1 @@ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.supabase=t():e.supabase=t()}(self,()=>(()=>{"use strict";var e={13:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0});const s=r(231),n=r(739),i=r(698),o=r(158),a=r(251),l=r(442),c=r(819),u=r(795);t.default=class{constructor(e,t,r){var s,i,u;this.supabaseUrl=e,this.supabaseKey=t;const h=(0,c.validateSupabaseUrl)(e);if(!t)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",h),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",h),this.storageUrl=new URL("storage/v1",h),this.functionsUrl=new URL("functions/v1",h);const d=`sb-${h.hostname.split(".")[0]}-auth-token`,f={db:a.DEFAULT_DB_OPTIONS,realtime:a.DEFAULT_REALTIME_OPTIONS,auth:Object.assign(Object.assign({},a.DEFAULT_AUTH_OPTIONS),{storageKey:d}),global:a.DEFAULT_GLOBAL_OPTIONS},p=(0,c.applySettingDefaults)(null!=r?r:{},f);this.storageKey=null!==(s=p.auth.storageKey)&&void 0!==s?s:"",this.headers=null!==(i=p.global.headers)&&void 0!==i?i:{},p.accessToken?(this.accessToken=p.accessToken,this.auth=new Proxy({},{get:(e,t)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(t)} is not possible`)}})):this.auth=this._initSupabaseAuthClient(null!==(u=p.auth)&&void 0!==u?u:{},this.headers,p.global.fetch),this.fetch=(0,l.fetchWithAuth)(t,this._getAccessToken.bind(this),p.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},p.realtime)),this.accessToken&&this.accessToken().then(e=>this.realtime.setAuth(e)).catch(e=>console.warn("Failed to set initial Realtime auth token:",e)),this.rest=new n.PostgrestClient(new URL("rest/v1",h).href,{headers:this.headers,schema:p.db.schema,fetch:this.fetch}),this.storage=new o.StorageClient(this.storageUrl.href,this.headers,this.fetch,null==r?void 0:r.storage),p.accessToken||this._listenForAuthEvents()}get functions(){return new s.FunctionsClient(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,t,r)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var e,t;if(this.accessToken)return await this.accessToken();const{data:r}=await this.auth.getSession();return null!==(t=null===(e=r.session)||void 0===e?void 0:e.access_token)&&void 0!==t?t:this.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,userStorage:n,storageKey:i,flowType:o,lock:a,debug:l,throwOnError:c},h,d){const f={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new u.SupabaseAuthClient({url:this.authUrl.href,headers:Object.assign(Object.assign({},f),h),storageKey:i,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,userStorage:n,flowType:o,lock:a,debug:l,throwOnError:c,fetch:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some(e=>"authorization"===e.toLowerCase())})}_initRealtimeClient(e){return new i.RealtimeClient(this.realtimeUrl.href,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},null==e?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,t)=>{this._handleTokenChanged(e,"CLIENT",null==t?void 0:t.access_token)})}_handleTokenChanged(e,t,r){"TOKEN_REFRESHED"!==e&&"SIGNED_IN"!==e||this.changedAccessToken===r?"SIGNED_OUT"===e&&(this.realtime.setAuth(),"STORAGE"==t&&this.auth.signOut(),this.changedAccessToken=void 0):(this.changedAccessToken=r,this.realtime.setAuth(r))}}},158:(e,t,r)=>{r.r(t),r.d(t,{StorageAnalyticsClient:()=>I,StorageApiError:()=>o,StorageClient:()=>Q,StorageError:()=>n,StorageUnknownError:()=>a,StorageVectorsApiError:()=>N,StorageVectorsClient:()=>J,StorageVectorsError:()=>C,StorageVectorsErrorCode:()=>D,StorageVectorsUnknownError:()=>U,VectorBucketApi:()=>H,VectorBucketScope:()=>z,VectorDataApi:()=>G,VectorIndexApi:()=>W,VectorIndexScope:()=>Y,isPlainObject:()=>q,isStorageError:()=>i,isStorageVectorsError:()=>x,normalizeToFloat32:()=>F,resolveFetch:()=>L,resolveResponse:()=>B,validateVectorDimension:()=>M});var s=r(823);class n extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function i(e){return"object"==typeof e&&null!==e&&"__isStorageError"in e}class o extends n{constructor(e,t,r){super(e),this.name="StorageApiError",this.status=t,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}}class a extends n{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}}const l=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),c=e=>{if(Array.isArray(e))return e.map(e=>c(e));if("function"==typeof e||e!==Object(e))return e;const t={};return Object.entries(e).forEach(([e,r])=>{const s=e.replace(/([-_][a-z])/gi,e=>e.toUpperCase().replace(/[-_]/g,""));t[s]=c(r)}),t},u=e=>{var t;return e.msg||e.message||e.error_description||("string"==typeof e.error?e.error:null===(t=e.error)||void 0===t?void 0:t.message)||JSON.stringify(e)};function h(e,t,r,n,i,l){return(0,s.__awaiter)(this,void 0,void 0,function*(){return new Promise((c,h)=>{e(r,((e,t,r,s)=>{const n={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"!==e&&s?((e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)})(s)?(n.headers=Object.assign({"Content-Type":"application/json"},null==t?void 0:t.headers),n.body=JSON.stringify(s)):n.body=s,(null==t?void 0:t.duplex)&&(n.duplex=t.duplex),Object.assign(Object.assign({},n),r)):n})(t,n,i,l)).then(e=>{if(!e.ok)throw e;return(null==n?void 0:n.noResolveJson)?e:e.json()}).then(e=>c(e)).catch(e=>((e,t,r)=>(0,s.__awaiter)(void 0,void 0,void 0,function*(){const s=yield Response;e instanceof s&&!(null==r?void 0:r.noResolveJson)?e.json().then(r=>{const s=e.status||500,n=(null==r?void 0:r.statusCode)||s+"";t(new o(u(r),s,n))}).catch(e=>{t(new a(u(e),e))}):t(new a(u(e),e))}))(e,h,n))})})}function d(e,t,r,n){return(0,s.__awaiter)(this,void 0,void 0,function*(){return h(e,"GET",t,r,n)})}function f(e,t,r,n,i){return(0,s.__awaiter)(this,void 0,void 0,function*(){return h(e,"POST",t,n,i,r)})}function p(e,t,r,n,i){return(0,s.__awaiter)(this,void 0,void 0,function*(){return h(e,"PUT",t,n,i,r)})}function g(e,t,r,n,i){return(0,s.__awaiter)(this,void 0,void 0,function*(){return h(e,"DELETE",t,n,i,r)})}class w{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}then(e,t){return this.execute().then(e,t)}execute(){return(0,s.__awaiter)(this,void 0,void 0,function*(){try{return{data:(yield this.downloadFn()).body,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(i(e))return{data:null,error:e};throw e}})}}var y;y=Symbol.toStringTag;const _=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[y]="BlobDownloadBuilder",this.promise=null}asStream(){return new w(this.downloadFn,this.shouldThrowOnError)}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}execute(){return(0,s.__awaiter)(this,void 0,void 0,function*(){try{const e=yield this.downloadFn();return{data:yield e.blob(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(i(e))return{data:null,error:e};throw e}})}},v={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},m={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class b{constructor(e,t={},r,s){this.shouldThrowOnError=!1,this.url=e,this.headers=t,this.bucketId=r,this.fetch=l(s)}throwOnError(){return this.shouldThrowOnError=!0,this}uploadOrUpdate(e,t,r,n){return(0,s.__awaiter)(this,void 0,void 0,function*(){try{let s;const i=Object.assign(Object.assign({},m),n);let o=Object.assign(Object.assign({},this.headers),"POST"===e&&{"x-upsert":String(i.upsert)});const a=i.metadata;"undefined"!=typeof Blob&&r instanceof Blob?(s=new FormData,s.append("cacheControl",i.cacheControl),a&&s.append("metadata",this.encodeMetadata(a)),s.append("",r)):"undefined"!=typeof FormData&&r instanceof FormData?(s=r,s.has("cacheControl")||s.append("cacheControl",i.cacheControl),a&&!s.has("metadata")&&s.append("metadata",this.encodeMetadata(a))):(s=r,o["cache-control"]=`max-age=${i.cacheControl}`,o["content-type"]=i.contentType,a&&(o["x-metadata"]=this.toBase64(this.encodeMetadata(a))),("undefined"!=typeof ReadableStream&&s instanceof ReadableStream||s&&"object"==typeof s&&"pipe"in s&&"function"==typeof s.pipe)&&!i.duplex&&(i.duplex="half")),(null==n?void 0:n.headers)&&(o=Object.assign(Object.assign({},o),n.headers));const l=this._removeEmptyFolders(t),c=this._getFinalPath(l),u=yield("PUT"==e?p:f)(this.fetch,`${this.url}/object/${c}`,s,Object.assign({headers:o},(null==i?void 0:i.duplex)?{duplex:i.duplex}:{}));return{data:{path:l,id:u.Id,fullPath:u.Key},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(i(e))return{data:null,error:e};throw e}})}upload(e,t,r){return(0,s.__awaiter)(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,r)})}uploadToSignedUrl(e,t,r,n){return(0,s.__awaiter)(this,void 0,void 0,function*(){const s=this._removeEmptyFolders(e),o=this._getFinalPath(s),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let e;const t=Object.assign({upsert:m.upsert},n),i=Object.assign(Object.assign({},this.headers),{"x-upsert":String(t.upsert)});return"undefined"!=typeof Blob&&r instanceof Blob?(e=new FormData,e.append("cacheControl",t.cacheControl),e.append("",r)):"undefined"!=typeof FormData&&r instanceof FormData?(e=r,e.append("cacheControl",t.cacheControl)):(e=r,i["cache-control"]=`max-age=${t.cacheControl}`,i["content-type"]=t.contentType),{data:{path:s,fullPath:(yield p(this.fetch,a.toString(),e,{headers:i})).Key},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(i(e))return{data:null,error:e};throw e}})}createSignedUploadUrl(e,t){return(0,s.__awaiter)(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e);const s=Object.assign({},this.headers);(null==t?void 0:t.upsert)&&(s["x-upsert"]="true");const i=yield f(this.fetch,`${this.url}/object/upload/sign/${r}`,{},{headers:s}),o=new URL(this.url+i.url),a=o.searchParams.get("token");if(!a)throw new n("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(i(e))return{data:null,error:e};throw e}})}update(e,t,r){return(0,s.__awaiter)(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,r)})}move(e,t,r){return(0,s.__awaiter)(this,void 0,void 0,function*(){try{return{data:yield f(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:null==r?void 0:r.destinationBucket},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(i(e))return{data:null,error:e};throw e}})}copy(e,t,r){return(0,s.__awaiter)(this,void 0,void 0,function*(){try{return{data:{path:(yield f(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:null==r?void 0:r.destinationBucket},{headers:this.headers})).Key},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(i(e))return{data:null,error:e};throw e}})}createSignedUrl(e,t,r){return(0,s.__awaiter)(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e),n=yield f(this.fetch,`${this.url}/object/sign/${s}`,Object.assign({expiresIn:t},(null==r?void 0:r.transform)?{transform:r.transform}:{}),{headers:this.headers});const i=(null==r?void 0:r.download)?`&download=${!0===r.download?"":r.download}`:"";return n={signedUrl:encodeURI(`${this.url}${n.signedURL}${i}`)},{data:n,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(i(e))return{data:null,error:e};throw e}})}createSignedUrls(e,t,r){return(0,s.__awaiter)(this,void 0,void 0,function*(){try{const s=yield f(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=(null==r?void 0:r.download)?`&download=${!0===r.download?"":r.download}`:"";return{data:s.map(e=>Object.assign(Object.assign({},e),{signedUrl:e.signedURL?encodeURI(`${this.url}${e.signedURL}${n}`):null})),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(i(e))return{data:null,error:e};throw e}})}download(e,t){const r=void 0!==(null==t?void 0:t.transform)?"render/image/authenticated":"object",s=this.transformOptsToQueryString((null==t?void 0:t.transform)||{}),n=s?`?${s}`:"",i=this._getFinalPath(e);return new _(()=>d(this.fetch,`${this.url}/${r}/${i}${n}`,{headers:this.headers,noResolveJson:!0}),this.shouldThrowOnError)}info(e){return(0,s.__awaiter)(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{const e=yield d(this.fetch,`${this.url}/object/info/${t}`,{headers:this.headers});return{data:c(e),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(i(e))return{data:null,error:e};throw e}})}exists(e){return(0,s.__awaiter)(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{return yield function(e,t,r){return(0,s.__awaiter)(this,void 0,void 0,function*(){return h(e,"HEAD",t,Object.assign(Object.assign({},r),{noResolveJson:!0}),undefined)})}(this.fetch,`${this.url}/object/${t}`,{headers:this.headers}),{data:!0,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(i(e)&&e instanceof a){const t=e.originalError;if([400,404].includes(null==t?void 0:t.status))return{data:!1,error:e}}throw e}})}getPublicUrl(e,t){const r=this._getFinalPath(e),s=[],n=(null==t?void 0:t.download)?`download=${!0===t.download?"":t.download}`:"";""!==n&&s.push(n);const i=void 0!==(null==t?void 0:t.transform)?"render/image":"object",o=this.transformOptsToQueryString((null==t?void 0:t.transform)||{});""!==o&&s.push(o);let a=s.join("&");return""!==a&&(a=`?${a}`),{data:{publicUrl:encodeURI(`${this.url}/${i}/public/${r}${a}`)}}}remove(e){return(0,s.__awaiter)(this,void 0,void 0,function*(){try{return{data:yield g(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(i(e))return{data:null,error:e};throw e}})}list(e,t,r){return(0,s.__awaiter)(this,void 0,void 0,function*(){try{const s=Object.assign(Object.assign(Object.assign({},v),t),{prefix:e||""});return{data:yield f(this.fetch,`${this.url}/object/list/${this.bucketId}`,s,{headers:this.headers},r),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(i(e))return{data:null,error:e};throw e}})}listV2(e,t){return(0,s.__awaiter)(this,void 0,void 0,function*(){try{const r=Object.assign({},e);return{data:yield f(this.fetch,`${this.url}/object/list-v2/${this.bucketId}`,r,{headers:this.headers},t),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(i(e))return{data:null,error:e};throw e}})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return"undefined"!=typeof Buffer?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){const t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}}const E="2.87.1",k={"X-Client-Info":`storage-js/${E}`};class S{constructor(e,t={},r,s){this.shouldThrowOnError=!1;const n=new URL(e);(null==s?void 0:s.useNewHostname)&&/supabase\.(co|in|red)$/.test(n.hostname)&&!n.hostname.includes("storage.supabase.")&&(n.hostname=n.hostname.replace("supabase.","storage.supabase.")),this.url=n.href.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},k),t),this.fetch=l(r)}throwOnError(){return this.shouldThrowOnError=!0,this}listBuckets(e){return(0,s.__awaiter)(this,void 0,void 0,function*(){try{const t=this.listBucketOptionsToQueryString(e);return{data:yield d(this.fetch,`${this.url}/bucket${t}`,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(i(e))return{data:null,error:e};throw e}})}getBucket(e){return(0,s.__awaiter)(this,void 0,void 0,function*(){try{return{data:yield d(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(i(e))return{data:null,error:e};throw e}})}createBucket(e){return(0,s.__awaiter)(this,arguments,void 0,function*(e,t={public:!1}){try{return{data:yield f(this.fetch,`${this.url}/bucket`,{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(i(e))return{data:null,error:e};throw e}})}updateBucket(e,t){return(0,s.__awaiter)(this,void 0,void 0,function*(){try{return{data:yield p(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(i(e))return{data:null,error:e};throw e}})}emptyBucket(e){return(0,s.__awaiter)(this,void 0,void 0,function*(){try{return{data:yield f(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(i(e))return{data:null,error:e};throw e}})}deleteBucket(e){return(0,s.__awaiter)(this,void 0,void 0,function*(){try{return{data:yield g(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(i(e))return{data:null,error:e};throw e}})}listBucketOptionsToQueryString(e){const t={};return e&&("limit"in e&&(t.limit=String(e.limit)),"offset"in e&&(t.offset=String(e.offset)),e.search&&(t.search=e.search),e.sortColumn&&(t.sortColumn=e.sortColumn),e.sortOrder&&(t.sortOrder=e.sortOrder)),Object.keys(t).length>0?"?"+new URLSearchParams(t).toString():""}}var T=class extends Error{constructor(e,t){super(e),this.name="IcebergError",this.status=t.status,this.icebergType=t.icebergType,this.icebergCode=t.icebergCode,this.details=t.details,this.isCommitStateUnknown="CommitStateUnknownException"===t.icebergType||[500,502,504].includes(t.status)&&!0===t.icebergType?.includes("CommitState")}isNotFound(){return 404===this.status}isConflict(){return 409===this.status}isAuthenticationTimeout(){return 419===this.status}};function O(e){return e.join("")}var j=class{constructor(e,t=""){this.client=e,this.prefix=t}async listNamespaces(e){const t=e?{parent:O(e.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:t})).data.namespaces.map(e=>({namespace:e}))}async createNamespace(e,t){const r={namespace:e.namespace,properties:t?.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${O(e.namespace)}`})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${O(e.namespace)}`})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${O(e.namespace)}`}),!0}catch(e){if(e instanceof T&&404===e.status)return!1;throw e}}async createNamespaceIfNotExists(e,t){try{return await this.createNamespace(e,t)}catch(e){if(e instanceof T&&409===e.status)return;throw e}}};function R(e){return e.join("")}var A=class{constructor(e,t="",r){this.client=e,this.prefix=t,this.accessDelegation=r}async listTables(e){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${R(e.namespace)}/tables`})).data.identifiers}async createTable(e,t){const r={};return this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${R(e.namespace)}/tables`,body:t,headers:r})).data.metadata}async updateTable(e,t){const r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${R(e.namespace)}/tables/${e.name}`,body:t});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(e,t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${R(e.namespace)}/tables/${e.name}`,query:{purgeRequested:String(t?.purge??!1)}})}async loadTable(e){const t={};return this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${R(e.namespace)}/tables/${e.name}`,headers:t})).data.metadata}async tableExists(e){const t={};this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${R(e.namespace)}/tables/${e.name}`,headers:t}),!0}catch(e){if(e instanceof T&&404===e.status)return!1;throw e}}async createTableIfNotExists(e,t){try{return await this.createTable(e,t)}catch(r){if(r instanceof T&&409===r.status)return await this.loadTable({namespace:e.namespace,name:t.name});throw r}}},P=class{constructor(e){let t="v1";e.catalogName&&(t+=`/${e.catalogName}`);const r=e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`;this.client=function(e){const t=e.fetchImpl??globalThis.fetch;return{async request({method:r,path:s,query:n,body:i,headers:o}){const a=function(e,t,r){const s=new URL(t,e);if(r)for(const[e,t]of Object.entries(r))void 0!==t&&s.searchParams.set(e,t);return s.toString()}(e.baseUrl,s,n),l=await async function(e){return e&&"none"!==e.type?"bearer"===e.type?{Authorization:`Bearer ${e.token}`}:"header"===e.type?{[e.name]:e.value}:"custom"===e.type?await e.getHeaders():{}:{}}(e.auth),c=await t(a,{method:r,headers:{...i?{"Content-Type":"application/json"}:{},...l,...o},body:i?JSON.stringify(i):void 0}),u=await c.text(),h=(c.headers.get("content-type")||"").includes("application/json"),d=h&&u?JSON.parse(u):u;if(!c.ok){const e=h?d:void 0,t=e?.error;throw new T(t?.message??`Request failed with status ${c.status}`,{status:c.status,icebergType:t?.type,icebergCode:t?.code,details:e})}return{status:c.status,headers:c.headers,data:d}}}}({baseUrl:r,auth:e.auth,fetchImpl:e.fetch}),this.accessDelegation=e.accessDelegation?.join(","),this.namespaceOps=new j(this.client,t),this.tableOps=new A(this.client,t,this.accessDelegation)}async listNamespaces(e){return this.namespaceOps.listNamespaces(e)}async createNamespace(e,t){return this.namespaceOps.createNamespace(e,t)}async dropNamespace(e){await this.namespaceOps.dropNamespace(e)}async loadNamespaceMetadata(e){return this.namespaceOps.loadNamespaceMetadata(e)}async listTables(e){return this.tableOps.listTables(e)}async createTable(e,t){return this.tableOps.createTable(e,t)}async updateTable(e,t){return this.tableOps.updateTable(e,t)}async dropTable(e,t){await this.tableOps.dropTable(e,t)}async loadTable(e){return this.tableOps.loadTable(e)}async namespaceExists(e){return this.namespaceOps.namespaceExists(e)}async tableExists(e){return this.tableOps.tableExists(e)}async createNamespaceIfNotExists(e,t){return this.namespaceOps.createNamespaceIfNotExists(e,t)}async createTableIfNotExists(e,t){return this.tableOps.createTableIfNotExists(e,t)}};class I{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},k),t),this.fetch=l(r)}throwOnError(){return this.shouldThrowOnError=!0,this}createBucket(e){return(0,s.__awaiter)(this,void 0,void 0,function*(){try{return{data:yield f(this.fetch,`${this.url}/bucket`,{name:e},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(i(e))return{data:null,error:e};throw e}})}listBuckets(e){return(0,s.__awaiter)(this,void 0,void 0,function*(){try{const t=new URLSearchParams;void 0!==(null==e?void 0:e.limit)&&t.set("limit",e.limit.toString()),void 0!==(null==e?void 0:e.offset)&&t.set("offset",e.offset.toString()),(null==e?void 0:e.sortColumn)&&t.set("sortColumn",e.sortColumn),(null==e?void 0:e.sortOrder)&&t.set("sortOrder",e.sortOrder),(null==e?void 0:e.search)&&t.set("search",e.search);const r=t.toString(),s=r?`${this.url}/bucket?${r}`:`${this.url}/bucket`;return{data:yield d(this.fetch,s,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(i(e))return{data:null,error:e};throw e}})}deleteBucket(e){return(0,s.__awaiter)(this,void 0,void 0,function*(){try{return{data:yield g(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(i(e))return{data:null,error:e};throw e}})}from(e){if(!(e=>!(!e||"string"!=typeof e)&&!(0===e.length||e.length>100)&&e.trim()===e&&!e.includes("/")&&!e.includes("\\")&&/^[\w!.\*'() &$@=;:+,?-]+$/.test(e))(e))throw new n("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");const t=new P({baseUrl:this.url,catalogName:e,auth:{type:"custom",getHeaders:()=>(0,s.__awaiter)(this,void 0,void 0,function*(){return this.headers})},fetch:this.fetch}),r=this.shouldThrowOnError;return new Proxy(t,{get(e,t){const n=e[t];return"function"!=typeof n?n:(...t)=>(0,s.__awaiter)(this,void 0,void 0,function*(){try{return{data:yield n.apply(e,t),error:null}}catch(e){if(r)throw e;return{data:null,error:e}}})}})}}const $={"X-Client-Info":`storage-js/${E}`,"Content-Type":"application/json"};class C extends Error{constructor(e){super(e),this.__isStorageVectorsError=!0,this.name="StorageVectorsError"}}function x(e){return"object"==typeof e&&null!==e&&"__isStorageVectorsError"in e}class N extends C{constructor(e,t,r){super(e),this.name="StorageVectorsApiError",this.status=t,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}}class U extends C{constructor(e,t){super(e),this.name="StorageVectorsUnknownError",this.originalError=t}}var D;!function(e){e.InternalError="InternalError",e.S3VectorConflictException="S3VectorConflictException",e.S3VectorNotFoundException="S3VectorNotFoundException",e.S3VectorBucketNotEmpty="S3VectorBucketNotEmpty",e.S3VectorMaxBucketsExceeded="S3VectorMaxBucketsExceeded",e.S3VectorMaxIndexesExceeded="S3VectorMaxIndexesExceeded"}(D||(D={}));const L=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),B=()=>Response,q=e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)},F=e=>Array.from(new Float32Array(e)),M=(e,t)=>{if(void 0!==t&&e.float32.length!==t)throw new Error(`Vector dimension mismatch: expected ${t}, got ${e.float32.length}`)},K=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e);function V(e,t,r,n,i){return(0,s.__awaiter)(this,void 0,void 0,function*(){return function(e,t,r,n,i,o){return(0,s.__awaiter)(this,void 0,void 0,function*(){return new Promise((a,l)=>{e(r,((e,t,r,s)=>{const n={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"!==e&&s?(q(s)?(n.headers=Object.assign({"Content-Type":"application/json"},null==t?void 0:t.headers),n.body=JSON.stringify(s)):n.body=s,Object.assign(Object.assign({},n),r)):n})(t,n,i,o)).then(e=>{if(!e.ok)throw e;if(null==n?void 0:n.noResolveJson)return e;const t=e.headers.get("content-type");return t&&t.includes("application/json")?e.json():{}}).then(e=>a(e)).catch(e=>((e,t,r)=>(0,s.__awaiter)(void 0,void 0,void 0,function*(){if(e&&"object"==typeof e&&"status"in e&&"ok"in e&&"number"==typeof e.status&&!(null==r?void 0:r.noResolveJson)){const r=e.status||500,s=e;if("function"==typeof s.json)s.json().then(e=>{const s=(null==e?void 0:e.statusCode)||(null==e?void 0:e.code)||r+"";t(new N(K(e),r,s))}).catch(()=>{const e=r+"",n=s.statusText||`HTTP ${r} error`;t(new N(n,r,e))});else{const e=r+"",n=s.statusText||`HTTP ${r} error`;t(new N(n,r,e))}}else t(new U(K(e),e))}))(e,l,n))})})}(e,"POST",t,n,i,r)})}class W{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},$),t),this.fetch=L(r)}throwOnError(){return this.shouldThrowOnError=!0,this}createIndex(e){return(0,s.__awaiter)(this,void 0,void 0,function*(){try{return{data:(yield V(this.fetch,`${this.url}/CreateIndex`,e,{headers:this.headers}))||{},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(x(e))return{data:null,error:e};throw e}})}getIndex(e,t){return(0,s.__awaiter)(this,void 0,void 0,function*(){try{return{data:yield V(this.fetch,`${this.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(x(e))return{data:null,error:e};throw e}})}listIndexes(e){return(0,s.__awaiter)(this,void 0,void 0,function*(){try{return{data:yield V(this.fetch,`${this.url}/ListIndexes`,e,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(x(e))return{data:null,error:e};throw e}})}deleteIndex(e,t){return(0,s.__awaiter)(this,void 0,void 0,function*(){try{return{data:(yield V(this.fetch,`${this.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:this.headers}))||{},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(x(e))return{data:null,error:e};throw e}})}}class G{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},$),t),this.fetch=L(r)}throwOnError(){return this.shouldThrowOnError=!0,this}putVectors(e){return(0,s.__awaiter)(this,void 0,void 0,function*(){try{if(e.vectors.length<1||e.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return{data:(yield V(this.fetch,`${this.url}/PutVectors`,e,{headers:this.headers}))||{},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(x(e))return{data:null,error:e};throw e}})}getVectors(e){return(0,s.__awaiter)(this,void 0,void 0,function*(){try{return{data:yield V(this.fetch,`${this.url}/GetVectors`,e,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(x(e))return{data:null,error:e};throw e}})}listVectors(e){return(0,s.__awaiter)(this,void 0,void 0,function*(){try{if(void 0!==e.segmentCount){if(e.segmentCount<1||e.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(void 0!==e.segmentIndex&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw new Error("segmentIndex must be between 0 and "+(e.segmentCount-1))}return{data:yield V(this.fetch,`${this.url}/ListVectors`,e,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(x(e))return{data:null,error:e};throw e}})}queryVectors(e){return(0,s.__awaiter)(this,void 0,void 0,function*(){try{return{data:yield V(this.fetch,`${this.url}/QueryVectors`,e,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(x(e))return{data:null,error:e};throw e}})}deleteVectors(e){return(0,s.__awaiter)(this,void 0,void 0,function*(){try{if(e.keys.length<1||e.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return{data:(yield V(this.fetch,`${this.url}/DeleteVectors`,e,{headers:this.headers}))||{},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(x(e))return{data:null,error:e};throw e}})}}class H{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},$),t),this.fetch=L(r)}throwOnError(){return this.shouldThrowOnError=!0,this}createBucket(e){return(0,s.__awaiter)(this,void 0,void 0,function*(){try{return{data:(yield V(this.fetch,`${this.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:this.headers}))||{},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(x(e))return{data:null,error:e};throw e}})}getBucket(e){return(0,s.__awaiter)(this,void 0,void 0,function*(){try{return{data:yield V(this.fetch,`${this.url}/GetVectorBucket`,{vectorBucketName:e},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(x(e))return{data:null,error:e};throw e}})}listBuckets(){return(0,s.__awaiter)(this,arguments,void 0,function*(e={}){try{return{data:yield V(this.fetch,`${this.url}/ListVectorBuckets`,e,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(x(e))return{data:null,error:e};throw e}})}deleteBucket(e){return(0,s.__awaiter)(this,void 0,void 0,function*(){try{return{data:(yield V(this.fetch,`${this.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:this.headers}))||{},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(x(e))return{data:null,error:e};throw e}})}}class J extends H{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new z(this.url,this.headers,e,this.fetch)}createBucket(e){const t=Object.create(null,{createBucket:{get:()=>super.createBucket}});return(0,s.__awaiter)(this,void 0,void 0,function*(){return t.createBucket.call(this,e)})}getBucket(e){const t=Object.create(null,{getBucket:{get:()=>super.getBucket}});return(0,s.__awaiter)(this,void 0,void 0,function*(){return t.getBucket.call(this,e)})}listBuckets(){const e=Object.create(null,{listBuckets:{get:()=>super.listBuckets}});return(0,s.__awaiter)(this,arguments,void 0,function*(t={}){return e.listBuckets.call(this,t)})}deleteBucket(e){const t=Object.create(null,{deleteBucket:{get:()=>super.deleteBucket}});return(0,s.__awaiter)(this,void 0,void 0,function*(){return t.deleteBucket.call(this,e)})}}class z extends W{constructor(e,t,r,s){super(e,t,s),this.vectorBucketName=r}createIndex(e){const t=Object.create(null,{createIndex:{get:()=>super.createIndex}});return(0,s.__awaiter)(this,void 0,void 0,function*(){return t.createIndex.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName}))})}listIndexes(){const e=Object.create(null,{listIndexes:{get:()=>super.listIndexes}});return(0,s.__awaiter)(this,arguments,void 0,function*(t={}){return e.listIndexes.call(this,Object.assign(Object.assign({},t),{vectorBucketName:this.vectorBucketName}))})}getIndex(e){const t=Object.create(null,{getIndex:{get:()=>super.getIndex}});return(0,s.__awaiter)(this,void 0,void 0,function*(){return t.getIndex.call(this,this.vectorBucketName,e)})}deleteIndex(e){const t=Object.create(null,{deleteIndex:{get:()=>super.deleteIndex}});return(0,s.__awaiter)(this,void 0,void 0,function*(){return t.deleteIndex.call(this,this.vectorBucketName,e)})}index(e){return new Y(this.url,this.headers,this.vectorBucketName,e,this.fetch)}}class Y extends G{constructor(e,t,r,s,n){super(e,t,n),this.vectorBucketName=r,this.indexName=s}putVectors(e){const t=Object.create(null,{putVectors:{get:()=>super.putVectors}});return(0,s.__awaiter)(this,void 0,void 0,function*(){return t.putVectors.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}getVectors(e){const t=Object.create(null,{getVectors:{get:()=>super.getVectors}});return(0,s.__awaiter)(this,void 0,void 0,function*(){return t.getVectors.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}listVectors(){const e=Object.create(null,{listVectors:{get:()=>super.listVectors}});return(0,s.__awaiter)(this,arguments,void 0,function*(t={}){return e.listVectors.call(this,Object.assign(Object.assign({},t),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}queryVectors(e){const t=Object.create(null,{queryVectors:{get:()=>super.queryVectors}});return(0,s.__awaiter)(this,void 0,void 0,function*(){return t.queryVectors.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}deleteVectors(e){const t=Object.create(null,{deleteVectors:{get:()=>super.deleteVectors}});return(0,s.__awaiter)(this,void 0,void 0,function*(){return t.deleteVectors.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}}class Q extends S{constructor(e,t={},r,s){super(e,t,r,s)}from(e){return new b(this.url,this.headers,e,this.fetch)}get vectors(){return new J(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new I(this.url+"/iceberg",this.headers,this.fetch)}}},166:(e,t,r)=>{r.r(t),r.d(t,{AuthAdminApi:()=>Me,AuthApiError:()=>f,AuthClient:()=>Ke,AuthError:()=>h,AuthImplicitGrantRedirectError:()=>b,AuthInvalidCredentialsError:()=>m,AuthInvalidJwtError:()=>R,AuthInvalidTokenResponseError:()=>v,AuthPKCEGrantCodeExchangeError:()=>k,AuthRetryableFetchError:()=>S,AuthSessionMissingError:()=>y,AuthUnknownError:()=>g,AuthWeakPasswordError:()=>O,CustomAuthError:()=>w,GoTrueAdminApi:()=>he,GoTrueClient:()=>Fe,NavigatorLockAcquireTimeoutError:()=>ge,SIGN_OUT_SCOPES:()=>ue,isAuthApiError:()=>p,isAuthError:()=>d,isAuthImplicitGrantRedirectError:()=>E,isAuthRetryableFetchError:()=>T,isAuthSessionMissingError:()=>_,isAuthWeakPasswordError:()=>j,lockInternals:()=>fe,navigatorLock:()=>ye,processLock:()=>ve});var s=r(823);const n="2.87.1",i=3e4,o={"X-Client-Info":`gotrue-js/${n}`},a="X-Supabase-Api-Version",l=Date.parse("2024-01-01T00:00:00.0Z"),c="2024-01-01",u=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i;class h extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}}function d(e){return"object"==typeof e&&null!==e&&"__isAuthError"in e}class f extends h{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}}function p(e){return d(e)&&"AuthApiError"===e.name}class g extends h{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class w extends h{constructor(e,t,r,s){super(e,r,s),this.name=t,this.status=r}}class y extends w{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function _(e){return d(e)&&"AuthSessionMissingError"===e.name}class v extends w{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class m extends w{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class b extends w{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}function E(e){return d(e)&&"AuthImplicitGrantRedirectError"===e.name}class k extends w{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class S extends w{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function T(e){return d(e)&&"AuthRetryableFetchError"===e.name}class O extends w{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}}function j(e){return d(e)&&"AuthWeakPasswordError"===e.name}class R extends w{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const A="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),P=" \t\n\r=".split(""),I=(()=>{const e=new Array(128);for(let t=0;t=6;){const e=t.queue>>t.queuedBits-6&63;r(A[e]),t.queuedBits-=6}else if(t.queuedBits>0)for(t.queue=t.queue<<6-t.queuedBits,t.queuedBits=6;t.queuedBits>=6;){const e=t.queue>>t.queuedBits-6&63;r(A[e]),t.queuedBits-=6}}function C(e,t,r){const s=I[e];if(!(s>-1)){if(-2===s)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`)}for(t.queue=t.queue<<6|s,t.queuedBits+=6;t.queuedBits>=8;)r(t.queue>>t.queuedBits-8&255),t.queuedBits-=8}function x(e){const t=[],r=e=>{t.push(String.fromCodePoint(e))},s={utf8seq:0,codepoint:0},n={queue:0,queuedBits:0},i=e=>{!function(e,t,r){if(0===t.utf8seq){if(e<=127)return void r(e);for(let r=1;r<6;r+=1)if(!(e>>7-r&1)){t.utf8seq=r;break}if(2===t.utf8seq)t.codepoint=31&e;else if(3===t.utf8seq)t.codepoint=15&e;else{if(4!==t.utf8seq)throw new Error("Invalid UTF-8 sequence");t.codepoint=7&e}t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw new Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|63&e,t.utf8seq-=1,0===t.utf8seq&&r(t.codepoint)}}(e,s,r)};for(let t=0;t>6),void t(128|63&e);if(e<=65535)return t(224|e>>12),t(128|e>>6&63),void t(128|63&e);if(e<=1114111)return t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),void t(128|63&e);throw new Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}t(e)}function U(e){const t=[],r={queue:0,queuedBits:0},s=e=>{t.push(e)};for(let t=0;t{t.push(e)};return e.forEach(e=>$(e,r,s)),$(null,r,s),t.join("")}const L=()=>"undefined"!=typeof window&&"undefined"!=typeof document,B={tested:!1,writable:!1},q=()=>{if(!L())return!1;try{if("object"!=typeof globalThis.localStorage)return!1}catch(e){return!1}if(B.tested)return B.writable;const e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),B.tested=!0,B.writable=!0}catch(e){B.tested=!0,B.writable=!1}return B.writable},F=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),M=async(e,t,r)=>{await e.setItem(t,JSON.stringify(r))},K=async(e,t)=>{const r=await e.getItem(t);if(!r)return null;try{return JSON.parse(r)}catch(e){return r}},V=async(e,t)=>{await e.removeItem(t)};class W{constructor(){this.promise=new W.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}function G(e){const t=e.split(".");if(3!==t.length)throw new R("Invalid JWT structure");for(let e=0;eString.fromCharCode(e)).join("")}(e);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}(s);return[i,s===i?"plain":"s256"]}W.promiseConstructor=Promise;const z=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i,Y=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Q(e){if(!Y.test(e))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function X(){return new Proxy({},{get:(e,t)=>{if("__isUserNotAvailableProxy"===t)return!0;if("symbol"==typeof t){const e=t.toString();if("Symbol(Symbol.toPrimitive)"===e||"Symbol(Symbol.toStringTag)"===e||"Symbol(util.inspect.custom)"===e)return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${t}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function Z(e){return JSON.parse(JSON.stringify(e))}const ee=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),te=[502,503,504];async function re(e){var t,r;if(!("object"==typeof(r=e)&&null!==r&&"status"in r&&"ok"in r&&"json"in r&&"function"==typeof r.json))throw new S(ee(e),0);if(te.includes(e.status))throw new S(ee(e),e.status);let s,n;try{s=await e.json()}catch(e){throw new g(ee(e),e)}const i=function(e){const t=e.headers.get(a);if(!t)return null;if(!t.match(z))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch(e){return null}}(e);if(i&&i.getTime()>=l&&"object"==typeof s&&s&&"string"==typeof s.code?n=s.code:"object"==typeof s&&s&&"string"==typeof s.error_code&&(n=s.error_code),n){if("weak_password"===n)throw new O(ee(s),e.status,(null===(t=s.weak_password)||void 0===t?void 0:t.reasons)||[]);if("session_not_found"===n)throw new y}else if("object"==typeof s&&s&&"object"==typeof s.weak_password&&s.weak_password&&Array.isArray(s.weak_password.reasons)&&s.weak_password.reasons.length&&s.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0))throw new O(ee(s),e.status,s.weak_password.reasons);throw new f(ee(s),e.status||500,n)}async function se(e,t,r,s){var n;const i=Object.assign({},null==s?void 0:s.headers);i[a]||(i[a]=c),(null==s?void 0:s.jwt)&&(i.Authorization=`Bearer ${s.jwt}`);const o=null!==(n=null==s?void 0:s.query)&&void 0!==n?n:{};(null==s?void 0:s.redirectTo)&&(o.redirect_to=s.redirectTo);const l=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",u=await async function(e,t,r,s,n,i){const o=((e,t,r,s)=>{const n={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"===e?n:(n.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},null==t?void 0:t.headers),n.body=JSON.stringify(s),Object.assign(Object.assign({},n),r))})(t,s,{},i);let a;try{a=await e(r,Object.assign({},o))}catch(e){throw console.error(e),new S(ee(e),0)}if(a.ok||await re(a),null==s?void 0:s.noResolveJson)return a;try{return await a.json()}catch(e){await re(e)}}(e,t,r+l,{headers:i,noResolveJson:null==s?void 0:s.noResolveJson},0,null==s?void 0:s.body);return(null==s?void 0:s.xform)?null==s?void 0:s.xform(u):{data:Object.assign({},u),error:null}}function ne(e){var t;let r=null;var s;return function(e){return e.access_token&&e.refresh_token&&e.expires_in}(e)&&(r=Object.assign({},e),e.expires_at||(r.expires_at=(s=e.expires_in,Math.round(Date.now()/1e3)+s))),{data:{session:r,user:null!==(t=e.user)&&void 0!==t?t:e},error:null}}function ie(e){const t=ne(e);return!t.error&&e.weak_password&&"object"==typeof e.weak_password&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&"string"==typeof e.weak_password.message&&e.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0)&&(t.data.weak_password=e.weak_password),t}function oe(e){var t;return{data:{user:null!==(t=e.user)&&void 0!==t?t:e},error:null}}function ae(e){return{data:e,error:null}}function le(e){const{action_link:t,email_otp:r,hashed_token:n,redirect_to:i,verification_type:o}=e,a=(0,s.__rest)(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]);return{data:{properties:{action_link:t,email_otp:r,hashed_token:n,redirect_to:i,verification_type:o},user:Object.assign({},a)},error:null}}function ce(e){return e}const ue=["global","local","others"];class he{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=F(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)}}async signOut(e,t=ue[0]){if(ue.indexOf(t)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${ue.join(", ")}`);try{return await se(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(e){if(d(e))return{data:null,error:e};throw e}}async inviteUserByEmail(e,t={}){try{return await se(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:oe})}catch(e){if(d(e))return{data:{user:null},error:e};throw e}}async generateLink(e){try{const{options:t}=e,r=(0,s.__rest)(e,["options"]),n=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(n.new_email=null==r?void 0:r.newEmail,delete n.newEmail),await se(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:le,redirectTo:null==t?void 0:t.redirectTo})}catch(e){if(d(e))return{data:{properties:null,user:null},error:e};throw e}}async createUser(e){try{return await se(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:oe})}catch(e){if(d(e))return{data:{user:null},error:e};throw e}}async listUsers(e){var t,r,s,n,i,o,a;try{const l={nextPage:null,lastPage:0,total:0},c=await se(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:null!==(r=null===(t=null==e?void 0:e.page)||void 0===t?void 0:t.toString())&&void 0!==r?r:"",per_page:null!==(n=null===(s=null==e?void 0:e.perPage)||void 0===s?void 0:s.toString())&&void 0!==n?n:""},xform:ce});if(c.error)throw c.error;const u=await c.json(),h=null!==(i=c.headers.get("x-total-count"))&&void 0!==i?i:0,d=null!==(a=null===(o=c.headers.get("link"))||void 0===o?void 0:o.split(","))&&void 0!==a?a:[];return d.length>0&&(d.forEach(e=>{const t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),r=JSON.parse(e.split(";")[1].split("=")[1]);l[`${r}Page`]=t}),l.total=parseInt(h)),{data:Object.assign(Object.assign({},u),l),error:null}}catch(e){if(d(e))return{data:{users:[]},error:e};throw e}}async getUserById(e){Q(e);try{return await se(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:oe})}catch(e){if(d(e))return{data:{user:null},error:e};throw e}}async updateUserById(e,t){Q(e);try{return await se(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:oe})}catch(e){if(d(e))return{data:{user:null},error:e};throw e}}async deleteUser(e,t=!1){Q(e);try{return await se(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:oe})}catch(e){if(d(e))return{data:{user:null},error:e};throw e}}async _listFactors(e){Q(e.userId);try{const{data:t,error:r}=await se(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:e=>({data:{factors:e},error:null})});return{data:t,error:r}}catch(e){if(d(e))return{data:null,error:e};throw e}}async _deleteFactor(e){Q(e.userId),Q(e.id);try{return{data:await se(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(e){if(d(e))return{data:null,error:e};throw e}}async _listOAuthClients(e){var t,r,s,n,i,o,a;try{const l={nextPage:null,lastPage:0,total:0},c=await se(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:null!==(r=null===(t=null==e?void 0:e.page)||void 0===t?void 0:t.toString())&&void 0!==r?r:"",per_page:null!==(n=null===(s=null==e?void 0:e.perPage)||void 0===s?void 0:s.toString())&&void 0!==n?n:""},xform:ce});if(c.error)throw c.error;const u=await c.json(),h=null!==(i=c.headers.get("x-total-count"))&&void 0!==i?i:0,d=null!==(a=null===(o=c.headers.get("link"))||void 0===o?void 0:o.split(","))&&void 0!==a?a:[];return d.length>0&&(d.forEach(e=>{const t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),r=JSON.parse(e.split(";")[1].split("=")[1]);l[`${r}Page`]=t}),l.total=parseInt(h)),{data:Object.assign(Object.assign({},u),l),error:null}}catch(e){if(d(e))return{data:{clients:[]},error:e};throw e}}async _createOAuthClient(e){try{return await se(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(d(e))return{data:null,error:e};throw e}}async _getOAuthClient(e){try{return await se(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(d(e))return{data:null,error:e};throw e}}async _updateOAuthClient(e,t){try{return await se(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(d(e))return{data:null,error:e};throw e}}async _deleteOAuthClient(e){try{return await se(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(d(e))return{data:null,error:e};throw e}}async _regenerateOAuthClientSecret(e){try{return await se(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(d(e))return{data:null,error:e};throw e}}}function de(e={}){return{getItem:t=>e[t]||null,setItem:(t,r)=>{e[t]=r},removeItem:t=>{delete e[t]}}}const fe={debug:!!(globalThis&&q()&&globalThis.localStorage&&"true"===globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug"))};class pe extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class ge extends pe{}class we extends pe{}async function ye(e,t,r){fe.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",e,t);const s=new globalThis.AbortController;return t>0&&setTimeout(()=>{s.abort(),fe.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",e)},t),await Promise.resolve().then(()=>globalThis.navigator.locks.request(e,0===t?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async s=>{if(!s){if(0===t)throw fe.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",e),new ge(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);if(fe.debug)try{const e=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(e,null," "))}catch(e){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",e)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await r()}fe.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",e,s.name);try{return await r()}finally{fe.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",e,s.name)}}))}const _e={};async function ve(e,t,r){var s;const n=null!==(s=_e[e])&&void 0!==s?s:Promise.resolve(),i=Promise.race([n.catch(()=>null),t>=0?new Promise((r,s)=>{setTimeout(()=>{s(new we(`Acquring process lock with name "${e}" timed out`))},t)}):null].filter(e=>e)).catch(e=>{if(e&&e.isAcquireTimeout)throw e;return null}).then(async()=>await r());return _e[e]=i.catch(async e=>{if(e&&e.isAcquireTimeout)return await n,null;throw e}),await i}function me(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw new Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}function be(e){const t=(new TextEncoder).encode(e);return"0x"+Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}class Ee extends Error{constructor({message:e,code:t,cause:r,name:s}){var n;super(e,{cause:r}),this.__isWebAuthnError=!0,this.name=null!==(n=null!=s?s:r instanceof Error?r.name:void 0)&&void 0!==n?n:"Unknown Error",this.code=t}}class ke extends Ee{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}}function Se({error:e,options:t}){var r,s,n;const{publicKey:i}=t;if(!i)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new Ee({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if("ConstraintError"===e.name){if(!0===(null===(r=i.authenticatorSelection)||void 0===r?void 0:r.requireResidentKey))return new Ee({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});if("conditional"===t.mediation&&"required"===(null===(s=i.authenticatorSelection)||void 0===s?void 0:s.userVerification))return new Ee({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});if("required"===(null===(n=i.authenticatorSelection)||void 0===n?void 0:n.userVerification))return new Ee({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else{if("InvalidStateError"===e.name)return new Ee({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if("NotAllowedError"===e.name)return new Ee({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("NotSupportedError"===e.name)return 0===i.pubKeyCredParams.filter(e=>"public-key"===e.type).length?new Ee({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new Ee({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e});if("SecurityError"===e.name){const t=window.location.hostname;if(!Ie(t))return new Ee({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(i.rp.id!==t)return new Ee({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("TypeError"===e.name){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new Ee({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if("UnknownError"===e.name)return new Ee({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new Ee({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}function Te({error:e,options:t}){const{publicKey:r}=t;if(!r)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new Ee({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else{if("NotAllowedError"===e.name)return new Ee({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("SecurityError"===e.name){const t=window.location.hostname;if(!Ie(t))return new Ee({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(r.rpId!==t)return new Ee({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("UnknownError"===e.name)return new Ee({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new Ee({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}const Oe=new class{createNewAbortSignal(){if(this.controller){const e=new Error("Cancelling existing WebAuthn API call for new one");e.name="AbortError",this.controller.abort(e)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}};function je(e){if(!e)throw new Error("Credential creation options are required");if("undefined"!=typeof PublicKeyCredential&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseCreationOptionsFromJSON)return PublicKeyCredential.parseCreationOptionsFromJSON(e);const{challenge:t,user:r,excludeCredentials:n}=e,i=(0,s.__rest)(e,["challenge","user","excludeCredentials"]),o=U(t).buffer,a=Object.assign(Object.assign({},r),{id:U(r.id).buffer}),l=Object.assign(Object.assign({},i),{challenge:o,user:a});if(n&&n.length>0){l.excludeCredentials=new Array(n.length);for(let e=0;e0){o.allowCredentials=new Array(r.length);for(let e=0;enull!==e&&"object"==typeof e&&!Array.isArray(e),r=e=>e instanceof ArrayBuffer||ArrayBuffer.isView(e),s={};for(const n of e)if(n)for(const e in n){const i=n[e];if(void 0!==i)if(Array.isArray(i))s[e]=i;else if(r(i))s[e]=i;else if(t(i)){const r=s[e];t(r)?s[e]=Ne(r,i):s[e]=Ne(i)}else s[e]=i}return s}class Ue{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:t,friendlyName:r,signal:s},n){try{const{data:i,error:o}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!i)return{data:null,error:o};const a=null!=s?s:Oe.createNewAbortSignal();if("create"===i.webauthn.type){const{user:e}=i.webauthn.credential_options.publicKey;e.name||(e.name=`${e.id}:${r}`),e.displayName||(e.displayName=e.name)}switch(i.webauthn.type){case"create":{const t=function(e,t){return Ne(Ce,e,t||{})}(i.webauthn.credential_options.publicKey,null==n?void 0:n.create),{data:r,error:s}=await async function(e){try{const t=await navigator.credentials.create(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new ke("Browser returned unexpected credential type",t)}:{data:null,error:new ke("Empty credential response",t)}}catch(t){return{data:null,error:Se({error:t,options:e})}}}({publicKey:t,signal:a});return r?{data:{factorId:e,challengeId:i.id,webauthn:{type:i.webauthn.type,credential_response:r}},error:null}:{data:null,error:s}}case"request":{const t=function(e,t){return Ne(xe,e,t||{})}(i.webauthn.credential_options.publicKey,null==n?void 0:n.request),{data:r,error:s}=await async function(e){try{const t=await navigator.credentials.get(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new ke("Browser returned unexpected credential type",t)}:{data:null,error:new ke("Empty credential response",t)}}catch(t){return{data:null,error:Te({error:t,options:e})}}}(Object.assign(Object.assign({},i.webauthn.credential_options),{publicKey:t,signal:a}));return r?{data:{factorId:e,challengeId:i.id,webauthn:{type:i.webauthn.type,credential_response:r}},error:null}:{data:null,error:s}}}}catch(e){return d(e)?{data:null,error:e}:{data:null,error:new g("Unexpected error in challenge",e)}}}async _verify({challengeId:e,factorId:t,webauthn:r}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:r})}async _authenticate({factorId:e,webauthn:{rpId:t=("undefined"!=typeof window?window.location.hostname:void 0),rpOrigins:r=("undefined"!=typeof window?[window.location.origin]:void 0),signal:s}={}},n){if(!t)return{data:null,error:new h("rpId is required for WebAuthn authentication")};try{if(!$e())return{data:null,error:new g("Browser does not support WebAuthn",null)};const{data:i,error:o}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:r},signal:s},{request:n});if(!i)return{data:null,error:o};const{webauthn:a}=i;return this._verify({factorId:e,challengeId:i.challengeId,webauthn:{type:a.type,rpId:t,rpOrigins:r,credential_response:a.credential_response}})}catch(e){return d(e)?{data:null,error:e}:{data:null,error:new g("Unexpected error in authenticate",e)}}}async _register({friendlyName:e,webauthn:{rpId:t=("undefined"!=typeof window?window.location.hostname:void 0),rpOrigins:r=("undefined"!=typeof window?[window.location.origin]:void 0),signal:s}={}},n){if(!t)return{data:null,error:new h("rpId is required for WebAuthn registration")};try{if(!$e())return{data:null,error:new g("Browser does not support WebAuthn",null)};const{data:i,error:o}=await this._enroll({friendlyName:e});if(!i)return await this.client.mfa.listFactors().then(t=>{var r;return null===(r=t.data)||void 0===r?void 0:r.all.find(t=>"webauthn"===t.factor_type&&t.friendly_name===e&&"unverified"!==t.status)}).then(e=>e?this.client.mfa.unenroll({factorId:null==e?void 0:e.id}):void 0),{data:null,error:o};const{data:a,error:l}=await this._challenge({factorId:i.id,friendlyName:i.friendly_name,webauthn:{rpId:t,rpOrigins:r},signal:s},{create:n});return a?this._verify({factorId:i.id,challengeId:a.challengeId,webauthn:{rpId:t,rpOrigins:r,type:a.webauthn.type,credential_response:a.webauthn.credential_response}}):{data:null,error:l}}catch(e){return d(e)?{data:null,error:e}:{data:null,error:new g("Unexpected error in register",e)}}}}!function(){if("object"!=typeof globalThis)try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch(e){"undefined"!=typeof self&&(self.globalThis=self)}}();const De={url:"http://localhost:9999",storageKey:"supabase.auth.token",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:o,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1};async function Le(e,t,r){return await r()}const Be={};class qe{get jwks(){var e,t;return null!==(t=null===(e=Be[this.storageKey])||void 0===e?void 0:e.jwks)&&void 0!==t?t:{keys:[]}}set jwks(e){Be[this.storageKey]=Object.assign(Object.assign({},Be[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return null!==(t=null===(e=Be[this.storageKey])||void 0===e?void 0:e.cachedAt)&&void 0!==t?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Be[this.storageKey]=Object.assign(Object.assign({},Be[this.storageKey]),{cachedAt:e})}constructor(e){var t,r,s;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const n=Object.assign(Object.assign({},De),e);if(this.storageKey=n.storageKey,this.instanceID=null!==(t=qe.nextInstanceID[this.storageKey])&&void 0!==t?t:0,qe.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!n.debug,"function"==typeof n.debug&&(this.logger=n.debug),this.instanceID>0&&L()){const e=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(e),this.logDebugMessages&&console.trace(e)}if(this.persistSession=n.persistSession,this.autoRefreshToken=n.autoRefreshToken,this.admin=new he({url:n.url,headers:n.headers,fetch:n.fetch}),this.url=n.url,this.headers=n.headers,this.fetch=F(n.fetch),this.lock=n.lock||Le,this.detectSessionInUrl=n.detectSessionInUrl,this.flowType=n.flowType,this.hasCustomAuthorizationHeader=n.hasCustomAuthorizationHeader,this.throwOnError=n.throwOnError,n.lock?this.lock=n.lock:this.persistSession&&L()&&(null===(r=null===globalThis||void 0===globalThis?void 0:globalThis.navigator)||void 0===r?void 0:r.locks)?this.lock=ye:this.lock=Le,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new Ue(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.persistSession?(n.storage?this.storage=n.storage:q()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=de(this.memoryStorage)),n.userStorage&&(this.userStorage=n.userStorage)):(this.memoryStorage={},this.storage=de(this.memoryStorage)),L()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(e){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",e)}null===(s=this.broadcastChannel)||void 0===s||s.addEventListener("message",async e=>{this._debug("received broadcast notification from other tab or client",e),await this._notifyAllSubscribers(e.data.event,e.data.session,!1)})}this.initialize()}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${n}) ${(new Date).toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise||(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))()),await this.initializePromise}async _initialize(){var e;try{let t={},r="none";if(L()&&(t=function(e){const t={},r=new URL(e);if(r.hash&&"#"===r.hash[0])try{new URLSearchParams(r.hash.substring(1)).forEach((e,r)=>{t[r]=e})}catch(e){}return r.searchParams.forEach((e,r)=>{t[r]=e}),t}(window.location.href),this._isImplicitGrantCallback(t)?r="implicit":await this._isPKCECallback(t)&&(r="pkce")),L()&&this.detectSessionInUrl&&"none"!==r){const{data:s,error:n}=await this._getSessionFromURL(t,r);if(n){if(this._debug("#_initialize()","error detecting session from URL",n),E(n)){const t=null===(e=n.details)||void 0===e?void 0:e.code;if("identity_already_exists"===t||"identity_not_found"===t||"single_identity_not_deletable"===t)return{error:n}}return await this._removeSession(),{error:n}}const{session:i,redirectType:o}=s;return this._debug("#_initialize()","detected session in URL",i,"redirect type",o),await this._saveSession(i),setTimeout(async()=>{"recovery"===o?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return d(e)?this._returnResult({error:e}):this._returnResult({error:new g("Unexpected error during initialization",e)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,s;try{const n=await se(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:null!==(r=null===(t=null==e?void 0:e.options)||void 0===t?void 0:t.data)&&void 0!==r?r:{},gotrue_meta_security:{captcha_token:null===(s=null==e?void 0:e.options)||void 0===s?void 0:s.captchaToken}},xform:ne}),{data:i,error:o}=n;if(o||!i)return this._returnResult({data:{user:null,session:null},error:o});const a=i.session,l=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",a)),this._returnResult({data:{user:l,session:a},error:null})}catch(e){if(d(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signUp(e){var t,r,s;try{let n;if("email"in e){const{email:r,password:s,options:i}=e;let o=null,a=null;"pkce"===this.flowType&&([o,a]=await J(this.storage,this.storageKey)),n=await se(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:null==i?void 0:i.emailRedirectTo,body:{email:r,password:s,data:null!==(t=null==i?void 0:i.data)&&void 0!==t?t:{},gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken},code_challenge:o,code_challenge_method:a},xform:ne})}else{if(!("phone"in e))throw new m("You must provide either an email or phone number and a password");{const{phone:t,password:i,options:o}=e;n=await se(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:t,password:i,data:null!==(r=null==o?void 0:o.data)&&void 0!==r?r:{},channel:null!==(s=null==o?void 0:o.channel)&&void 0!==s?s:"sms",gotrue_meta_security:{captcha_token:null==o?void 0:o.captchaToken}},xform:ne})}}const{data:i,error:o}=n;if(o||!i)return await V(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:o});const a=i.session,l=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",a)),this._returnResult({data:{user:l,session:a},error:null})}catch(e){if(await V(this.storage,`${this.storageKey}-code-verifier`),d(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithPassword(e){try{let t;if("email"in e){const{email:r,password:s,options:n}=e;t=await se(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:r,password:s,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken}},xform:ie})}else{if(!("phone"in e))throw new m("You must provide either an email or phone number and a password");{const{phone:r,password:s,options:n}=e;t=await se(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:r,password:s,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken}},xform:ie})}}const{data:r,error:s}=t;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!r||!r.session||!r.user){const e=new v;return this._returnResult({data:{user:null,session:null},error:e})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:s})}catch(e){if(d(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOAuth(e){var t,r,s,n;return await this._handleProviderSignIn(e.provider,{redirectTo:null===(t=e.options)||void 0===t?void 0:t.redirectTo,scopes:null===(r=e.options)||void 0===r?void 0:r.scopes,queryParams:null===(s=e.options)||void 0===s?void 0:s.queryParams,skipBrowserRedirect:null===(n=e.options)||void 0===n?void 0:n.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){var t,r,s,n,i,o,a,l,c,u,h;let f,p;if("message"in e)f=e.message,p=e.signature;else{const{chain:u,wallet:h,statement:d,options:g}=e;let w;if(L())if("object"==typeof h)w=h;else{const e=window;if(!("ethereum"in e)||"object"!=typeof e.ethereum||!("request"in e.ethereum)||"function"!=typeof e.ethereum.request)throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.");w=e.ethereum}else{if("object"!=typeof h||!(null==g?void 0:g.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");w=h}const y=new URL(null!==(t=null==g?void 0:g.url)&&void 0!==t?t:window.location.href),_=await w.request({method:"eth_requestAccounts"}).then(e=>e).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!_||0===_.length)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const v=me(_[0]);let m=null===(r=null==g?void 0:g.signInWithEthereum)||void 0===r?void 0:r.chainId;if(!m){const e=await w.request({method:"eth_chainId"});m=parseInt(e,16)}f=function(e){var t;const{chainId:r,domain:s,expirationTime:n,issuedAt:i=new Date,nonce:o,notBefore:a,requestId:l,resources:c,scheme:u,uri:h,version:d}=e;if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!s)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(o&&o.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${o}`);if(!h)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if("1"!==d)throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${d}`);if(null===(t=e.statement)||void 0===t?void 0:t.includes("\n"))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${e.statement}`);const f=`${u?`${u}://${s}`:s} wants you to sign in with your Ethereum account:\n${me(e.address)}\n\n${e.statement?`${e.statement}\n`:""}`;let p=`URI: ${h}\nVersion: ${d}\nChain ID: ${r}${o?`\nNonce: ${o}`:""}\nIssued At: ${i.toISOString()}`;if(n&&(p+=`\nExpiration Time: ${n.toISOString()}`),a&&(p+=`\nNot Before: ${a.toISOString()}`),l&&(p+=`\nRequest ID: ${l}`),c){let e="\nResources:";for(const t of c){if(!t||"string"!=typeof t)throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${t}`);e+=`\n- ${t}`}p+=e}return`${f}\n${p}`}({domain:y.host,address:v,statement:d,uri:y.href,version:"1",chainId:m,nonce:null===(s=null==g?void 0:g.signInWithEthereum)||void 0===s?void 0:s.nonce,issuedAt:null!==(i=null===(n=null==g?void 0:g.signInWithEthereum)||void 0===n?void 0:n.issuedAt)&&void 0!==i?i:new Date,expirationTime:null===(o=null==g?void 0:g.signInWithEthereum)||void 0===o?void 0:o.expirationTime,notBefore:null===(a=null==g?void 0:g.signInWithEthereum)||void 0===a?void 0:a.notBefore,requestId:null===(l=null==g?void 0:g.signInWithEthereum)||void 0===l?void 0:l.requestId,resources:null===(c=null==g?void 0:g.signInWithEthereum)||void 0===c?void 0:c.resources}),p=await w.request({method:"personal_sign",params:[be(f),v]})}try{const{data:t,error:r}=await se(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:f,signature:p},(null===(u=e.options)||void 0===u?void 0:u.captchaToken)?{gotrue_meta_security:{captcha_token:null===(h=e.options)||void 0===h?void 0:h.captchaToken}}:null),xform:ne});if(r)throw r;if(!t||!t.session||!t.user){const e=new v;return this._returnResult({data:{user:null,session:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign({},t),error:r})}catch(e){if(d(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSolana(e){var t,r,s,n,i,o,a,l,c,u,h,f;let p,g;if("message"in e)p=e.message,g=e.signature;else{const{chain:h,wallet:d,statement:f,options:w}=e;let y;if(L())if("object"==typeof d)y=d;else{const e=window;if(!("solana"in e)||"object"!=typeof e.solana||!("signIn"in e.solana&&"function"==typeof e.solana.signIn||"signMessage"in e.solana&&"function"==typeof e.solana.signMessage))throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.");y=e.solana}else{if("object"!=typeof d||!(null==w?void 0:w.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");y=d}const _=new URL(null!==(t=null==w?void 0:w.url)&&void 0!==t?t:window.location.href);if("signIn"in y&&y.signIn){const e=await y.signIn(Object.assign(Object.assign(Object.assign({issuedAt:(new Date).toISOString()},null==w?void 0:w.signInWithSolana),{version:"1",domain:_.host,uri:_.href}),f?{statement:f}:null));let t;if(Array.isArray(e)&&e[0]&&"object"==typeof e[0])t=e[0];else{if(!(e&&"object"==typeof e&&"signedMessage"in e&&"signature"in e))throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");t=e}if(!("signedMessage"in t&&"signature"in t&&("string"==typeof t.signedMessage||t.signedMessage instanceof Uint8Array)&&t.signature instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields");p="string"==typeof t.signedMessage?t.signedMessage:(new TextDecoder).decode(t.signedMessage),g=t.signature}else{if(!("signMessage"in y&&"function"==typeof y.signMessage&&"publicKey"in y&&"object"==typeof y&&y.publicKey&&"toBase58"in y.publicKey&&"function"==typeof y.publicKey.toBase58))throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");p=[`${_.host} wants you to sign in with your Solana account:`,y.publicKey.toBase58(),...f?["",f,""]:[""],"Version: 1",`URI: ${_.href}`,`Issued At: ${null!==(s=null===(r=null==w?void 0:w.signInWithSolana)||void 0===r?void 0:r.issuedAt)&&void 0!==s?s:(new Date).toISOString()}`,...(null===(n=null==w?void 0:w.signInWithSolana)||void 0===n?void 0:n.notBefore)?[`Not Before: ${w.signInWithSolana.notBefore}`]:[],...(null===(i=null==w?void 0:w.signInWithSolana)||void 0===i?void 0:i.expirationTime)?[`Expiration Time: ${w.signInWithSolana.expirationTime}`]:[],...(null===(o=null==w?void 0:w.signInWithSolana)||void 0===o?void 0:o.chainId)?[`Chain ID: ${w.signInWithSolana.chainId}`]:[],...(null===(a=null==w?void 0:w.signInWithSolana)||void 0===a?void 0:a.nonce)?[`Nonce: ${w.signInWithSolana.nonce}`]:[],...(null===(l=null==w?void 0:w.signInWithSolana)||void 0===l?void 0:l.requestId)?[`Request ID: ${w.signInWithSolana.requestId}`]:[],...(null===(u=null===(c=null==w?void 0:w.signInWithSolana)||void 0===c?void 0:c.resources)||void 0===u?void 0:u.length)?["Resources",...w.signInWithSolana.resources.map(e=>`- ${e}`)]:[]].join("\n");const e=await y.signMessage((new TextEncoder).encode(p),"utf8");if(!(e&&e instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");g=e}}try{const{data:t,error:r}=await se(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:p,signature:D(g)},(null===(h=e.options)||void 0===h?void 0:h.captchaToken)?{gotrue_meta_security:{captcha_token:null===(f=e.options)||void 0===f?void 0:f.captchaToken}}:null),xform:ne});if(r)throw r;if(!t||!t.session||!t.user){const e=new v;return this._returnResult({data:{user:null,session:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign({},t),error:r})}catch(e){if(d(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _exchangeCodeForSession(e){const t=await K(this.storage,`${this.storageKey}-code-verifier`),[r,s]=(null!=t?t:"").split("/");try{const{data:t,error:n}=await se(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:ne});if(await V(this.storage,`${this.storageKey}-code-verifier`),n)throw n;if(!t||!t.session||!t.user){const e=new v;return this._returnResult({data:{user:null,session:null,redirectType:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign(Object.assign({},t),{redirectType:null!=s?s:null}),error:n})}catch(e){if(await V(this.storage,`${this.storageKey}-code-verifier`),d(e))return this._returnResult({data:{user:null,session:null,redirectType:null},error:e});throw e}}async signInWithIdToken(e){try{const{options:t,provider:r,token:s,access_token:n,nonce:i}=e,o=await se(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:s,access_token:n,nonce:i,gotrue_meta_security:{captcha_token:null==t?void 0:t.captchaToken}},xform:ne}),{data:a,error:l}=o;if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!a||!a.session||!a.user){const e=new v;return this._returnResult({data:{user:null,session:null},error:e})}return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session)),this._returnResult({data:a,error:l})}catch(e){if(d(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOtp(e){var t,r,s,n,i;try{if("email"in e){const{email:s,options:n}=e;let i=null,o=null;"pkce"===this.flowType&&([i,o]=await J(this.storage,this.storageKey));const{error:a}=await se(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:s,data:null!==(t=null==n?void 0:n.data)&&void 0!==t?t:{},create_user:null===(r=null==n?void 0:n.shouldCreateUser)||void 0===r||r,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken},code_challenge:i,code_challenge_method:o},redirectTo:null==n?void 0:n.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:a})}if("phone"in e){const{phone:t,options:r}=e,{data:o,error:a}=await se(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:t,data:null!==(s=null==r?void 0:r.data)&&void 0!==s?s:{},create_user:null===(n=null==r?void 0:r.shouldCreateUser)||void 0===n||n,gotrue_meta_security:{captcha_token:null==r?void 0:r.captchaToken},channel:null!==(i=null==r?void 0:r.channel)&&void 0!==i?i:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:null==o?void 0:o.message_id},error:a})}throw new m("You must provide either an email or phone number.")}catch(e){if(await V(this.storage,`${this.storageKey}-code-verifier`),d(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async verifyOtp(e){var t,r;try{let s,n;"options"in e&&(s=null===(t=e.options)||void 0===t?void 0:t.redirectTo,n=null===(r=e.options)||void 0===r?void 0:r.captchaToken);const{data:i,error:o}=await se(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:s,xform:ne});if(o)throw o;if(!i)throw new Error("An error occurred on token verification.");const a=i.session,l=i.user;return(null==a?void 0:a.access_token)&&(await this._saveSession(a),await this._notifyAllSubscribers("recovery"==e.type?"PASSWORD_RECOVERY":"SIGNED_IN",a)),this._returnResult({data:{user:l,session:a},error:null})}catch(e){if(d(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSSO(e){var t,r,s,n,i;try{let o=null,a=null;"pkce"===this.flowType&&([o,a]=await J(this.storage,this.storageKey));const l=await se(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:null!==(r=null===(t=e.options)||void 0===t?void 0:t.redirectTo)&&void 0!==r?r:void 0}),(null===(s=null==e?void 0:e.options)||void 0===s?void 0:s.captchaToken)?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:o,code_challenge_method:a}),headers:this.headers,xform:ae});return(null===(n=l.data)||void 0===n?void 0:n.url)&&L()&&!(null===(i=e.options)||void 0===i?void 0:i.skipBrowserRedirect)&&window.location.assign(l.data.url),this._returnResult(l)}catch(e){if(await V(this.storage,`${this.storageKey}-code-verifier`),d(e))return this._returnResult({data:null,error:e});throw e}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new y;const{error:s}=await se(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:s})})}catch(e){if(d(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{const t=`${this.url}/resend`;if("email"in e){const{email:r,type:s,options:n}=e,{error:i}=await se(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:s,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken}},redirectTo:null==n?void 0:n.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:i})}if("phone"in e){const{phone:r,type:s,options:n}=e,{data:i,error:o}=await se(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:s,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:null==i?void 0:i.message_id},error:o})}throw new m("You must provide either an email or phone number and a type")}catch(e){if(d(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async e=>e))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const e=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),r=(async()=>(await e,await t()))();return this.pendingInLock.push((async()=>{try{await r}catch(e){}})()),r}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const e=t();for(this.pendingInLock.push((async()=>{try{await e}catch(e){}})()),await e;this.pendingInLock.length;){const e=[...this.pendingInLock];await Promise.all(e),this.pendingInLock.splice(0,e.length)}return await e}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{const t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",(new Error).stack);try{let e=null;const t=await K(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),null!==t&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const r=!!e.expires_at&&1e3*e.expires_at-Date.now()<9e4;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",e.expires_at),!r){if(this.userStorage){const t=await K(this.userStorage,this.storageKey+"-user");(null==t?void 0:t.user)?e.user=t.user:e.user=X()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const t={value:this.suppressGetSessionWarning};e.user=function(e,t){return new Proxy(e,{get:(e,r,s)=>{if("__isInsecureUserWarningProxy"===r)return!0;if("symbol"==typeof r){const t=r.toString();if("Symbol(Symbol.toPrimitive)"===t||"Symbol(Symbol.toStringTag)"===t||"Symbol(util.inspect.custom)"===t||"Symbol(nodejs.util.inspect.custom)"===t)return Reflect.get(e,r,s)}return t.value||"string"!=typeof r||(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),t.value=!0),Reflect.get(e,r,s)}})}(e.user,t),t.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:s,error:n}=await this._callRefreshToken(e.refresh_token);return n?this._returnResult({data:{session:null},error:n}):this._returnResult({data:{session:s},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;const t=await this._acquireLock(-1,async()=>await this._getUser());return t.data.user&&(this.suppressGetSessionWarning=!0),t}async _getUser(e){try{return e?await se(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:oe}):await this._useSession(async e=>{var t,r,s;const{data:n,error:i}=e;if(i)throw i;return(null===(t=n.session)||void 0===t?void 0:t.access_token)||this.hasCustomAuthorizationHeader?await se(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:null!==(s=null===(r=n.session)||void 0===r?void 0:r.access_token)&&void 0!==s?s:void 0,xform:oe}):{data:{user:null},error:new y}})}catch(e){if(d(e))return _(e)&&(await this._removeSession(),await V(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:e});throw e}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async r=>{const{data:s,error:n}=r;if(n)throw n;if(!s.session)throw new y;const i=s.session;let o=null,a=null;"pkce"===this.flowType&&null!=e.email&&([o,a]=await J(this.storage,this.storageKey));const{data:l,error:c}=await se(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:null==t?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:o,code_challenge_method:a}),jwt:i.access_token,xform:oe});if(c)throw c;return i.user=l.user,await this._saveSession(i),await this._notifyAllSubscribers("USER_UPDATED",i),this._returnResult({data:{user:i.user},error:null})})}catch(e){if(await V(this.storage,`${this.storageKey}-code-verifier`),d(e))return this._returnResult({data:{user:null},error:e});throw e}}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new y;const t=Date.now()/1e3;let r=t,s=!0,n=null;const{payload:i}=G(e.access_token);if(i.exp&&(r=i.exp,s=r<=t),s){const{data:t,error:r}=await this._callRefreshToken(e.refresh_token);if(r)return this._returnResult({data:{user:null,session:null},error:r});if(!t)return{data:{user:null,session:null},error:null};n=t}else{const{data:s,error:i}=await this._getUser(e.access_token);if(i)throw i;n={access_token:e.access_token,refresh_token:e.refresh_token,user:s.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return this._returnResult({data:{user:n.user,session:n},error:null})}catch(e){if(d(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var r;if(!e){const{data:s,error:n}=t;if(n)throw n;e=null!==(r=s.session)&&void 0!==r?r:void 0}if(!(null==e?void 0:e.refresh_token))throw new y;const{data:s,error:n}=await this._callRefreshToken(e.refresh_token);return n?this._returnResult({data:{user:null,session:null},error:n}):s?this._returnResult({data:{user:s.user,session:s},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(e){if(d(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _getSessionFromURL(e,t){try{if(!L())throw new b("No browser detected.");if(e.error||e.error_description||e.error_code)throw new b(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if("pkce"===this.flowType)throw new k("Not a valid PKCE flow url.");break;case"pkce":if("implicit"===this.flowType)throw new b("Not a valid implicit grant flow url.")}if("pkce"===t){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new k("No code detected.");const{data:t,error:r}=await this._exchangeCodeForSession(e.code);if(r)throw r;const s=new URL(window.location.href);return s.searchParams.delete("code"),window.history.replaceState(window.history.state,"",s.toString()),{data:{session:t.session,redirectType:null},error:null}}const{provider_token:r,provider_refresh_token:s,access_token:n,refresh_token:o,expires_in:a,expires_at:l,token_type:c}=e;if(!(n&&a&&o&&c))throw new b("No session defined in URL");const u=Math.round(Date.now()/1e3),h=parseInt(a);let d=u+h;l&&(d=parseInt(l));const f=d-u;1e3*f<=i&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${h}s`);const p=d-h;u-p>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",p,d,u):u-p<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",p,d,u);const{data:g,error:w}=await this._getUser(n);if(w)throw w;const y={provider_token:r,provider_refresh_token:s,access_token:n,expires_in:h,expires_at:d,refresh_token:o,token_type:c,user:g.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:y,redirectType:e.type},error:null})}catch(e){if(d(e))return this._returnResult({data:{session:null,redirectType:null},error:e});throw e}}_isImplicitGrantCallback(e){return Boolean(e.access_token||e.error_description)}async _isPKCECallback(e){const t=await K(this.storage,`${this.storageKey}-code-verifier`);return!(!e.code||!t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var r;const{data:s,error:n}=t;if(n)return this._returnResult({error:n});const i=null===(r=s.session)||void 0===r?void 0:r.access_token;if(i){const{error:t}=await this.admin.signOut(i,e);if(t&&(!p(t)||404!==t.status&&401!==t.status&&403!==t.status))return this._returnResult({error:t})}return"others"!==e&&(await this._removeSession(),await V(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const t=Symbol("auth-callback"),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>{await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})})(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,s;try{const{data:{session:s},error:n}=t;if(n)throw n;await(null===(r=this.stateChangeEmitters.get(e))||void 0===r?void 0:r.callback("INITIAL_SESSION",s)),this._debug("INITIAL_SESSION","callback id",e,"session",s)}catch(t){await(null===(s=this.stateChangeEmitters.get(e))||void 0===s?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",t),console.error(t)}})}async resetPasswordForEmail(e,t={}){let r=null,s=null;"pkce"===this.flowType&&([r,s]=await J(this.storage,this.storageKey,!0));try{return await se(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:s,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(e){if(await V(this.storage,`${this.storageKey}-code-verifier`),d(e))return this._returnResult({data:null,error:e});throw e}}async getUserIdentities(){var e;try{const{data:t,error:r}=await this.getUser();if(r)throw r;return this._returnResult({data:{identities:null!==(e=t.user.identities)&&void 0!==e?e:[]},error:null})}catch(e){if(d(e))return this._returnResult({data:null,error:e});throw e}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;try{const{data:r,error:s}=await this._useSession(async t=>{var r,s,n,i,o;const{data:a,error:l}=t;if(l)throw l;const c=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:null===(r=e.options)||void 0===r?void 0:r.redirectTo,scopes:null===(s=e.options)||void 0===s?void 0:s.scopes,queryParams:null===(n=e.options)||void 0===n?void 0:n.queryParams,skipBrowserRedirect:!0});return await se(this.fetch,"GET",c,{headers:this.headers,jwt:null!==(o=null===(i=a.session)||void 0===i?void 0:i.access_token)&&void 0!==o?o:void 0})});if(s)throw s;return L()&&!(null===(t=e.options)||void 0===t?void 0:t.skipBrowserRedirect)&&window.location.assign(null==r?void 0:r.url),this._returnResult({data:{provider:e.provider,url:null==r?void 0:r.url},error:null})}catch(t){if(d(t))return this._returnResult({data:{provider:e.provider,url:null},error:t});throw t}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var r;try{const{error:s,data:{session:n}}=t;if(s)throw s;const{options:i,provider:o,token:a,access_token:l,nonce:c}=e,u=await se(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:null!==(r=null==n?void 0:n.access_token)&&void 0!==r?r:void 0,body:{provider:o,id_token:a,access_token:l,nonce:c,link_identity:!0,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},xform:ne}),{data:h,error:d}=u;return d?this._returnResult({data:{user:null,session:null},error:d}):h&&h.session&&h.user?(h.session&&(await this._saveSession(h.session),await this._notifyAllSubscribers("USER_UPDATED",h.session)),this._returnResult({data:h,error:d})):this._returnResult({data:{user:null,session:null},error:new v})}catch(e){if(await V(this.storage,`${this.storageKey}-code-verifier`),d(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,s;const{data:n,error:i}=t;if(i)throw i;return await se(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:null!==(s=null===(r=n.session)||void 0===r?void 0:r.access_token)&&void 0!==s?s:void 0})})}catch(e){if(d(e))return this._returnResult({data:null,error:e});throw e}}async _refreshAccessToken(e){const t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{const n=Date.now();return await(r=async r=>(r>0&&await async function(e){return await new Promise(t=>{setTimeout(()=>t(null),e)})}(200*Math.pow(2,r-1)),this._debug(t,"refreshing attempt",r),await se(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:ne})),s=(e,t)=>{const r=200*Math.pow(2,e);return t&&T(t)&&Date.now()+r-n{(async()=>{for(let n=0;n<1/0;n++)try{const t=await r(n);if(!s(n,null))return void e(t)}catch(e){if(!s(n,e))return void t(e)}})()}))}catch(e){if(this._debug(t,"error",e),d(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}finally{this._debug(t,"end")}var r,s}_isValidSession(e){return"object"==typeof e&&null!==e&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){const r=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),L()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e,t;const r="#_recoverAndRefresh()";this._debug(r,"begin");try{const s=await K(this.storage,this.storageKey);if(s&&this.userStorage){let t=await K(this.userStorage,this.storageKey+"-user");this.storage.isServer||!Object.is(this.storage,this.userStorage)||t||(t={user:s.user},await M(this.userStorage,this.storageKey+"-user",t)),s.user=null!==(e=null==t?void 0:t.user)&&void 0!==e?e:X()}else if(s&&!s.user&&!s.user){const e=await K(this.storage,this.storageKey+"-user");e&&(null==e?void 0:e.user)?(s.user=e.user,await V(this.storage,this.storageKey+"-user"),await M(this.storage,this.storageKey,s)):s.user=X()}if(this._debug(r,"session from storage",s),!this._isValidSession(s))return this._debug(r,"session is not valid"),void(null!==s&&await this._removeSession());const n=1e3*(null!==(t=s.expires_at)&&void 0!==t?t:1/0)-Date.now()<9e4;if(this._debug(r,`session has${n?"":" not"} expired with margin of 90000s`),n){if(this.autoRefreshToken&&s.refresh_token){const{error:e}=await this._callRefreshToken(s.refresh_token);e&&(console.error(e),T(e)||(this._debug(r,"refresh failed with a non-retryable error, removing the session",e),await this._removeSession()))}}else if(s.user&&!0===s.user.__isUserNotAvailableProxy)try{const{data:e,error:t}=await this._getUser(s.access_token);!t&&(null==e?void 0:e.user)?(s.user=e.user,await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)):this._debug(r,"could not get user data, skipping SIGNED_IN notification")}catch(e){console.error("Error getting user data:",e),this._debug(r,"error getting user data, skipping SIGNED_IN notification",e)}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(e){return this._debug(r,"error",e),void console.error(e)}finally{this._debug(r,"end")}}async _callRefreshToken(e){var t,r;if(!e)throw new y;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const s=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{this.refreshingDeferred=new W;const{data:t,error:r}=await this._refreshAccessToken(e);if(r)throw r;if(!t.session)throw new y;await this._saveSession(t.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",t.session);const s={data:t.session,error:null};return this.refreshingDeferred.resolve(s),s}catch(e){if(this._debug(s,"error",e),d(e)){const r={data:null,error:e};return T(e)||await this._removeSession(),null===(t=this.refreshingDeferred)||void 0===t||t.resolve(r),r}throw null===(r=this.refreshingDeferred)||void 0===r||r.reject(e),e}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,t,r=!0){const s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});const s=[],n=Array.from(this.stateChangeEmitters.values()).map(async r=>{try{await r.callback(e,t)}catch(e){s.push(e)}});if(await Promise.all(n),s.length>0){for(let e=0;ethis._autoRefreshTokenTick(),i);this.autoRefreshTicker=e,e&&"object"==typeof e&&"function"==typeof e.unref?e.unref():"undefined"!=typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const e=Date.now();try{return await this._useSession(async t=>{const{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at)return void this._debug("#_autoRefreshTokenTick()","no session");const s=Math.floor((1e3*r.expires_at-e)/i);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts 30000ms, refresh threshold is 3 ticks`),s<=3&&await this._callRefreshToken(r.refresh_token)})}catch(e){console.error("Auto refresh tick failed with error. This is likely a transient error.",e)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(!(e.isAcquireTimeout||e instanceof pe))throw e;this._debug("auto refresh token tick lock not available")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!L()||!(null===window||void 0===window?void 0:window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),null===window||void 0===window||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),"visible"===document.visibilityState?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{"visible"===document.visibilityState?await this._recoverAndRefresh():this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting")}))):"hidden"===document.visibilityState&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){const s=[`provider=${encodeURIComponent(t)}`];if((null==r?void 0:r.redirectTo)&&s.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),(null==r?void 0:r.scopes)&&s.push(`scopes=${encodeURIComponent(r.scopes)}`),"pkce"===this.flowType){const[e,t]=await J(this.storage,this.storageKey),r=new URLSearchParams({code_challenge:`${encodeURIComponent(e)}`,code_challenge_method:`${encodeURIComponent(t)}`});s.push(r.toString())}if(null==r?void 0:r.queryParams){const e=new URLSearchParams(r.queryParams);s.push(e.toString())}return(null==r?void 0:r.skipBrowserRedirect)&&s.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${e}?${s.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var r;const{data:s,error:n}=t;return n?this._returnResult({data:null,error:n}):await se(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:null===(r=null==s?void 0:s.session)||void 0===r?void 0:r.access_token})})}catch(e){if(d(e))return this._returnResult({data:null,error:e});throw e}}async _enroll(e){try{return await this._useSession(async t=>{var r,s;const{data:n,error:i}=t;if(i)return this._returnResult({data:null,error:i});const o=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},"phone"===e.factorType?{phone:e.phone}:"totp"===e.factorType?{issuer:e.issuer}:{}),{data:a,error:l}=await se(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:null===(r=null==n?void 0:n.session)||void 0===r?void 0:r.access_token});return l?this._returnResult({data:null,error:l}):("totp"===e.factorType&&"totp"===a.type&&(null===(s=null==a?void 0:a.totp)||void 0===s?void 0:s.qr_code)&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),this._returnResult({data:a,error:null}))})}catch(e){if(d(e))return this._returnResult({data:null,error:e});throw e}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;const{data:s,error:n}=t;if(n)return this._returnResult({data:null,error:n});const i=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:"create"===e.webauthn.type?Ae(e.webauthn.credential_response):Pe(e.webauthn.credential_response)})}:{code:e.code}),{data:o,error:a}=await se(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:i,headers:this.headers,jwt:null===(r=null==s?void 0:s.session)||void 0===r?void 0:r.access_token});return a?this._returnResult({data:null,error:a}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),this._returnResult({data:o,error:a}))})}catch(e){if(d(e))return this._returnResult({data:null,error:e});throw e}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;const{data:s,error:n}=t;if(n)return this._returnResult({data:null,error:n});const i=await se(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:null===(r=null==s?void 0:s.session)||void 0===r?void 0:r.access_token});if(i.error)return i;const{data:o}=i;if("webauthn"!==o.type)return{data:o,error:null};switch(o.webauthn.type){case"create":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:je(o.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:Re(o.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(e){if(d(e))return this._returnResult({data:null,error:e});throw e}})}async _challengeAndVerify(e){const{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?this._returnResult({data:null,error:r}):await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){var e;const{data:{user:t},error:r}=await this.getUser();if(r)return{data:null,error:r};const s={all:[],phone:[],totp:[],webauthn:[]};for(const r of null!==(e=null==t?void 0:t.factors)&&void 0!==e?e:[])s.all.push(r),"verified"===r.status&&s[r.factor_type].push(r);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(){var e,t;const{data:{session:r},error:s}=await this.getSession();if(s)return this._returnResult({data:null,error:s});if(!r)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:n}=G(r.access_token);let i=null;n.aal&&(i=n.aal);let o=i;return(null!==(t=null===(e=r.user.factors)||void 0===e?void 0:e.filter(e=>"verified"===e.status))&&void 0!==t?t:[]).length>0&&(o="aal2"),{data:{currentLevel:i,nextLevel:o,currentAuthenticationMethods:n.amr||[]},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{const{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?await se(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:r.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new y})})}catch(e){if(d(e))return this._returnResult({data:null,error:e});throw e}}async _approveAuthorization(e,t){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new y});const i=await se(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:e=>({data:e,error:null})});return i.data&&i.data.redirect_url&&L()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(i.data.redirect_url),i})}catch(e){if(d(e))return this._returnResult({data:null,error:e});throw e}}async _denyAuthorization(e,t){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new y});const i=await se(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:e=>({data:e,error:null})});return i.data&&i.data.redirect_url&&L()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(i.data.redirect_url),i})}catch(e){if(d(e))return this._returnResult({data:null,error:e});throw e}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:t},error:r}=e;return r?this._returnResult({data:null,error:r}):t?await se(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new y})})}catch(e){if(d(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{const{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?(await se(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new y})})}catch(e){if(d(e))return this._returnResult({data:null,error:e});throw e}}async fetchJwk(e,t={keys:[]}){let r=t.keys.find(t=>t.kid===e);if(r)return r;const s=Date.now();if(r=this.jwks.keys.find(t=>t.kid===e),r&&this.jwks_cached_at+6e5>s)return r;const{data:n,error:i}=await se(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(i)throw i;return n.keys&&0!==n.keys.length?(this.jwks=n,this.jwks_cached_at=s,r=n.keys.find(t=>t.kid===e),r||null):null}async getClaims(e,t={}){try{let r=e;if(!r){const{data:e,error:t}=await this.getSession();if(t||!e.session)return this._returnResult({data:null,error:t});r=e.session.access_token}const{header:s,payload:n,signature:i,raw:{header:o,payload:a}}=G(r);(null==t?void 0:t.allowExpired)||function(e){if(!e)throw new Error("Missing exp claim");if(e<=Math.floor(Date.now()/1e3))throw new Error("JWT has expired")}(n.exp);const l=s.alg&&!s.alg.startsWith("HS")&&s.kid&&"crypto"in globalThis&&"subtle"in globalThis.crypto?await this.fetchJwk(s.kid,(null==t?void 0:t.keys)?{keys:t.keys}:null==t?void 0:t.jwks):null;if(!l){const{error:e}=await this.getUser(r);if(e)throw e;return{data:{claims:n,header:s,signature:i},error:null}}const c=function(e){switch(e){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}(s.alg),u=await crypto.subtle.importKey("jwk",l,c,!0,["verify"]);if(!await crypto.subtle.verify(c,u,i,function(e){const t=[];return function(e,t){for(let r=0;r55295&&s<=56319){const t=1024*(s-55296)&65535;s=65536+(e.charCodeAt(r+1)-56320&65535|t),r+=1}N(s,t)}}(e,e=>t.push(e)),new Uint8Array(t)}(`${o}.${a}`)))throw new R("Invalid JWT signature");return{data:{claims:n,header:s,signature:i},error:null}}catch(e){if(d(e))return this._returnResult({data:null,error:e});throw e}}}qe.nextInstanceID={};const Fe=qe,Me=he,Ke=qe},231:(e,t,r)=>{r.r(t),r.d(t,{FunctionRegion:()=>s,FunctionsClient:()=>c,FunctionsError:()=>i,FunctionsFetchError:()=>o,FunctionsHttpError:()=>l,FunctionsRelayError:()=>a});var s,n=r(823);class i extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}}class o extends i{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class a extends i{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class l extends i{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}!function(e){e.Any="any",e.ApNortheast1="ap-northeast-1",e.ApNortheast2="ap-northeast-2",e.ApSouth1="ap-south-1",e.ApSoutheast1="ap-southeast-1",e.ApSoutheast2="ap-southeast-2",e.CaCentral1="ca-central-1",e.EuCentral1="eu-central-1",e.EuWest1="eu-west-1",e.EuWest2="eu-west-2",e.EuWest3="eu-west-3",e.SaEast1="sa-east-1",e.UsEast1="us-east-1",e.UsWest1="us-west-1",e.UsWest2="us-west-2"}(s||(s={}));class c{constructor(e,{headers:t={},customFetch:r,region:n=s.Any}={}){this.url=e,this.headers=t,this.region=n,this.fetch=(e=>e?(...t)=>e(...t):(...e)=>fetch(...e))(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return(0,n.__awaiter)(this,arguments,void 0,function*(e,t={}){var r;let s,n;try{const{headers:i,method:c,body:u,signal:h,timeout:d}=t;let f={},{region:p}=t;p||(p=this.region);const g=new URL(`${this.url}/${e}`);let w;p&&"any"!==p&&(f["x-region"]=p,g.searchParams.set("forceFunctionRegion",p)),u&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)?"undefined"!=typeof Blob&&u instanceof Blob||u instanceof ArrayBuffer?(f["Content-Type"]="application/octet-stream",w=u):"string"==typeof u?(f["Content-Type"]="text/plain",w=u):"undefined"!=typeof FormData&&u instanceof FormData?w=u:(f["Content-Type"]="application/json",w=JSON.stringify(u)):w=u;let y=h;d&&(n=new AbortController,s=setTimeout(()=>n.abort(),d),h?(y=n.signal,h.addEventListener("abort",()=>n.abort())):y=n.signal);const _=yield this.fetch(g.toString(),{method:c||"POST",headers:Object.assign(Object.assign(Object.assign({},f),this.headers),i),body:w,signal:y}).catch(e=>{throw new o(e)}),v=_.headers.get("x-relay-error");if(v&&"true"===v)throw new a(_);if(!_.ok)throw new l(_);let m,b=(null!==(r=_.headers.get("Content-Type"))&&void 0!==r?r:"text/plain").split(";")[0].trim();return m="application/json"===b?yield _.json():"application/octet-stream"===b||"application/pdf"===b?yield _.blob():"text/event-stream"===b?_:"multipart/form-data"===b?yield _.formData():yield _.text(),{data:m,error:null,response:_}}catch(e){return{data:null,error:e,response:e instanceof l||e instanceof a?e.context:void 0}}finally{s&&clearTimeout(s)}})}}},251:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_REALTIME_OPTIONS=t.DEFAULT_AUTH_OPTIONS=t.DEFAULT_DB_OPTIONS=t.DEFAULT_GLOBAL_OPTIONS=t.DEFAULT_HEADERS=void 0;const s=r(822);let n="";n="undefined"!=typeof Deno?"deno":"undefined"!=typeof document?"web":"undefined"!=typeof navigator&&"ReactNative"===navigator.product?"react-native":"node",t.DEFAULT_HEADERS={"X-Client-Info":`supabase-js-${n}/${s.version}`},t.DEFAULT_GLOBAL_OPTIONS={headers:t.DEFAULT_HEADERS},t.DEFAULT_DB_OPTIONS={schema:"public"},t.DEFAULT_AUTH_OPTIONS={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},t.DEFAULT_REALTIME_OPTIONS={}},442:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fetchWithAuth=t.resolveHeadersConstructor=t.resolveFetch=void 0,t.resolveFetch=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),t.resolveHeadersConstructor=()=>Headers,t.fetchWithAuth=(e,r,s)=>{const n=(0,t.resolveFetch)(s),i=(0,t.resolveHeadersConstructor)();return async(t,s)=>{var o;const a=null!==(o=await r())&&void 0!==o?o:e;let l=new i(null==s?void 0:s.headers);return l.has("apikey")||l.set("apikey",e),l.has("Authorization")||l.set("Authorization",`Bearer ${a}`),n(t,Object.assign(Object.assign({},s),{headers:l}))}}},595:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0});const s=r(823).__importDefault(r(886));t.default=class{constructor(e){var t,r;this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=null!==(t=e.shouldThrowOnError)&&void 0!==t&&t,this.signal=e.signal,this.isMaybeSingle=null!==(r=e.isMaybeSingle)&&void 0!==r&&r,e.fetch?this.fetch=e.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}then(e,t){void 0===this.schema||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),"GET"!==this.method&&"HEAD"!==this.method&&this.headers.set("Content-Type","application/json");let r=(0,this.fetch)(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async e=>{var t,r,n,i;let o=null,a=null,l=null,c=e.status,u=e.statusText;if(e.ok){if("HEAD"!==this.method){const r=await e.text();""===r||(a="text/csv"===this.headers.get("Accept")||this.headers.get("Accept")&&(null===(t=this.headers.get("Accept"))||void 0===t?void 0:t.includes("application/vnd.pgrst.plan+text"))?r:JSON.parse(r))}const s=null===(r=this.headers.get("Prefer"))||void 0===r?void 0:r.match(/count=(exact|planned|estimated)/),i=null===(n=e.headers.get("content-range"))||void 0===n?void 0:n.split("/");s&&i&&i.length>1&&(l=parseInt(i[1])),this.isMaybeSingle&&"GET"===this.method&&Array.isArray(a)&&(a.length>1?(o={code:"PGRST116",details:`Results contain ${a.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},a=null,l=null,c=406,u="Not Acceptable"):a=1===a.length?a[0]:null)}else{const t=await e.text();try{o=JSON.parse(t),Array.isArray(o)&&404===e.status&&(a=[],o=null,c=200,u="OK")}catch(r){404===e.status&&""===t?(c=204,u="No Content"):o={message:t}}if(o&&this.isMaybeSingle&&(null===(i=null==o?void 0:o.details)||void 0===i?void 0:i.includes("0 rows"))&&(o=null,c=200,u="OK"),o&&this.shouldThrowOnError)throw new s.default(o)}return{error:o,data:a,count:l,status:c,statusText:u}});return this.shouldThrowOnError||(r=r.catch(e=>{var t,r,s,n,i,o;let a="";const l=null==e?void 0:e.cause;if(l){const i=null!==(t=null==l?void 0:l.message)&&void 0!==t?t:"",o=null!==(r=null==l?void 0:l.code)&&void 0!==r?r:"";a=`${null!==(s=null==e?void 0:e.name)&&void 0!==s?s:"FetchError"}: ${null==e?void 0:e.message}`,a+=`\n\nCaused by: ${null!==(n=null==l?void 0:l.name)&&void 0!==n?n:"Error"}: ${i}`,o&&(a+=` (${o})`),(null==l?void 0:l.stack)&&(a+=`\n${l.stack}`)}else a=null!==(i=null==e?void 0:e.stack)&&void 0!==i?i:"";return{error:{message:`${null!==(o=null==e?void 0:e.name)&&void 0!==o?o:"FetchError"}: ${null==e?void 0:e.message}`,details:a,hint:"",code:""},data:null,count:null,status:0,statusText:""}})),r.then(e,t)}returns(){return this}overrideTypes(){return this}}},597:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0});const s=r(823),n=s.__importDefault(r(705)),i=s.__importDefault(r(973));class o{constructor(e,{headers:t={},schema:r,fetch:s}={}){this.url=e,this.headers=new Headers(t),this.schemaName=r,this.fetch=s}from(e){if(!e||"string"!=typeof e||""===e.trim())throw new Error("Invalid relation name: relation must be a non-empty string.");const t=new URL(`${this.url}/${e}`);return new n.default(t,{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new o(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:r=!1,get:s=!1,count:n}={}){var o;let a;const l=new URL(`${this.url}/rpc/${e}`);let c;r||s?(a=r?"HEAD":"GET",Object.entries(t).filter(([e,t])=>void 0!==t).map(([e,t])=>[e,Array.isArray(t)?`{${t.join(",")}}`:`${t}`]).forEach(([e,t])=>{l.searchParams.append(e,t)})):(a="POST",c=t);const u=new Headers(this.headers);return n&&u.set("Prefer",`count=${n}`),new i.default({method:a,url:l,headers:u,schema:this.schemaName,body:c,fetch:null!==(o=this.fetch)&&void 0!==o?o:fetch})}}t.default=o},646:function(e,t,r){var s=this&&this.__createBinding||(Object.create?function(e,t,r,s){void 0===s&&(s=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,s,n)}:function(e,t,r,s){void 0===s&&(s=r),e[s]=t[r]}),n=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||s(t,e,r)},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.createClient=t.SupabaseClient=t.FunctionRegion=t.FunctionsError=t.FunctionsRelayError=t.FunctionsFetchError=t.FunctionsHttpError=t.PostgrestError=void 0;const o=i(r(13));n(r(166),t);var a=r(739);Object.defineProperty(t,"PostgrestError",{enumerable:!0,get:function(){return a.PostgrestError}});var l=r(231);Object.defineProperty(t,"FunctionsHttpError",{enumerable:!0,get:function(){return l.FunctionsHttpError}}),Object.defineProperty(t,"FunctionsFetchError",{enumerable:!0,get:function(){return l.FunctionsFetchError}}),Object.defineProperty(t,"FunctionsRelayError",{enumerable:!0,get:function(){return l.FunctionsRelayError}}),Object.defineProperty(t,"FunctionsError",{enumerable:!0,get:function(){return l.FunctionsError}}),Object.defineProperty(t,"FunctionRegion",{enumerable:!0,get:function(){return l.FunctionRegion}}),n(r(698),t);var c=r(13);Object.defineProperty(t,"SupabaseClient",{enumerable:!0,get:function(){return i(c).default}}),t.createClient=(e,t,r)=>new o.default(e,t,r),function(){if("undefined"!=typeof window)return!1;if("undefined"==typeof process)return!1;const e=process.version;if(null==e)return!1;const t=e.match(/^v(\d+)\./);return!!t&&parseInt(t[1],10)<=18}()&&console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217")},698:(e,t,r)=>{r.r(t),r.d(t,{REALTIME_CHANNEL_STATES:()=>P,REALTIME_LISTEN_TYPES:()=>j,REALTIME_POSTGRES_CHANGES_LISTEN_EVENT:()=>O,REALTIME_PRESENCE_LISTEN_EVENTS:()=>T,REALTIME_SUBSCRIBE_STATES:()=>R,RealtimeChannel:()=>I,RealtimeClient:()=>x,RealtimePresence:()=>A,WebSocketFactory:()=>s});const s=class{constructor(){}static detectEnvironment(){var e;if("undefined"!=typeof WebSocket)return{type:"native",constructor:WebSocket};if("undefined"!=typeof globalThis&&void 0!==globalThis.WebSocket)return{type:"native",constructor:globalThis.WebSocket};if(void 0!==r.g&&void 0!==r.g.WebSocket)return{type:"native",constructor:r.g.WebSocket};if("undefined"!=typeof globalThis&&void 0!==globalThis.WebSocketPair&&void 0===globalThis.WebSocket)return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if("undefined"!=typeof globalThis&&globalThis.EdgeRuntime||"undefined"!=typeof navigator&&(null===(e=navigator.userAgent)||void 0===e?void 0:e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};if("undefined"!=typeof process){const e=process.versions;if(e&&e.node){const t=e.node,r=parseInt(t.replace(/^v/,"").split(".")[0]);return r>=22?void 0!==globalThis.WebSocket?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${r} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${r} detected without native WebSocket support.`,workaround:'For Node.js < 22, install "ws" package and provide it via the transport option:\nimport ws from "ws"\nnew RealtimeClient(url, { transport: ws })'}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const e=this.detectEnvironment();if(e.constructor)return e.constructor;let t=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(t+=`\n\nSuggested solution: ${e.workaround}`),new Error(t)}static createWebSocket(e,t){return new(this.getWebSocketConstructor())(e,t)}static isWebSocketSupported(){try{const e=this.detectEnvironment();return"native"===e.type||"ws"===e.type}catch(e){return!1}}},n="1.0.0",i=n;var o,a,l,c,u,h;!function(e){e[e.connecting=0]="connecting",e[e.open=1]="open",e[e.closing=2]="closing",e[e.closed=3]="closed"}(o||(o={})),function(e){e.closed="closed",e.errored="errored",e.joined="joined",e.joining="joining",e.leaving="leaving"}(a||(a={})),function(e){e.close="phx_close",e.error="phx_error",e.join="phx_join",e.reply="phx_reply",e.leave="phx_leave",e.access_token="access_token"}(l||(l={})),function(e){e.websocket="websocket"}(c||(c={})),function(e){e.Connecting="connecting",e.Open="open",e.Closing="closing",e.Closed="closed"}(u||(u={}));class d{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=null!=e?e:[]}encode(e,t){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&"string"==typeof e.payload.event)return t(this._binaryEncodeUserBroadcastPush(e));let r=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(r))}_binaryEncodeUserBroadcastPush(e){var t;return this._isArrayBuffer(null===(t=e.payload)||void 0===t?void 0:t.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var t,r;const s=null!==(r=null===(t=e.payload)||void 0===t?void 0:t.payload)&&void 0!==r?r:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,s)}_encodeJsonUserBroadcastPush(e){var t,r;const s=null!==(r=null===(t=e.payload)||void 0===t?void 0:t.payload)&&void 0!==r?r:{},n=(new TextEncoder).encode(JSON.stringify(s)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,n)}_encodeUserBroadcastPush(e,t,r){var s,n;const i=e.topic,o=null!==(s=e.ref)&&void 0!==s?s:"",a=null!==(n=e.join_ref)&&void 0!==n?n:"",l=e.payload.event,c=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},u=0===Object.keys(c).length?"":JSON.stringify(c);if(a.length>255)throw new Error(`joinRef length ${a.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`ref length ${o.length} exceeds maximum of 255`);if(i.length>255)throw new Error(`topic length ${i.length} exceeds maximum of 255`);if(l.length>255)throw new Error(`userEvent length ${l.length} exceeds maximum of 255`);if(u.length>255)throw new Error(`metadata length ${u.length} exceeds maximum of 255`);const h=this.USER_BROADCAST_PUSH_META_LENGTH+a.length+o.length+i.length+l.length+u.length,d=new ArrayBuffer(this.HEADER_LENGTH+h);let f=new DataView(d),p=0;f.setUint8(p++,this.KINDS.userBroadcastPush),f.setUint8(p++,a.length),f.setUint8(p++,o.length),f.setUint8(p++,i.length),f.setUint8(p++,l.length),f.setUint8(p++,u.length),f.setUint8(p++,t),Array.from(a,e=>f.setUint8(p++,e.charCodeAt(0))),Array.from(o,e=>f.setUint8(p++,e.charCodeAt(0))),Array.from(i,e=>f.setUint8(p++,e.charCodeAt(0))),Array.from(l,e=>f.setUint8(p++,e.charCodeAt(0))),Array.from(u,e=>f.setUint8(p++,e.charCodeAt(0)));var g=new Uint8Array(d.byteLength+r.byteLength);return g.set(new Uint8Array(d),0),g.set(new Uint8Array(r),d.byteLength),g.buffer}decode(e,t){if(this._isArrayBuffer(e))return t(this._binaryDecode(e));if("string"==typeof e){const r=JSON.parse(e),[s,n,i,o,a]=r;return t({join_ref:s,ref:n,topic:i,event:o,payload:a})}return t({})}_binaryDecode(e){const t=new DataView(e),r=t.getUint8(0),s=new TextDecoder;if(r===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,t,s)}_decodeUserBroadcast(e,t,r){const s=t.getUint8(1),n=t.getUint8(2),i=t.getUint8(3),o=t.getUint8(4);let a=this.HEADER_LENGTH+4;const l=r.decode(e.slice(a,a+s));a+=s;const c=r.decode(e.slice(a,a+n));a+=n;const u=r.decode(e.slice(a,a+i));a+=i;const h=e.slice(a,e.byteLength),d=o===this.JSON_ENCODING?JSON.parse(r.decode(h)):h,f={type:this.BROADCAST_EVENT,event:c,payload:d};return i>0&&(f.meta=JSON.parse(u)),{join_ref:null,ref:null,topic:l,event:this.BROADCAST_EVENT,payload:f}}_isArrayBuffer(e){var t;return e instanceof ArrayBuffer||"ArrayBuffer"===(null===(t=null==e?void 0:e.constructor)||void 0===t?void 0:t.name)}_pick(e,t){return e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(([e])=>t.includes(e))):{}}}class f{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}!function(e){e.abstime="abstime",e.bool="bool",e.date="date",e.daterange="daterange",e.float4="float4",e.float8="float8",e.int2="int2",e.int4="int4",e.int4range="int4range",e.int8="int8",e.int8range="int8range",e.json="json",e.jsonb="jsonb",e.money="money",e.numeric="numeric",e.oid="oid",e.reltime="reltime",e.text="text",e.time="time",e.timestamp="timestamp",e.timestamptz="timestamptz",e.timetz="timetz",e.tsrange="tsrange",e.tstzrange="tstzrange"}(h||(h={}));const p=(e,t,r={})=>{var s;const n=null!==(s=r.skipTypes)&&void 0!==s?s:[];return t?Object.keys(t).reduce((r,s)=>(r[s]=g(s,e,t,n),r),{}):{}},g=(e,t,r,s)=>{const n=t.find(t=>t.name===e),i=null==n?void 0:n.type,o=r[e];return i&&!s.includes(i)?w(i,o):y(o)},w=(e,t)=>{if("_"===e.charAt(0)){const r=e.slice(1,e.length);return b(t,r)}switch(e){case h.bool:return _(t);case h.float4:case h.float8:case h.int2:case h.int4:case h.int8:case h.numeric:case h.oid:return v(t);case h.json:case h.jsonb:return m(t);case h.timestamp:return E(t);case h.abstime:case h.date:case h.daterange:case h.int4range:case h.int8range:case h.money:case h.reltime:case h.text:case h.time:case h.timestamptz:case h.timetz:case h.tsrange:case h.tstzrange:default:return y(t)}},y=e=>e,_=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},v=e=>{if("string"==typeof e){const t=parseFloat(e);if(!Number.isNaN(t))return t}return e},m=e=>{if("string"==typeof e)try{return JSON.parse(e)}catch(t){return console.log(`JSON parse error: ${t}`),e}return e},b=(e,t)=>{if("string"!=typeof e)return e;const r=e.length-1,s=e[r];if("{"===e[0]&&"}"===s){let s;const n=e.slice(1,r);try{s=JSON.parse("["+n+"]")}catch(e){s=n?n.split(","):[]}return s.map(e=>w(t,e))}return e},E=e=>"string"==typeof e?e.replace(" ","T"):e,k=e=>{const t=new URL(e);return t.protocol=t.protocol.replace(/^ws/i,"http"),t.pathname=t.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),""===t.pathname||"/"===t.pathname?t.pathname="/api/broadcast":t.pathname=t.pathname+"/api/broadcast",t.href};class S{constructor(e,t,r={},s=1e4){this.channel=e,this.event=t,this.payload=r,this.timeout=s,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var r;return this._hasReceived(e)&&t(null===(r=this.receivedResp)||void 0===r?void 0:r.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){this.timeoutTimer||(this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref),this.channel._on(this.refEvent,{},e=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=e,this._matchReceive(e)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout))}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(t=>t.status===e).forEach(e=>e.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var T,O,j,R;!function(e){e.SYNC="sync",e.JOIN="join",e.LEAVE="leave"}(T||(T={}));class A{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const r=(null==t?void 0:t.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},e=>{const{onJoin:t,onLeave:r,onSync:s}=this.caller;this.joinRef=this.channel._joinRef(),this.state=A.syncState(this.state,e,t,r),this.pendingDiffs.forEach(e=>{this.state=A.syncDiff(this.state,e,t,r)}),this.pendingDiffs=[],s()}),this.channel._on(r.diff,{},e=>{const{onJoin:t,onLeave:r,onSync:s}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(e):(this.state=A.syncDiff(this.state,e,t,r),s())}),this.onJoin((e,t,r)=>{this.channel._trigger("presence",{event:"join",key:e,currentPresences:t,newPresences:r})}),this.onLeave((e,t,r)=>{this.channel._trigger("presence",{event:"leave",key:e,currentPresences:t,leftPresences:r})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,r,s){const n=this.cloneDeep(e),i=this.transformState(t),o={},a={};return this.map(n,(e,t)=>{i[e]||(a[e]=t)}),this.map(i,(e,t)=>{const r=n[e];if(r){const s=t.map(e=>e.presence_ref),n=r.map(e=>e.presence_ref),i=t.filter(e=>n.indexOf(e.presence_ref)<0),l=r.filter(e=>s.indexOf(e.presence_ref)<0);i.length>0&&(o[e]=i),l.length>0&&(a[e]=l)}else o[e]=t}),this.syncDiff(n,{joins:o,leaves:a},r,s)}static syncDiff(e,t,r,s){const{joins:n,leaves:i}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||(r=()=>{}),s||(s=()=>{}),this.map(n,(t,s)=>{var n;const i=null!==(n=e[t])&&void 0!==n?n:[];if(e[t]=this.cloneDeep(s),i.length>0){const r=e[t].map(e=>e.presence_ref),s=i.filter(e=>r.indexOf(e.presence_ref)<0);e[t].unshift(...s)}r(t,i,s)}),this.map(i,(t,r)=>{let n=e[t];if(!n)return;const i=r.map(e=>e.presence_ref);n=n.filter(e=>i.indexOf(e.presence_ref)<0),e[t]=n,s(t,n,r),0===n.length&&delete e[t]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(r=>t(r,e[r]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,r)=>{const s=e[r];return t[r]="metas"in s?s.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e)):s,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}!function(e){e.ALL="*",e.INSERT="INSERT",e.UPDATE="UPDATE",e.DELETE="DELETE"}(O||(O={})),function(e){e.BROADCAST="broadcast",e.PRESENCE="presence",e.POSTGRES_CHANGES="postgres_changes",e.SYSTEM="system"}(j||(j={})),function(e){e.SUBSCRIBED="SUBSCRIBED",e.TIMED_OUT="TIMED_OUT",e.CLOSED="CLOSED",e.CHANNEL_ERROR="CHANNEL_ERROR"}(R||(R={}));const P=a;class I{constructor(e,t={config:{}},r){var s,n;if(this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=a.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config),this.timeout=this.socket.timeout,this.joinPush=new S(this,l.join,this.params,this.timeout),this.rejoinTimer=new f(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=a.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(e=>e.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=a.closed,this.socket._remove(this)}),this._onError(e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=a.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=a.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=a.errored,this.rejoinTimer.scheduleTimeout())}),this._on(l.reply,{},(e,t)=>{this._trigger(this._replyEventName(t),e)}),this.presence=new A(this),this.broadcastEndpointURL=k(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&(null===(n=null===(s=this.params.config)||void 0===s?void 0:s.broadcast)||void 0===n?void 0:n.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,t=this.timeout){var r,s,n;if(this.socket.isConnected()||this.socket.connect(),this.state==a.closed){const{config:{broadcast:i,presence:o,private:l}}=this.params,c=null!==(s=null===(r=this.bindings.postgres_changes)||void 0===r?void 0:r.map(e=>e.filter))&&void 0!==s?s:[],u=!!this.bindings[j.PRESENCE]&&this.bindings[j.PRESENCE].length>0||!0===(null===(n=this.params.config.presence)||void 0===n?void 0:n.enabled),h={},d={broadcast:i,presence:Object.assign(Object.assign({},o),{enabled:u}),postgres_changes:c,private:l};this.socket.accessTokenValue&&(h.access_token=this.socket.accessTokenValue),this._onError(t=>null==e?void 0:e(R.CHANNEL_ERROR,t)),this._onClose(()=>null==e?void 0:e(R.CLOSED)),this.updateJoinPayload(Object.assign({config:d},h)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",async({postgres_changes:t})=>{var r;if(this.socket._isManualToken()||this.socket.setAuth(),void 0!==t){const s=this.bindings.postgres_changes,n=null!==(r=null==s?void 0:s.length)&&void 0!==r?r:0,i=[];for(let r=0;r{this.state=a.errored,null==e||e(R.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(t).join(", ")||"error")))}).receive("timeout",()=>{null==e||e(R.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,r){return this.state===a.joined&&e===j.PRESENCE&&(this.socket.log("channel",`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(async()=>await this.subscribe())),this._on(e,t,r)}async httpSend(e,t,r={}){var s;const n=this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"";if(null==t)return Promise.reject("Payload is required for httpSend()");const i={method:"POST",headers:{Authorization:n,apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:t,private:this.private}]})},o=await this._fetchWithTimeout(this.broadcastEndpointURL,i,null!==(s=r.timeout)&&void 0!==s?s:this.timeout);if(202===o.status)return{success:!0};let a=o.statusText;try{const e=await o.json();a=e.error||e.message||a}catch(e){}return Promise.reject(new Error(a))}async send(e,t={}){var r,s;if(this._canPush()||"broadcast"!==e.type)return new Promise(r=>{var s,n,i;const o=this._push(e.type,e,t.timeout||this.timeout);"broadcast"!==e.type||(null===(i=null===(n=null===(s=this.params)||void 0===s?void 0:s.config)||void 0===n?void 0:n.broadcast)||void 0===i?void 0:i.ack)||r("ok"),o.receive("ok",()=>r("ok")),o.receive("error",()=>r("error")),o.receive("timeout",()=>r("timed out"))});{console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");const{event:n,payload:i}=e,o={method:"POST",headers:{Authorization:this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:i,private:this.private}]})};try{const e=await this._fetchWithTimeout(this.broadcastEndpointURL,o,null!==(r=t.timeout)&&void 0!==r?r:this.timeout);return await(null===(s=e.body)||void 0===s?void 0:s.cancel()),e.ok?"ok":"error"}catch(e){return"AbortError"===e.name?"timed out":"error"}}}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=a.leaving;const t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(l.close,"leave",this._joinRef())};this.joinPush.destroy();let r=null;return new Promise(s=>{r=new S(this,l.leave,{},e),r.receive("ok",()=>{t(),s("ok")}).receive("timeout",()=>{t(),s("timed out")}).receive("error",()=>{s("error")}),r.send(),this._canPush()||r.trigger("ok",{})}).finally(()=>{null==r||r.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=a.closed,this.bindings={}}async _fetchWithTimeout(e,t,r){const s=new AbortController,n=setTimeout(()=>s.abort(),r),i=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:s.signal}));return clearTimeout(n),i}_push(e,t,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let s=new S(this,e,t,r);return this._canPush()?s.send():this._addToPushBuffer(s),s}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>100){const e=this.pushBuffer.shift();e&&(e.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${e.event}`,e.payload))}}_onMessage(e,t,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var s,n;const i=e.toLocaleLowerCase(),{close:o,error:a,leave:c,join:u}=l;if(r&&[o,a,c,u].indexOf(i)>=0&&r!==this._joinRef())return;let h=this._onMessage(i,t,r);if(t&&!h)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(i)?null===(s=this.bindings.postgres_changes)||void 0===s||s.filter(e=>{var t,r,s;return"*"===(null===(t=e.filter)||void 0===t?void 0:t.event)||(null===(s=null===(r=e.filter)||void 0===r?void 0:r.event)||void 0===s?void 0:s.toLocaleLowerCase())===i}).map(e=>e.callback(h,r)):null===(n=this.bindings[i])||void 0===n||n.filter(e=>{var r,s,n,o,a,l;if(["broadcast","presence","postgres_changes"].includes(i)){if("id"in e){const i=e.id,o=null===(r=e.filter)||void 0===r?void 0:r.event;return i&&(null===(s=t.ids)||void 0===s?void 0:s.includes(i))&&("*"===o||(null==o?void 0:o.toLocaleLowerCase())===(null===(n=t.data)||void 0===n?void 0:n.type.toLocaleLowerCase()))}{const r=null===(a=null===(o=null==e?void 0:e.filter)||void 0===o?void 0:o.event)||void 0===a?void 0:a.toLocaleLowerCase();return"*"===r||r===(null===(l=null==t?void 0:t.event)||void 0===l?void 0:l.toLocaleLowerCase())}}return e.type.toLocaleLowerCase()===i}).map(e=>{if("object"==typeof h&&"ids"in h){const e=h.data,{schema:t,table:r,commit_timestamp:s,type:n,errors:i}=e,o={schema:t,table:r,commit_timestamp:s,eventType:n,new:{},old:{},errors:i};h=Object.assign(Object.assign({},o),this._getPayloadRecords(e))}e.callback(h,r)})}_isClosed(){return this.state===a.closed}_isJoined(){return this.state===a.joined}_isJoining(){return this.state===a.joining}_isLeaving(){return this.state===a.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,r){const s=e.toLocaleLowerCase(),n={type:s,filter:t,callback:r};return this.bindings[s]?this.bindings[s].push(n):this.bindings[s]=[n],this}_off(e,t){const r=e.toLocaleLowerCase();return this.bindings[r]&&(this.bindings[r]=this.bindings[r].filter(e=>{var s;return!((null===(s=e.type)||void 0===s?void 0:s.toLocaleLowerCase())===r&&I.isEqual(e.filter,t))})),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const r in e)if(e[r]!==t[r])return!1;return!0}static isFilterValueEqual(e,t){return(null!=e?e:void 0)===(null!=t?t:void 0)}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(l.close,{},e)}_onError(e){this._on(l.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=a.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const t={new:{},old:{}};return"INSERT"!==e.type&&"UPDATE"!==e.type||(t.new=p(e.columns,e.record)),"UPDATE"!==e.type&&"DELETE"!==e.type||(t.old=p(e.columns,e.old_record)),t}}const $=()=>{},C=[1e3,2e3,5e3,1e4];class x{constructor(e,t){var r;if(this.accessTokenValue=null,this.apiKey=null,this._manuallySetToken=!1,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=1e4,this.transport=null,this.heartbeatIntervalMs=25e3,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=$,this.ref=0,this.reconnectTimer=null,this.vsn=i,this.logger=$,this.conn=null,this.sendBuffer=[],this.serializer=new d,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._resolveFetch=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),!(null===(r=null==t?void 0:t.params)||void 0===r?void 0:r.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey,this.endPoint=`${e}/${c.websocket}`,this.httpEndpoint=k(e),this._initializeOptions(t),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(null==t?void 0:t.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||null!==this.conn&&this.isConnected())){if(this._setConnectionState("connecting"),this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=s.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");const t=e.message;if(t.includes("Node.js"))throw new Error(`${t}\n\nTo use Realtime in Node.js, you need to provide a WebSocket implementation:\n\nOption 1: Use Node.js 22+ which has native WebSocket support\nOption 2: Install and provide the "ws" package:\n\n npm install ws\n\n import ws from "ws"\n const client = new RealtimeClient(url, {\n ...options,\n transport: ws\n })`);throw new Error(`WebSocket not available: ${t}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:this.vsn}))}disconnect(e,t){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){const r=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(r),this._setConnectionState("disconnected")},"function"==typeof this.conn.close&&(e?this.conn.close(e,null!=t?t:""):this.conn.close()),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(e){const t=await e.unsubscribe();return 0===this.channels.length&&this.disconnect(),t}async removeAllChannels(){const e=await Promise.all(this.channels.map(e=>e.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,t,r){this.logger(e,t,r)}connectionState(){switch(this.conn&&this.conn.readyState){case o.connecting:return u.Connecting;case o.open:return u.Open;case o.closing:return u.Closing;default:return u.Closed}}isConnected(){return this.connectionState()===u.Open}isConnecting(){return"connecting"===this._connectionState}isDisconnecting(){return"disconnecting"===this._connectionState}channel(e,t={config:{}}){const r=`realtime:${e}`,s=this.getChannels().find(e=>e.topic===r);if(s)return s;{const r=new I(`realtime:${e}`,t,this);return this.channels.push(r),r}}push(e){const{topic:t,event:r,payload:s,ref:n}=e,i=()=>{this.encode(e,e=>{var t;null===(t=this.conn)||void 0===t||t.send(e)})};this.log("push",`${t} ${r} (${n})`,s),this.isConnected()?i():this.sendBuffer.push(i)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(e){this.log("error","error in heartbeat callback",e)}return this._wasManualDisconnect=!1,null===(e=this.conn)||void 0===e||e.close(1e3,"heartbeat timeout"),void setTimeout(()=>{var e;this.isConnected()||null===(e=this.reconnectTimer)||void 0===e||e.scheduleTimeout()},100)}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(e){this.log("error","error in heartbeat callback",e)}this._setAuthSafely("heartbeat")}else try{this.heartbeatCallback("disconnected")}catch(e){this.log("error","error in heartbeat callback",e)}}onHeartbeat(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(t=>t.topic===e&&(t._isJoined()||t._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,e=>{if("phoenix"===e.topic&&"phx_reply"===e.event)try{this.heartbeatCallback("ok"===e.payload.status?"ok":"error")}catch(e){this.log("error","error in heartbeat callback",e)}e.ref&&e.ref===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null);const{topic:t,event:r,payload:s,ref:n}=e,i=n?`(${n})`:"",o=s.status||"";this.log("receive",`${o} ${t} ${r} ${i}`.trim(),s),this.channels.filter(e=>e._isMember(t)).forEach(e=>e._trigger(r,s,n)),this._triggerStateCallbacks("message",e)})}_clearTimer(e){var t;"heartbeat"===e&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):"reconnect"===e&&(null===(t=this.reconnectTimer)||void 0===t||t.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in this.conn&&(this.conn.binaryType="arraybuffer"),this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_teardownConnection(){if(this.conn){if(this.conn.readyState===o.open||this.conn.readyState===o.connecting)try{this.conn.close()}catch(e){this.log("error","Error closing connection",e)}this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null}this._clearAllTimers(),this.channels.forEach(e=>e.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`),(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).then(()=>{this.flushSendBuffer()}).catch(e=>{this.log("error","error waiting for auth on connect",e),this.flushSendBuffer()}),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=e=>{this.log("worker","worker error",e.message),this.workerRef.terminate()},this.workerRef.onmessage=e=>{"keepAlive"===e.data.event&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_onConnClose(e){var t;this._setConnectionState("disconnected"),this.log("transport","close",e),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||null===(t=this.reconnectTimer)||void 0===t||t.scheduleTimeout(),this._triggerStateCallbacks("close",e)}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport",`${e}`),this._triggerChanError(),this._triggerStateCallbacks("error",e)}_triggerChanError(){this.channels.forEach(e=>e._trigger(l.error))}_appendParams(e,t){if(0===Object.keys(t).length)return e;const r=e.match(/\?/)?"&":"?";return`${e}${r}${new URLSearchParams(t)}`}_workerObjectUrl(e){let t;if(e)t=e;else{const e=new Blob(['\n addEventListener("message", (e) => {\n if (e.data.event === "start") {\n setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);\n }\n });'],{type:"application/javascript"});t=URL.createObjectURL(e)}return t}_setConnectionState(e,t=!1){this._connectionState=e,"connecting"===e?this._wasManualDisconnect=!1:"disconnecting"===e&&(this._wasManualDisconnect=t)}async _performAuth(e=null){let t,r=!1;if(e)t=e,r=!0;else if(this.accessToken)try{t=await this.accessToken()}catch(e){this.log("error","Error fetching access token from callback",e),t=this.accessTokenValue}else t=this.accessTokenValue;r?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=t&&(this.accessTokenValue=t,this.channels.forEach(e=>{const r={access_token:t,version:"realtime-js/2.87.1"};t&&e.updateJoinPayload(r),e.joinedOnce&&e._isJoined()&&e._push(l.access_token,{access_token:t})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(t=>{this.log("error",`Error setting auth in ${e}`,t)})}_triggerStateCallbacks(e,t){try{this.stateChangeCallbacks[e].forEach(r=>{try{r(t)}catch(t){this.log("error",`error in ${e} callback`,t)}})}catch(t){this.log("error",`error triggering ${e} callbacks`,t)}}_setupReconnectionTimer(){this.reconnectTimer=new f(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},10)},this.reconnectAfterMs)}_initializeOptions(e){var t,r,s,o,a,l,c,u,h,d,f,p;switch(this.transport=null!==(t=null==e?void 0:e.transport)&&void 0!==t?t:null,this.timeout=null!==(r=null==e?void 0:e.timeout)&&void 0!==r?r:1e4,this.heartbeatIntervalMs=null!==(s=null==e?void 0:e.heartbeatIntervalMs)&&void 0!==s?s:25e3,this.worker=null!==(o=null==e?void 0:e.worker)&&void 0!==o&&o,this.accessToken=null!==(a=null==e?void 0:e.accessToken)&&void 0!==a?a:null,this.heartbeatCallback=null!==(l=null==e?void 0:e.heartbeatCallback)&&void 0!==l?l:$,this.vsn=null!==(c=null==e?void 0:e.vsn)&&void 0!==c?c:i,(null==e?void 0:e.params)&&(this.params=e.params),(null==e?void 0:e.logger)&&(this.logger=e.logger),((null==e?void 0:e.logLevel)||(null==e?void 0:e.log_level))&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=null!==(u=null==e?void 0:e.reconnectAfterMs)&&void 0!==u?u:e=>C[e-1]||1e4,this.vsn){case n:this.encode=null!==(h=null==e?void 0:e.encode)&&void 0!==h?h:(e,t)=>t(JSON.stringify(e)),this.decode=null!==(d=null==e?void 0:e.decode)&&void 0!==d?d:(e,t)=>t(JSON.parse(e));break;case"2.0.0":this.encode=null!==(f=null==e?void 0:e.encode)&&void 0!==f?f:this.serializer.encode.bind(this.serializer),this.decode=null!==(p=null==e?void 0:e.decode)&&void 0!==p?p:this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${this.vsn}`)}if(this.worker){if("undefined"!=typeof window&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=null==e?void 0:e.workerUrl}}}},705:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0});const s=r(823).__importDefault(r(973));t.default=class{constructor(e,{headers:t={},schema:r,fetch:s}){this.url=e,this.headers=new Headers(t),this.schema=r,this.fetch=s}select(e,t){const{head:r=!1,count:n}=null!=t?t:{},i=r?"HEAD":"GET";let o=!1;const a=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!o?"":('"'===e&&(o=!o),e)).join("");return this.url.searchParams.set("select",a),n&&this.headers.append("Prefer",`count=${n}`),new s.default({method:i,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch})}insert(e,{count:t,defaultToNull:r=!0}={}){var n;if(t&&this.headers.append("Prefer",`count=${t}`),r||this.headers.append("Prefer","missing=default"),Array.isArray(e)){const t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){const e=[...new Set(t)].map(e=>`"${e}"`);this.url.searchParams.set("columns",e.join(","))}}return new s.default({method:"POST",url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:null!==(n=this.fetch)&&void 0!==n?n:fetch})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:n,defaultToNull:i=!0}={}){var o;if(this.headers.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),void 0!==t&&this.url.searchParams.set("on_conflict",t),n&&this.headers.append("Prefer",`count=${n}`),i||this.headers.append("Prefer","missing=default"),Array.isArray(e)){const t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){const e=[...new Set(t)].map(e=>`"${e}"`);this.url.searchParams.set("columns",e.join(","))}}return new s.default({method:"POST",url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:null!==(o=this.fetch)&&void 0!==o?o:fetch})}update(e,{count:t}={}){var r;return t&&this.headers.append("Prefer",`count=${t}`),new s.default({method:"PATCH",url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:null!==(r=this.fetch)&&void 0!==r?r:fetch})}delete({count:e}={}){var t;return e&&this.headers.append("Prefer",`count=${e}`),new s.default({method:"DELETE",url:this.url,headers:this.headers,schema:this.schema,fetch:null!==(t=this.fetch)&&void 0!==t?t:fetch})}}},739:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PostgrestError=t.PostgrestBuilder=t.PostgrestTransformBuilder=t.PostgrestFilterBuilder=t.PostgrestQueryBuilder=t.PostgrestClient=void 0;const s=r(823),n=s.__importDefault(r(597));t.PostgrestClient=n.default;const i=s.__importDefault(r(705));t.PostgrestQueryBuilder=i.default;const o=s.__importDefault(r(973));t.PostgrestFilterBuilder=o.default;const a=s.__importDefault(r(817));t.PostgrestTransformBuilder=a.default;const l=s.__importDefault(r(595));t.PostgrestBuilder=l.default;const c=s.__importDefault(r(886));t.PostgrestError=c.default,t.default={PostgrestClient:n.default,PostgrestQueryBuilder:i.default,PostgrestFilterBuilder:o.default,PostgrestTransformBuilder:a.default,PostgrestBuilder:l.default,PostgrestError:c.default}},795:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SupabaseAuthClient=void 0;const s=r(166);class n extends s.AuthClient{constructor(e){super(e)}}t.SupabaseAuthClient=n},817:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0});const s=r(823).__importDefault(r(595));class n extends s.default{select(e){let t=!1;const r=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!t?"":('"'===e&&(t=!t),e)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(e,{ascending:t=!0,nullsFirst:r,foreignTable:s,referencedTable:n=s}={}){const i=n?`${n}.order`:"order",o=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${o?`${o},`:""}${e}.${t?"asc":"desc"}${void 0===r?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:r=t}={}){const s=void 0===r?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${e}`),this}range(e,t,{foreignTable:r,referencedTable:s=r}={}){const n=void 0===s?"offset":`${s}.offset`,i=void 0===s?"limit":`${s}.limit`;return this.url.searchParams.set(n,`${e}`),this.url.searchParams.set(i,""+(t-e+1)),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return"GET"===this.method?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:e=!1,verbose:t=!1,settings:r=!1,buffers:s=!1,wal:n=!1,format:i="text"}={}){var o;const a=[e?"analyze":null,t?"verbose":null,r?"settings":null,s?"buffers":null,n?"wal":null].filter(Boolean).join("|"),l=null!==(o=this.headers.get("Accept"))&&void 0!==o?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${l}"; options=${a};`),this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(e){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${e}`),this}}t.default=n},819:(e,t)=>{function r(e){return e.endsWith("/")?e:e+"/"}Object.defineProperty(t,"__esModule",{value:!0}),t.isBrowser=void 0,t.uuid=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)})},t.ensureTrailingSlash=r,t.applySettingDefaults=function(e,t){var r,s;const{db:n,auth:i,realtime:o,global:a}=e,{db:l,auth:c,realtime:u,global:h}=t,d={db:Object.assign(Object.assign({},l),n),auth:Object.assign(Object.assign({},c),i),realtime:Object.assign(Object.assign({},u),o),storage:{},global:Object.assign(Object.assign(Object.assign({},h),a),{headers:Object.assign(Object.assign({},null!==(r=null==h?void 0:h.headers)&&void 0!==r?r:{}),null!==(s=null==a?void 0:a.headers)&&void 0!==s?s:{})}),accessToken:async()=>""};return e.accessToken?d.accessToken=e.accessToken:delete d.accessToken,d},t.validateSupabaseUrl=function(e){const t=null==e?void 0:e.trim();if(!t)throw new Error("supabaseUrl is required.");if(!t.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(r(t))}catch(e){throw Error("Invalid supabaseUrl: Provided URL is malformed.")}},t.isBrowser=()=>"undefined"!=typeof window},822:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.version=void 0,t.version="2.87.1"},823:(e,t,r)=>{r.r(t),r.d(t,{__addDisposableResource:()=>N,__assign:()=>i,__asyncDelegator:()=>T,__asyncGenerator:()=>S,__asyncValues:()=>O,__await:()=>k,__awaiter:()=>p,__classPrivateFieldGet:()=>$,__classPrivateFieldIn:()=>x,__classPrivateFieldSet:()=>C,__createBinding:()=>w,__decorate:()=>a,__disposeResources:()=>D,__esDecorate:()=>c,__exportStar:()=>y,__extends:()=>n,__generator:()=>g,__importDefault:()=>I,__importStar:()=>P,__makeTemplateObject:()=>j,__metadata:()=>f,__param:()=>l,__propKey:()=>h,__read:()=>v,__rest:()=>o,__rewriteRelativeImportExtension:()=>L,__runInitializers:()=>u,__setFunctionName:()=>d,__spread:()=>m,__spreadArray:()=>E,__spreadArrays:()=>b,__values:()=>_,default:()=>B});var s=function(e,t){return s=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},s(e,t)};function n(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}s(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var i=function(){return i=Object.assign||function(e){for(var t,r=1,s=arguments.length;r=0;a--)(n=e[a])&&(o=(i<3?n(o):i>3?n(t,r,o):n(t,r))||o);return i>3&&o&&Object.defineProperty(t,r,o),o}function l(e,t){return function(r,s){t(r,s,e)}}function c(e,t,r,s,n,i){function o(e){if(void 0!==e&&"function"!=typeof e)throw new TypeError("Function expected");return e}for(var a,l=s.kind,c="getter"===l?"get":"setter"===l?"set":"value",u=!t&&e?s.static?e:e.prototype:null,h=t||(u?Object.getOwnPropertyDescriptor(u,s.name):{}),d=!1,f=r.length-1;f>=0;f--){var p={};for(var g in s)p[g]="access"===g?{}:s[g];for(var g in s.access)p.access[g]=s.access[g];p.addInitializer=function(e){if(d)throw new TypeError("Cannot add initializers after decoration has completed");i.push(o(e||null))};var w=(0,r[f])("accessor"===l?{get:h.get,set:h.set}:h[c],p);if("accessor"===l){if(void 0===w)continue;if(null===w||"object"!=typeof w)throw new TypeError("Object expected");(a=o(w.get))&&(h.get=a),(a=o(w.set))&&(h.set=a),(a=o(w.init))&&n.unshift(a)}else(a=o(w))&&("field"===l?n.unshift(a):h[c]=a)}u&&Object.defineProperty(u,s.name,h),d=!0}function u(e,t,r){for(var s=arguments.length>2,n=0;n0&&n[n.length-1])||6!==a[0]&&2!==a[0])){i=0;continue}if(3===a[0]&&(!n||a[1]>n[0]&&a[1]=e.length&&(e=void 0),{value:e&&e[s++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function v(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var s,n,i=r.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(s=i.next()).done;)o.push(s.value)}catch(e){n={error:e}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}return o}function m(){for(var e=[],t=0;t1||a(e,t)})},t&&(s[e]=t(s[e])))}function a(e,t){try{(r=n[e](t)).value instanceof k?Promise.resolve(r.value.v).then(l,c):u(i[0][2],r)}catch(e){u(i[0][3],e)}var r}function l(e){a("next",e)}function c(e){a("throw",e)}function u(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}}function T(e){var t,r;return t={},s("next"),s("throw",function(e){throw e}),s("return"),t[Symbol.iterator]=function(){return this},t;function s(s,n){t[s]=e[s]?function(t){return(r=!r)?{value:k(e[s](t)),done:!1}:n?n(t):t}:n}}function O(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=_(e),t={},s("next"),s("throw"),s("return"),t[Symbol.asyncIterator]=function(){return this},t);function s(r){t[r]=e[r]&&function(t){return new Promise(function(s,n){!function(e,t,r,s){Promise.resolve(s).then(function(t){e({value:t,done:r})},t)}(s,n,(t=e[r](t)).done,t.value)})}}}function j(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}var R=Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t},A=function(e){return A=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},A(e)};function P(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=A(e),s=0;s{Object.defineProperty(t,"__esModule",{value:!0});class r extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}}t.default=r},973:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0});const s=r(823).__importDefault(r(817)),n=new RegExp("[,()]");class i extends s.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}regexMatch(e,t){return this.url.searchParams.append(e,`match.${t}`),this}regexIMatch(e,t){return this.url.searchParams.append(e,`imatch.${t}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}isDistinct(e,t){return this.url.searchParams.append(e,`isdistinct.${t}`),this}in(e,t){const r=Array.from(new Set(t)).map(e=>"string"==typeof e&&n.test(e)?`"${e}"`:`${e}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}contains(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return"string"==typeof t?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:r,type:s}={}){let n="";"plain"===s?n="pl":"phrase"===s?n="ph":"websearch"===s&&(n="w");const i=void 0===r?"":`(${r})`;return this.url.searchParams.append(e,`${n}fts${i}.${t}`),this}match(e){return Object.entries(e).forEach(([e,t])=>{this.url.searchParams.append(e,`eq.${t}`)}),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t,referencedTable:r=t}={}){const s=r?`${r}.or`:"or";return this.url.searchParams.append(s,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}}t.default=i}},t={};function r(s){var n=t[s];if(void 0!==n)return n.exports;var i=t[s]={exports:{}};return e[s].call(i.exports,i,i.exports,r),i.exports}return r.d=(e,t)=>{for(var s in t)r.o(t,s)&&!r.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r(646)})()); \ No newline at end of file diff --git a/backend/node_modules/@supabase/supabase-js/package.json b/backend/node_modules/@supabase/supabase-js/package.json new file mode 100644 index 0000000..36d3a88 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/package.json @@ -0,0 +1,111 @@ +{ + "name": "@supabase/supabase-js", + "version": "2.87.1", + "description": "Isomorphic Javascript SDK for Supabase", + "keywords": [ + "javascript", + "typescript", + "supabase" + ], + "homepage": "https://github.com/supabase/supabase-js/tree/master/packages/core/supabase-js", + "bugs": "https://github.com/supabase/supabase-js/issues", + "license": "MIT", + "author": "Supabase", + "files": [ + "dist", + "src" + ], + "main": "dist/main/index.js", + "module": "dist/esm/wrapper.mjs", + "types": "dist/module/index.d.ts", + "exports": { + ".": { + "types": "./dist/module/index.d.ts", + "import": "./dist/esm/wrapper.mjs", + "require": "./dist/main/index.js" + }, + "./dist/module/*": "./dist/module/*", + "./package.json": "./package.json" + }, + "sideEffects": false, + "repository": { + "type": "git", + "url": "https://github.com/supabase/supabase-js.git", + "directory": "packages/core/supabase-js" + }, + "scripts": { + "build": "npm run build:main && npm run build:module && npm run build:esm && npm run build:umd", + "build:main": "tsc -p tsconfig.json", + "build:module": "tsc -p tsconfig.module.json", + "build:esm": "node scripts/copy-wrapper.cjs", + "build:umd": "webpack --env mode=production", + "test": "npm run test:types && npm run test:run", + "test:all": "npm run test:types && npm run test:run && npm run test:integration && npm run test:integration:browser", + "test:run": "jest --runInBand --detectOpenHandles", + "test:unit": "jest --runInBand --detectOpenHandles test/unit", + "test:coverage": "jest --runInBand --coverage --testPathIgnorePatterns=\"test/integration|test/deno\"", + "test:integration": "jest --runInBand --detectOpenHandles test/integration.test.ts", + "test:integration:browser": "deno test --allow-all test/integration.browser.test.ts", + "test:edge-functions": "cd test/deno && npm run test:edge-functions", + "test:deno": "cd test/deno && npm run test", + "test:watch": "jest --watch --verbose false --silent false", + "test:node:playwright": "cd test/integration/node-browser && npm install && cp ../../../dist/umd/supabase.js . && npm run test", + "test:bun": "cd test/integration/bun && bun install && bun test", + "test:expo": "cd test/integration/expo && npm test", + "test:next": "cd test/integration/next && npm test", + "test:types": "tsd --files test/types/*.test-d.ts && jsr publish --dry-run --allow-dirty", + "docs": "typedoc --entryPoints src/index.ts --out docs/v2", + "docs:json": "typedoc --entryPoints src/index.ts --json docs/v2/spec.json --excludeExternals", + "serve:coverage": "npx nx test:coverage supabase-js && serve test/coverage", + "update:test-deps": "npm run update:test-deps:expo && npm run update:test-deps:next && npm run update:test-deps:deno && npm run update:test-deps:bun", + "update:test-deps:expo": "cd test/integration/expo && npm install", + "update:test-deps:next": "cd test/integration/next && npm install", + "update:test-deps:deno": "cd test/deno && npm install", + "update:test-deps:bun": "cd test/integration/bun && bun install" + }, + "dependencies": { + "@supabase/auth-js": "2.87.1", + "@supabase/functions-js": "2.87.1", + "@supabase/postgrest-js": "2.87.1", + "@supabase/realtime-js": "2.87.1", + "@supabase/storage-js": "2.87.1" + }, + "devDependencies": { + "jsr": "^0.13.5", + "puppeteer": "^24.9.0", + "serve": "^14.2.1", + "ts-loader": "^9.5.4", + "tsd": "^0.30.4", + "webpack": "^5.69.1", + "webpack-cli": "^4.9.2" + }, + "jsdelivr": "dist/umd/supabase.js", + "unpkg": "dist/umd/supabase.js", + "nx": { + "targets": { + "test:integration:browser": { + "dependsOn": [ + { + "projects": [ + "storage-js" + ], + "target": "build" + } + ] + }, + "test:edge-functions": { + "dependsOn": [ + { + "projects": [ + "storage-js" + ], + "target": "build" + } + ] + } + } + }, + "engines": { + "node": ">=20.0.0" + } +} diff --git a/backend/node_modules/@supabase/supabase-js/src/SupabaseClient.ts b/backend/node_modules/@supabase/supabase-js/src/SupabaseClient.ts new file mode 100644 index 0000000..6defb4e --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/src/SupabaseClient.ts @@ -0,0 +1,419 @@ +import type { AuthChangeEvent } from '@supabase/auth-js' +import { FunctionsClient } from '@supabase/functions-js' +import { + PostgrestClient, + type PostgrestFilterBuilder, + type PostgrestQueryBuilder, +} from '@supabase/postgrest-js' +import { + type RealtimeChannel, + type RealtimeChannelOptions, + RealtimeClient, + type RealtimeClientOptions, +} from '@supabase/realtime-js' +import { StorageClient as SupabaseStorageClient } from '@supabase/storage-js' +import { + DEFAULT_AUTH_OPTIONS, + DEFAULT_DB_OPTIONS, + DEFAULT_GLOBAL_OPTIONS, + DEFAULT_REALTIME_OPTIONS, +} from './lib/constants' +import { fetchWithAuth } from './lib/fetch' +import { applySettingDefaults, validateSupabaseUrl } from './lib/helpers' +import { SupabaseAuthClient } from './lib/SupabaseAuthClient' +import type { + Fetch, + GenericSchema, + SupabaseAuthClientOptions, + SupabaseClientOptions, +} from './lib/types' +import { GetRpcFunctionFilterBuilderByArgs } from './lib/rest/types/common/rpc' + +/** + * Supabase Client. + * + * An isomorphic Javascript client for interacting with Postgres. + */ +export default class SupabaseClient< + Database = any, + // The second type parameter is also used for specifying db_schema, so we + // support both cases. + // TODO: Allow setting db_schema from ClientOptions. + SchemaNameOrClientOptions extends + | (string & keyof Omit) + | { PostgrestVersion: string } = 'public' extends keyof Omit + ? 'public' + : string & keyof Omit, + SchemaName extends string & + keyof Omit = SchemaNameOrClientOptions extends string & + keyof Omit + ? SchemaNameOrClientOptions + : 'public' extends keyof Omit + ? 'public' + : string & keyof Omit, '__InternalSupabase'>, + Schema extends Omit[SchemaName] extends GenericSchema + ? Omit[SchemaName] + : never = Omit[SchemaName] extends GenericSchema + ? Omit[SchemaName] + : never, + ClientOptions extends { PostgrestVersion: string } = SchemaNameOrClientOptions extends string & + keyof Omit + ? // If the version isn't explicitly set, look for it in the __InternalSupabase object to infer the right version + Database extends { __InternalSupabase: { PostgrestVersion: string } } + ? Database['__InternalSupabase'] + : // otherwise default to 12 + { PostgrestVersion: '12' } + : SchemaNameOrClientOptions extends { PostgrestVersion: string } + ? SchemaNameOrClientOptions + : never, +> { + /** + * Supabase Auth allows you to create and manage user sessions for access to data that is secured by access policies. + */ + auth: SupabaseAuthClient + realtime: RealtimeClient + /** + * Supabase Storage allows you to manage user-generated content, such as photos or videos. + */ + storage: SupabaseStorageClient + + protected realtimeUrl: URL + protected authUrl: URL + protected storageUrl: URL + protected functionsUrl: URL + protected rest: PostgrestClient + protected storageKey: string + protected fetch?: Fetch + protected changedAccessToken?: string + protected accessToken?: () => Promise + + protected headers: Record + + /** + * Create a new client for use in the browser. + * @param supabaseUrl The unique Supabase URL which is supplied when you create a new project in your project dashboard. + * @param supabaseKey The unique Supabase Key which is supplied when you create a new project in your project dashboard. + * @param options.db.schema You can switch in between schemas. The schema needs to be on the list of exposed schemas inside Supabase. + * @param options.auth.autoRefreshToken Set to "true" if you want to automatically refresh the token before expiring. + * @param options.auth.persistSession Set to "true" if you want to automatically save the user session into local storage. + * @param options.auth.detectSessionInUrl Set to "true" if you want to automatically detects OAuth grants in the URL and signs in the user. + * @param options.realtime Options passed along to realtime-js constructor. + * @param options.storage Options passed along to the storage-js constructor. + * @param options.global.fetch A custom fetch implementation. + * @param options.global.headers Any additional headers to send with each network request. + * @example + * ```ts + * import { createClient } from '@supabase/supabase-js' + * + * const supabase = createClient('https://xyzcompany.supabase.co', 'public-anon-key') + * const { data } = await supabase.from('profiles').select('*') + * ``` + */ + constructor( + protected supabaseUrl: string, + protected supabaseKey: string, + options?: SupabaseClientOptions + ) { + const baseUrl = validateSupabaseUrl(supabaseUrl) + if (!supabaseKey) throw new Error('supabaseKey is required.') + + this.realtimeUrl = new URL('realtime/v1', baseUrl) + this.realtimeUrl.protocol = this.realtimeUrl.protocol.replace('http', 'ws') + this.authUrl = new URL('auth/v1', baseUrl) + this.storageUrl = new URL('storage/v1', baseUrl) + this.functionsUrl = new URL('functions/v1', baseUrl) + + // default storage key uses the supabase project ref as a namespace + const defaultStorageKey = `sb-${baseUrl.hostname.split('.')[0]}-auth-token` + const DEFAULTS = { + db: DEFAULT_DB_OPTIONS, + realtime: DEFAULT_REALTIME_OPTIONS, + auth: { ...DEFAULT_AUTH_OPTIONS, storageKey: defaultStorageKey }, + global: DEFAULT_GLOBAL_OPTIONS, + } + + const settings = applySettingDefaults(options ?? {}, DEFAULTS) + + this.storageKey = settings.auth.storageKey ?? '' + this.headers = settings.global.headers ?? {} + + if (!settings.accessToken) { + this.auth = this._initSupabaseAuthClient( + settings.auth ?? {}, + this.headers, + settings.global.fetch + ) + } else { + this.accessToken = settings.accessToken + + this.auth = new Proxy({} as any, { + get: (_, prop) => { + throw new Error( + `@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String( + prop + )} is not possible` + ) + }, + }) + } + + this.fetch = fetchWithAuth(supabaseKey, this._getAccessToken.bind(this), settings.global.fetch) + this.realtime = this._initRealtimeClient({ + headers: this.headers, + accessToken: this._getAccessToken.bind(this), + ...settings.realtime, + }) + if (this.accessToken) { + // Start auth immediately to avoid race condition with channel subscriptions + this.accessToken() + .then((token) => this.realtime.setAuth(token)) + .catch((e) => console.warn('Failed to set initial Realtime auth token:', e)) + } + + this.rest = new PostgrestClient(new URL('rest/v1', baseUrl).href, { + headers: this.headers, + schema: settings.db.schema, + fetch: this.fetch, + }) + + this.storage = new SupabaseStorageClient( + this.storageUrl.href, + this.headers, + this.fetch, + options?.storage + ) + + if (!settings.accessToken) { + this._listenForAuthEvents() + } + } + + /** + * Supabase Functions allows you to deploy and invoke edge functions. + */ + get functions(): FunctionsClient { + return new FunctionsClient(this.functionsUrl.href, { + headers: this.headers, + customFetch: this.fetch, + }) + } + + // NOTE: signatures must be kept in sync with PostgrestClient.from + from< + TableName extends string & keyof Schema['Tables'], + Table extends Schema['Tables'][TableName], + >(relation: TableName): PostgrestQueryBuilder + from( + relation: ViewName + ): PostgrestQueryBuilder + /** + * Perform a query on a table or a view. + * + * @param relation - The table or view name to query + */ + from(relation: string): PostgrestQueryBuilder { + return this.rest.from(relation) + } + + // NOTE: signatures must be kept in sync with PostgrestClient.schema + /** + * Select a schema to query or perform an function (rpc) call. + * + * The schema needs to be on the list of exposed schemas inside Supabase. + * + * @param schema - The schema to query + */ + schema>( + schema: DynamicSchema + ): PostgrestClient< + Database, + ClientOptions, + DynamicSchema, + Database[DynamicSchema] extends GenericSchema ? Database[DynamicSchema] : any + > { + return this.rest.schema(schema) + } + + // NOTE: signatures must be kept in sync with PostgrestClient.rpc + /** + * Perform a function call. + * + * @param fn - The function name to call + * @param args - The arguments to pass to the function call + * @param options - Named parameters + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * @param options.get - When set to `true`, the function will be called with + * read-only access mode. + * @param options.count - Count algorithm to use to count rows returned by the + * function. Only applicable for [set-returning + * functions](https://www.postgresql.org/docs/current/functions-srf.html). + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + rpc< + FnName extends string & keyof Schema['Functions'], + Args extends Schema['Functions'][FnName]['Args'] = never, + FilterBuilder extends GetRpcFunctionFilterBuilderByArgs< + Schema, + FnName, + Args + > = GetRpcFunctionFilterBuilderByArgs, + >( + fn: FnName, + args: Args = {} as Args, + options: { + head?: boolean + get?: boolean + count?: 'exact' | 'planned' | 'estimated' + } = { + head: false, + get: false, + count: undefined, + } + ): PostgrestFilterBuilder< + ClientOptions, + Schema, + FilterBuilder['Row'], + FilterBuilder['Result'], + FilterBuilder['RelationName'], + FilterBuilder['Relationships'], + 'RPC' + > { + return this.rest.rpc(fn, args, options) as unknown as PostgrestFilterBuilder< + ClientOptions, + Schema, + FilterBuilder['Row'], + FilterBuilder['Result'], + FilterBuilder['RelationName'], + FilterBuilder['Relationships'], + 'RPC' + > + } + + /** + * Creates a Realtime channel with Broadcast, Presence, and Postgres Changes. + * + * @param {string} name - The name of the Realtime channel. + * @param {Object} opts - The options to pass to the Realtime channel. + * + */ + channel(name: string, opts: RealtimeChannelOptions = { config: {} }): RealtimeChannel { + return this.realtime.channel(name, opts) + } + + /** + * Returns all Realtime channels. + */ + getChannels(): RealtimeChannel[] { + return this.realtime.getChannels() + } + + /** + * Unsubscribes and removes Realtime channel from Realtime client. + * + * @param {RealtimeChannel} channel - The name of the Realtime channel. + * + */ + removeChannel(channel: RealtimeChannel): Promise<'ok' | 'timed out' | 'error'> { + return this.realtime.removeChannel(channel) + } + + /** + * Unsubscribes and removes all Realtime channels from Realtime client. + */ + removeAllChannels(): Promise<('ok' | 'timed out' | 'error')[]> { + return this.realtime.removeAllChannels() + } + + private async _getAccessToken() { + if (this.accessToken) { + return await this.accessToken() + } + + const { data } = await this.auth.getSession() + + return data.session?.access_token ?? this.supabaseKey + } + + private _initSupabaseAuthClient( + { + autoRefreshToken, + persistSession, + detectSessionInUrl, + storage, + userStorage, + storageKey, + flowType, + lock, + debug, + throwOnError, + }: SupabaseAuthClientOptions, + headers?: Record, + fetch?: Fetch + ) { + const authHeaders = { + Authorization: `Bearer ${this.supabaseKey}`, + apikey: `${this.supabaseKey}`, + } + return new SupabaseAuthClient({ + url: this.authUrl.href, + headers: { ...authHeaders, ...headers }, + storageKey: storageKey, + autoRefreshToken, + persistSession, + detectSessionInUrl, + storage, + userStorage, + flowType, + lock, + debug, + throwOnError, + fetch, + // auth checks if there is a custom authorizaiton header using this flag + // so it knows whether to return an error when getUser is called with no session + hasCustomAuthorizationHeader: Object.keys(this.headers).some( + (key) => key.toLowerCase() === 'authorization' + ), + }) + } + + private _initRealtimeClient(options: RealtimeClientOptions) { + return new RealtimeClient(this.realtimeUrl.href, { + ...options, + params: { ...{ apikey: this.supabaseKey }, ...options?.params }, + }) + } + + private _listenForAuthEvents() { + const data = this.auth.onAuthStateChange((event, session) => { + this._handleTokenChanged(event, 'CLIENT', session?.access_token) + }) + return data + } + + private _handleTokenChanged( + event: AuthChangeEvent, + source: 'CLIENT' | 'STORAGE', + token?: string + ) { + if ( + (event === 'TOKEN_REFRESHED' || event === 'SIGNED_IN') && + this.changedAccessToken !== token + ) { + this.changedAccessToken = token + this.realtime.setAuth(token) + } else if (event === 'SIGNED_OUT') { + this.realtime.setAuth() + if (source == 'STORAGE') this.auth.signOut() + this.changedAccessToken = undefined + } + } +} diff --git a/backend/node_modules/@supabase/supabase-js/src/index.ts b/backend/node_modules/@supabase/supabase-js/src/index.ts new file mode 100644 index 0000000..8dd7777 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/src/index.ts @@ -0,0 +1,94 @@ +import SupabaseClient from './SupabaseClient' +import type { SupabaseClientOptions } from './lib/types' + +export * from '@supabase/auth-js' +export type { User as AuthUser, Session as AuthSession } from '@supabase/auth-js' +export { + type PostgrestResponse, + type PostgrestSingleResponse, + type PostgrestMaybeSingleResponse, + PostgrestError, +} from '@supabase/postgrest-js' +export { + FunctionsHttpError, + FunctionsFetchError, + FunctionsRelayError, + FunctionsError, + type FunctionInvokeOptions, + FunctionRegion, +} from '@supabase/functions-js' +export * from '@supabase/realtime-js' +export { default as SupabaseClient } from './SupabaseClient' +export type { SupabaseClientOptions, QueryResult, QueryData, QueryError } from './lib/types' + +/** + * Creates a new Supabase Client. + * + * @example + * ```ts + * import { createClient } from '@supabase/supabase-js' + * + * const supabase = createClient('https://xyzcompany.supabase.co', 'public-anon-key') + * const { data, error } = await supabase.from('profiles').select('*') + * ``` + */ +export const createClient = < + Database = any, + SchemaNameOrClientOptions extends + | (string & keyof Omit) + | { PostgrestVersion: string } = 'public' extends keyof Omit + ? 'public' + : string & keyof Omit, + SchemaName extends string & + keyof Omit = SchemaNameOrClientOptions extends string & + keyof Omit + ? SchemaNameOrClientOptions + : 'public' extends keyof Omit + ? 'public' + : string & keyof Omit, '__InternalSupabase'>, +>( + supabaseUrl: string, + supabaseKey: string, + options?: SupabaseClientOptions +): SupabaseClient => { + return new SupabaseClient( + supabaseUrl, + supabaseKey, + options + ) +} + +// Check for Node.js <= 18 deprecation +function shouldShowDeprecationWarning(): boolean { + // Skip in browser environments + if (typeof window !== 'undefined') { + return false + } + + // Skip if process is not available (e.g., Edge Runtime) + if (typeof process === 'undefined') { + return false + } + + // Use dynamic property access to avoid Next.js Edge Runtime static analysis warnings + const processVersion = (process as any)['version'] + if (processVersion === undefined || processVersion === null) { + return false + } + + const versionMatch = processVersion.match(/^v(\d+)\./) + if (!versionMatch) { + return false + } + + const majorVersion = parseInt(versionMatch[1], 10) + return majorVersion <= 18 +} + +if (shouldShowDeprecationWarning()) { + console.warn( + `⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. ` + + `Please upgrade to Node.js 20 or later. ` + + `For more information, visit: https://github.com/orgs/supabase/discussions/37217` + ) +} diff --git a/backend/node_modules/@supabase/supabase-js/src/lib/SupabaseAuthClient.ts b/backend/node_modules/@supabase/supabase-js/src/lib/SupabaseAuthClient.ts new file mode 100644 index 0000000..ebc3639 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/src/lib/SupabaseAuthClient.ts @@ -0,0 +1,8 @@ +import { AuthClient } from '@supabase/auth-js' +import { SupabaseAuthClientOptions } from './types' + +export class SupabaseAuthClient extends AuthClient { + constructor(options: SupabaseAuthClientOptions) { + super(options) + } +} diff --git a/backend/node_modules/@supabase/supabase-js/src/lib/constants.ts b/backend/node_modules/@supabase/supabase-js/src/lib/constants.ts new file mode 100644 index 0000000..101927d --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/src/lib/constants.ts @@ -0,0 +1,35 @@ +// constants.ts +import { RealtimeClientOptions } from '@supabase/realtime-js' +import { SupabaseAuthClientOptions } from './types' +import { version } from './version' + +let JS_ENV = '' +// @ts-ignore +if (typeof Deno !== 'undefined') { + JS_ENV = 'deno' +} else if (typeof document !== 'undefined') { + JS_ENV = 'web' +} else if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') { + JS_ENV = 'react-native' +} else { + JS_ENV = 'node' +} + +export const DEFAULT_HEADERS = { 'X-Client-Info': `supabase-js-${JS_ENV}/${version}` } + +export const DEFAULT_GLOBAL_OPTIONS = { + headers: DEFAULT_HEADERS, +} + +export const DEFAULT_DB_OPTIONS = { + schema: 'public', +} + +export const DEFAULT_AUTH_OPTIONS: SupabaseAuthClientOptions = { + autoRefreshToken: true, + persistSession: true, + detectSessionInUrl: true, + flowType: 'implicit', +} + +export const DEFAULT_REALTIME_OPTIONS: RealtimeClientOptions = {} diff --git a/backend/node_modules/@supabase/supabase-js/src/lib/fetch.ts b/backend/node_modules/@supabase/supabase-js/src/lib/fetch.ts new file mode 100644 index 0000000..06cb48d --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/src/lib/fetch.ts @@ -0,0 +1,36 @@ +type Fetch = typeof fetch + +export const resolveFetch = (customFetch?: Fetch): Fetch => { + if (customFetch) { + return (...args: Parameters) => customFetch(...args) + } + return (...args: Parameters) => fetch(...args) +} + +export const resolveHeadersConstructor = () => { + return Headers +} + +export const fetchWithAuth = ( + supabaseKey: string, + getAccessToken: () => Promise, + customFetch?: Fetch +): Fetch => { + const fetch = resolveFetch(customFetch) + const HeadersConstructor = resolveHeadersConstructor() + + return async (input, init) => { + const accessToken = (await getAccessToken()) ?? supabaseKey + let headers = new HeadersConstructor(init?.headers) + + if (!headers.has('apikey')) { + headers.set('apikey', supabaseKey) + } + + if (!headers.has('Authorization')) { + headers.set('Authorization', `Bearer ${accessToken}`) + } + + return fetch(input, { ...init, headers }) + } +} diff --git a/backend/node_modules/@supabase/supabase-js/src/lib/helpers.ts b/backend/node_modules/@supabase/supabase-js/src/lib/helpers.ts new file mode 100644 index 0000000..df63a87 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/src/lib/helpers.ts @@ -0,0 +1,98 @@ +// helpers.ts +import { SupabaseClientOptions } from './types' + +export function uuid() { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { + var r = (Math.random() * 16) | 0, + v = c == 'x' ? r : (r & 0x3) | 0x8 + return v.toString(16) + }) +} + +export function ensureTrailingSlash(url: string): string { + return url.endsWith('/') ? url : url + '/' +} + +export const isBrowser = () => typeof window !== 'undefined' + +export function applySettingDefaults< + Database = any, + SchemaName extends string & keyof Database = 'public' extends keyof Database + ? 'public' + : string & keyof Database, +>( + options: SupabaseClientOptions, + defaults: SupabaseClientOptions +): Required> { + const { + db: dbOptions, + auth: authOptions, + realtime: realtimeOptions, + global: globalOptions, + } = options + const { + db: DEFAULT_DB_OPTIONS, + auth: DEFAULT_AUTH_OPTIONS, + realtime: DEFAULT_REALTIME_OPTIONS, + global: DEFAULT_GLOBAL_OPTIONS, + } = defaults + + const result: Required> = { + db: { + ...DEFAULT_DB_OPTIONS, + ...dbOptions, + }, + auth: { + ...DEFAULT_AUTH_OPTIONS, + ...authOptions, + }, + realtime: { + ...DEFAULT_REALTIME_OPTIONS, + ...realtimeOptions, + }, + storage: {}, + global: { + ...DEFAULT_GLOBAL_OPTIONS, + ...globalOptions, + headers: { + ...(DEFAULT_GLOBAL_OPTIONS?.headers ?? {}), + ...(globalOptions?.headers ?? {}), + }, + }, + accessToken: async () => '', + } + + if (options.accessToken) { + result.accessToken = options.accessToken + } else { + // hack around Required<> + delete (result as any).accessToken + } + + return result +} + +/** + * Validates a Supabase client URL + * + * @param {string} supabaseUrl - The Supabase client URL string. + * @returns {URL} - The validated base URL. + * @throws {Error} + */ +export function validateSupabaseUrl(supabaseUrl: string): URL { + const trimmedUrl = supabaseUrl?.trim() + + if (!trimmedUrl) { + throw new Error('supabaseUrl is required.') + } + + if (!trimmedUrl.match(/^https?:\/\//i)) { + throw new Error('Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.') + } + + try { + return new URL(ensureTrailingSlash(trimmedUrl)) + } catch { + throw Error('Invalid supabaseUrl: Provided URL is malformed.') + } +} diff --git a/backend/node_modules/@supabase/supabase-js/src/lib/rest/types/common/common.ts b/backend/node_modules/@supabase/supabase-js/src/lib/rest/types/common/common.ts new file mode 100644 index 0000000..8e38dd2 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/src/lib/rest/types/common/common.ts @@ -0,0 +1,66 @@ +/** + * AUTO-GENERATED FILE - DO NOT EDIT + * + * This file is automatically synchronized from @supabase/postgrest-js + * Source: packages/core/postgrest-js/src/types/common/ + * + * To update this file, modify the source in postgrest-js and run: + * npm run codegen + */ + +// Types that are shared between supabase-js and postgrest-js + +export type Fetch = typeof fetch + +export type GenericRelationship = { + foreignKeyName: string + columns: string[] + isOneToOne?: boolean + referencedRelation: string + referencedColumns: string[] +} + +export type GenericTable = { + Row: Record + Insert: Record + Update: Record + Relationships: GenericRelationship[] +} + +export type GenericUpdatableView = { + Row: Record + Insert: Record + Update: Record + Relationships: GenericRelationship[] +} + +export type GenericNonUpdatableView = { + Row: Record + Relationships: GenericRelationship[] +} + +export type GenericView = GenericUpdatableView | GenericNonUpdatableView + +export type GenericSetofOption = { + isSetofReturn?: boolean | undefined + isOneToOne?: boolean | undefined + isNotNullable?: boolean | undefined + to: string + from: string +} + +export type GenericFunction = { + Args: Record | never + Returns: unknown + SetofOptions?: GenericSetofOption +} + +export type GenericSchema = { + Tables: Record + Views: Record + Functions: Record +} + +export type ClientServerOptions = { + PostgrestVersion?: string +} diff --git a/backend/node_modules/@supabase/supabase-js/src/lib/rest/types/common/rpc.ts b/backend/node_modules/@supabase/supabase-js/src/lib/rest/types/common/rpc.ts new file mode 100644 index 0000000..25285ef --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/src/lib/rest/types/common/rpc.ts @@ -0,0 +1,158 @@ +/** + * AUTO-GENERATED FILE - DO NOT EDIT + * + * This file is automatically synchronized from @supabase/postgrest-js + * Source: packages/core/postgrest-js/src/types/common/ + * + * To update this file, modify the source in postgrest-js and run: + * npm run codegen + */ + +import type { GenericFunction, GenericSchema, GenericSetofOption } from './common' + +// Functions matching utils +type IsMatchingArgs< + FnArgs extends GenericFunction['Args'], + PassedArgs extends GenericFunction['Args'], +> = [FnArgs] extends [Record] + ? PassedArgs extends Record + ? true + : false + : keyof PassedArgs extends keyof FnArgs + ? PassedArgs extends FnArgs + ? true + : false + : false + +type MatchingFunctionArgs< + Fn extends GenericFunction, + Args extends GenericFunction['Args'], +> = Fn extends { Args: infer A extends GenericFunction['Args'] } + ? IsMatchingArgs extends true + ? Fn + : never + : false + +type FindMatchingFunctionByArgs< + FnUnion, + Args extends GenericFunction['Args'], +> = FnUnion extends infer Fn extends GenericFunction ? MatchingFunctionArgs : false + +// Types for working with database schemas +type TablesAndViews = Schema['Tables'] & Exclude + +// Utility types for working with unions +type UnionToIntersection = (U extends any ? (k: U) => void : never) extends (k: infer I) => void + ? I + : never + +type LastOf = + UnionToIntersection T : never> extends () => infer R ? R : never + +type IsAny = 0 extends 1 & T ? true : false + +type ExactMatch = [T] extends [S] ? ([S] extends [T] ? true : false) : false + +type ExtractExactFunction = Fns extends infer F + ? F extends GenericFunction + ? ExactMatch extends true + ? F + : never + : never + : never + +type IsNever = [T] extends [never] ? true : false + +type RpcFunctionNotFound = { + Row: any + Result: { + error: true + } & "Couldn't infer function definition matching provided arguments" + RelationName: FnName + Relationships: null +} + +type CrossSchemaError = { + error: true +} & `Function returns SETOF from a different schema ('${TableRef}'). Use .overrideTypes() to specify the return type explicitly.` + +export type GetRpcFunctionFilterBuilderByArgs< + Schema extends GenericSchema, + FnName extends string & keyof Schema['Functions'], + Args, +> = { + 0: Schema['Functions'][FnName] + // If the Args is exactly never (function call without any params) + 1: IsAny extends true + ? any + : IsNever extends true + ? // This is for retro compatibility, if the funcition is defined with an single return and an union of Args + // we fallback to the last function definition matched by name + IsNever> extends true + ? LastOf + : ExtractExactFunction + : Args extends Record + ? LastOf + : // Otherwise, we attempt to match with one of the function definition in the union based + // on the function arguments provided + Args extends GenericFunction['Args'] + ? // This is for retro compatibility, if the funcition is defined with an single return and an union of Args + // we fallback to the last function definition matched by name + IsNever< + LastOf> + > extends true + ? LastOf + : // Otherwise, we use the arguments based function definition narrowing to get the right value + LastOf> + : // If we can't find a matching function by args, we try to find one by function name + ExtractExactFunction extends GenericFunction + ? ExtractExactFunction + : any +}[1] extends infer Fn + ? // If we are dealing with an non-typed client everything is any + IsAny extends true + ? { Row: any; Result: any; RelationName: FnName; Relationships: null } + : // Otherwise, we use the arguments based function definition narrowing to get the right value + Fn extends GenericFunction + ? { + Row: Fn['SetofOptions'] extends GenericSetofOption + ? Fn['SetofOptions']['to'] extends keyof TablesAndViews + ? TablesAndViews[Fn['SetofOptions']['to']]['Row'] + : // Cross-schema fallback: use Returns type when table is not in current schema + Fn['Returns'] extends any[] + ? Fn['Returns'][number] extends Record + ? Fn['Returns'][number] + : CrossSchemaError + : Fn['Returns'] extends Record + ? Fn['Returns'] + : CrossSchemaError + : Fn['Returns'] extends any[] + ? Fn['Returns'][number] extends Record + ? Fn['Returns'][number] + : never + : Fn['Returns'] extends Record + ? Fn['Returns'] + : never + Result: Fn['SetofOptions'] extends GenericSetofOption + ? Fn['SetofOptions']['isSetofReturn'] extends true + ? Fn['SetofOptions']['isOneToOne'] extends true + ? Fn['Returns'][] + : Fn['Returns'] + : Fn['Returns'] + : Fn['Returns'] + RelationName: Fn['SetofOptions'] extends GenericSetofOption + ? Fn['SetofOptions']['to'] + : FnName + Relationships: Fn['SetofOptions'] extends GenericSetofOption + ? Fn['SetofOptions']['to'] extends keyof Schema['Tables'] + ? Schema['Tables'][Fn['SetofOptions']['to']]['Relationships'] + : Fn['SetofOptions']['to'] extends keyof Schema['Views'] + ? Schema['Views'][Fn['SetofOptions']['to']]['Relationships'] + : null + : null + } + : // If we failed to find the function by argument, we still pass with any but also add an overridable + Fn extends false + ? RpcFunctionNotFound + : RpcFunctionNotFound + : RpcFunctionNotFound diff --git a/backend/node_modules/@supabase/supabase-js/src/lib/types.ts b/backend/node_modules/@supabase/supabase-js/src/lib/types.ts new file mode 100644 index 0000000..fde2a48 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/src/lib/types.ts @@ -0,0 +1,119 @@ +import { GoTrueClientOptions } from '@supabase/auth-js' +import { RealtimeClientOptions } from '@supabase/realtime-js' +import { PostgrestError } from '@supabase/postgrest-js' +import type { StorageClientOptions } from '@supabase/storage-js' +import type { + GenericSchema, + GenericRelationship, + GenericTable, + GenericUpdatableView, + GenericNonUpdatableView, + GenericView, + GenericFunction, +} from './rest/types/common/common' +export type { + GenericSchema, + GenericRelationship, + GenericTable, + GenericUpdatableView, + GenericNonUpdatableView, + GenericView, + GenericFunction, +} + +export interface SupabaseAuthClientOptions extends GoTrueClientOptions {} + +export type Fetch = typeof fetch + +export type SupabaseClientOptions = { + /** + * The Postgres schema which your tables belong to. Must be on the list of exposed schemas in Supabase. Defaults to `public`. + */ + db?: { + schema?: SchemaName + } + + auth?: { + /** + * Automatically refreshes the token for logged-in users. Defaults to true. + */ + autoRefreshToken?: boolean + /** + * Optional key name used for storing tokens in local storage. + */ + storageKey?: string + /** + * Whether to persist a logged-in session to storage. Defaults to true. + */ + persistSession?: boolean + /** + * Detect a session from the URL. Used for OAuth login callbacks. Defaults to true. + */ + detectSessionInUrl?: boolean + /** + * A storage provider. Used to store the logged-in session. + */ + storage?: SupabaseAuthClientOptions['storage'] + /** + * A storage provider to store the user profile separately from the session. + * Useful when you need to store the session information in cookies, + * without bloating the data with the redundant user object. + * + * @experimental + */ + userStorage?: SupabaseAuthClientOptions['userStorage'] + /** + * OAuth flow to use - defaults to implicit flow. PKCE is recommended for mobile and server-side applications. + */ + flowType?: SupabaseAuthClientOptions['flowType'] + /** + * If debug messages for authentication client are emitted. Can be used to inspect the behavior of the library. + */ + debug?: SupabaseAuthClientOptions['debug'] + /** + * Provide your own locking mechanism based on the environment. By default no locking is done at this time. + * + * @experimental + */ + lock?: SupabaseAuthClientOptions['lock'] + /** + * If there is an error with the query, throwOnError will reject the promise by + * throwing the error instead of returning it as part of a successful response. + */ + throwOnError?: SupabaseAuthClientOptions['throwOnError'] + } + /** + * Options passed to the realtime-js instance + */ + realtime?: RealtimeClientOptions + storage?: StorageClientOptions + global?: { + /** + * A custom `fetch` implementation. + */ + fetch?: Fetch + /** + * Optional headers for initializing the client. + */ + headers?: Record + } + /** + * Optional function for using a third-party authentication system with + * Supabase. The function should return an access token or ID token (JWT) by + * obtaining it from the third-party auth SDK. Note that this + * function may be called concurrently and many times. Use memoization and + * locking techniques if this is not supported by the SDKs. + * + * When set, the `auth` namespace of the Supabase client cannot be used. + * Create another client if you wish to use Supabase Auth and third-party + * authentications concurrently in the same application. + */ + accessToken?: () => Promise +} + +/** + * Helper types for query results. + */ +export type QueryResult = T extends PromiseLike ? U : never +export type QueryData = T extends PromiseLike<{ data: infer U }> ? Exclude : never +export type QueryError = PostgrestError diff --git a/backend/node_modules/@supabase/supabase-js/src/lib/version.ts b/backend/node_modules/@supabase/supabase-js/src/lib/version.ts new file mode 100644 index 0000000..57a6913 --- /dev/null +++ b/backend/node_modules/@supabase/supabase-js/src/lib/version.ts @@ -0,0 +1,7 @@ +// Generated automatically during releases by scripts/update-version-files.ts +// This file provides runtime access to the package version for: +// - HTTP request headers (e.g., X-Client-Info header for API requests) +// - Debugging and support (identifying which version is running) +// - Telemetry and logging (version reporting in errors/analytics) +// - Ensuring build artifacts match the published package version +export const version = '2.87.1' diff --git a/backend/node_modules/@types/node/LICENSE b/backend/node_modules/@types/node/LICENSE new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/backend/node_modules/@types/node/LICENSE @@ -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 diff --git a/backend/node_modules/@types/node/README.md b/backend/node_modules/@types/node/README.md new file mode 100644 index 0000000..109b668 --- /dev/null +++ b/backend/node_modules/@types/node/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/node` + +# Summary +This package contains type definitions for node (https://nodejs.org/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node. + +### Additional Details + * Last updated: Wed, 10 Dec 2025 19:02:30 GMT + * Dependencies: [undici-types](https://npmjs.com/package/undici-types) + +# Credits +These definitions were written by [Microsoft TypeScript](https://github.com/Microsoft), [Alberto Schiabel](https://github.com/jkomyno), [Andrew Makarov](https://github.com/r3nya), [Benjamin Toueg](https://github.com/btoueg), [David Junger](https://github.com/touffy), [Mohsen Azimi](https://github.com/mohsen1), [Nikita Galkin](https://github.com/galkin), [Sebastian Silbermann](https://github.com/eps1lon), [Wilco Bakker](https://github.com/WilcoBakker), [Marcin Kopacz](https://github.com/chyzwar), [Trivikram Kamat](https://github.com/trivikr), [Junxiao Shi](https://github.com/yoursunny), [Ilia Baryshnikov](https://github.com/qwelias), [ExE Boss](https://github.com/ExE-Boss), [Piotr Błażejewicz](https://github.com/peterblazejewicz), [Anna Henningsen](https://github.com/addaleax), [Victor Perin](https://github.com/victorperin), [NodeJS Contributors](https://github.com/NodeJS), [Linus Unnebäck](https://github.com/LinusU), [wafuwafu13](https://github.com/wafuwafu13), [Matteo Collina](https://github.com/mcollina), [Dmitry Semigradsky](https://github.com/Semigradsky), [René](https://github.com/Renegade334), and [Yagiz Nizipli](https://github.com/anonrig). diff --git a/backend/node_modules/@types/node/assert.d.ts b/backend/node_modules/@types/node/assert.d.ts new file mode 100644 index 0000000..ef4d852 --- /dev/null +++ b/backend/node_modules/@types/node/assert.d.ts @@ -0,0 +1,955 @@ +/** + * The `node:assert` module provides a set of assertion functions for verifying + * invariants. + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/assert.js) + */ +declare module "node:assert" { + import strict = require("node:assert/strict"); + /** + * An alias of {@link assert.ok}. + * @since v0.5.9 + * @param value The input that is checked for being truthy. + */ + function assert(value: unknown, message?: string | Error): asserts value; + const kOptions: unique symbol; + namespace assert { + type AssertMethodNames = + | "deepEqual" + | "deepStrictEqual" + | "doesNotMatch" + | "doesNotReject" + | "doesNotThrow" + | "equal" + | "fail" + | "ifError" + | "match" + | "notDeepEqual" + | "notDeepStrictEqual" + | "notEqual" + | "notStrictEqual" + | "ok" + | "partialDeepStrictEqual" + | "rejects" + | "strictEqual" + | "throws"; + interface AssertOptions { + /** + * If set to `'full'`, shows the full diff in assertion errors. + * @default 'simple' + */ + diff?: "simple" | "full" | undefined; + /** + * If set to `true`, non-strict methods behave like their + * corresponding strict methods. + * @default true + */ + strict?: boolean | undefined; + /** + * If set to `true`, skips prototype and constructor + * comparison in deep equality checks. + * @since v24.9.0 + * @default false + */ + skipPrototype?: boolean | undefined; + } + interface Assert extends Pick { + readonly [kOptions]: AssertOptions & { strict: false }; + } + interface AssertStrict extends Pick { + readonly [kOptions]: AssertOptions & { strict: true }; + } + /** + * The `Assert` class allows creating independent assertion instances with custom options. + * @since v24.6.0 + */ + var Assert: { + /** + * Creates a new assertion instance. The `diff` option controls the verbosity of diffs in assertion error messages. + * + * ```js + * const { Assert } = require('node:assert'); + * const assertInstance = new Assert({ diff: 'full' }); + * assertInstance.deepStrictEqual({ a: 1 }, { a: 2 }); + * // Shows a full diff in the error message. + * ``` + * + * **Important**: When destructuring assertion methods from an `Assert` instance, + * the methods lose their connection to the instance's configuration options (such + * as `diff`, `strict`, and `skipPrototype` settings). + * The destructured methods will fall back to default behavior instead. + * + * ```js + * const myAssert = new Assert({ diff: 'full' }); + * + * // This works as expected - uses 'full' diff + * myAssert.strictEqual({ a: 1 }, { b: { c: 1 } }); + * + * // This loses the 'full' diff setting - falls back to default 'simple' diff + * const { strictEqual } = myAssert; + * strictEqual({ a: 1 }, { b: { c: 1 } }); + * ``` + * + * The `skipPrototype` option affects all deep equality methods: + * + * ```js + * class Foo { + * constructor(a) { + * this.a = a; + * } + * } + * + * class Bar { + * constructor(a) { + * this.a = a; + * } + * } + * + * const foo = new Foo(1); + * const bar = new Bar(1); + * + * // Default behavior - fails due to different constructors + * const assert1 = new Assert(); + * assert1.deepStrictEqual(foo, bar); // AssertionError + * + * // Skip prototype comparison - passes if properties are equal + * const assert2 = new Assert({ skipPrototype: true }); + * assert2.deepStrictEqual(foo, bar); // OK + * ``` + * + * When destructured, methods lose access to the instance's `this` context and revert to default assertion behavior + * (diff: 'simple', non-strict mode). + * To maintain custom options when using destructured methods, avoid + * destructuring and call methods directly on the instance. + * @since v24.6.0 + */ + new( + options?: AssertOptions & { strict?: true | undefined }, + ): AssertStrict; + new( + options: AssertOptions, + ): Assert; + }; + interface AssertionErrorOptions { + /** + * If provided, the error message is set to this value. + */ + message?: string | undefined; + /** + * The `actual` property on the error instance. + */ + actual?: unknown; + /** + * The `expected` property on the error instance. + */ + expected?: unknown; + /** + * The `operator` property on the error instance. + */ + operator?: string | undefined; + /** + * If provided, the generated stack trace omits frames before this function. + */ + stackStartFn?: Function | undefined; + /** + * If set to `'full'`, shows the full diff in assertion errors. + * @default 'simple' + */ + diff?: "simple" | "full" | undefined; + } + /** + * Indicates the failure of an assertion. All errors thrown by the `node:assert` module will be instances of the `AssertionError` class. + */ + class AssertionError extends Error { + constructor(options: AssertionErrorOptions); + /** + * Set to the `actual` argument for methods such as {@link assert.strictEqual()}. + */ + actual: unknown; + /** + * Set to the `expected` argument for methods such as {@link assert.strictEqual()}. + */ + expected: unknown; + /** + * Indicates if the message was auto-generated (`true`) or not. + */ + generatedMessage: boolean; + /** + * Value is always `ERR_ASSERTION` to show that the error is an assertion error. + */ + code: "ERR_ASSERTION"; + /** + * Set to the passed in operator value. + */ + operator: string; + } + type AssertPredicate = RegExp | (new() => object) | ((thrown: unknown) => boolean) | object | Error; + /** + * Throws an `AssertionError` with the provided error message or a default + * error message. If the `message` parameter is an instance of an `Error` then + * it will be thrown instead of the `AssertionError`. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.fail(); + * // AssertionError [ERR_ASSERTION]: Failed + * + * assert.fail('boom'); + * // AssertionError [ERR_ASSERTION]: boom + * + * assert.fail(new TypeError('need array')); + * // TypeError: need array + * ``` + * @since v0.1.21 + * @param [message='Failed'] + */ + function fail(message?: string | Error): never; + /** + * Tests if `value` is truthy. It is equivalent to `assert.equal(!!value, true, message)`. + * + * If `value` is not truthy, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is `undefined`, a default + * error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown instead of the `AssertionError`. + * If no arguments are passed in at all `message` will be set to the string:`` 'No value argument passed to `assert.ok()`' ``. + * + * Be aware that in the `repl` the error message will be different to the one + * thrown in a file! See below for further details. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.ok(true); + * // OK + * assert.ok(1); + * // OK + * + * assert.ok(); + * // AssertionError: No value argument passed to `assert.ok()` + * + * assert.ok(false, 'it\'s false'); + * // AssertionError: it's false + * + * // In the repl: + * assert.ok(typeof 123 === 'string'); + * // AssertionError: false == true + * + * // In a file (e.g. test.js): + * assert.ok(typeof 123 === 'string'); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(typeof 123 === 'string') + * + * assert.ok(false); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(false) + * + * assert.ok(0); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(0) + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * // Using `assert()` works the same: + * assert(0); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert(0) + * ``` + * @since v0.1.21 + */ + function ok(value: unknown, message?: string | Error): asserts value; + /** + * **Strict assertion mode** + * + * An alias of {@link strictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link strictEqual} instead. + * + * Tests shallow, coercive equality between the `actual` and `expected` parameters + * using the [`==` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality). `NaN` is specially handled + * and treated as being identical if both sides are `NaN`. + * + * ```js + * import assert from 'node:assert'; + * + * assert.equal(1, 1); + * // OK, 1 == 1 + * assert.equal(1, '1'); + * // OK, 1 == '1' + * assert.equal(NaN, NaN); + * // OK + * + * assert.equal(1, 2); + * // AssertionError: 1 == 2 + * assert.equal({ a: { b: 1 } }, { a: { b: 1 } }); + * // AssertionError: { a: { b: 1 } } == { a: { b: 1 } } + * ``` + * + * If the values are not equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a default + * error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown instead of the `AssertionError`. + * @since v0.1.21 + */ + function equal(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link notStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link notStrictEqual} instead. + * + * Tests shallow, coercive inequality with the [`!=` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Inequality). `NaN` is + * specially handled and treated as being identical if both sides are `NaN`. + * + * ```js + * import assert from 'node:assert'; + * + * assert.notEqual(1, 2); + * // OK + * + * assert.notEqual(1, 1); + * // AssertionError: 1 != 1 + * + * assert.notEqual(1, '1'); + * // AssertionError: 1 != '1' + * ``` + * + * If the values are equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a default error + * message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown instead of the `AssertionError`. + * @since v0.1.21 + */ + function notEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link deepStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link deepStrictEqual} instead. + * + * Tests for deep equality between the `actual` and `expected` parameters. Consider + * using {@link deepStrictEqual} instead. {@link deepEqual} can have + * surprising results. + * + * _Deep equality_ means that the enumerable "own" properties of child objects + * are also recursively evaluated by the following rules. + * @since v0.1.21 + */ + function deepEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link notDeepStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link notDeepStrictEqual} instead. + * + * Tests for any deep inequality. Opposite of {@link deepEqual}. + * + * ```js + * import assert from 'node:assert'; + * + * const obj1 = { + * a: { + * b: 1, + * }, + * }; + * const obj2 = { + * a: { + * b: 2, + * }, + * }; + * const obj3 = { + * a: { + * b: 1, + * }, + * }; + * const obj4 = { __proto__: obj1 }; + * + * assert.notDeepEqual(obj1, obj1); + * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } + * + * assert.notDeepEqual(obj1, obj2); + * // OK + * + * assert.notDeepEqual(obj1, obj3); + * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } + * + * assert.notDeepEqual(obj1, obj4); + * // OK + * ``` + * + * If the values are deeply equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a default + * error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function notDeepEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Tests strict equality between the `actual` and `expected` parameters as + * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.strictEqual(1, 2); + * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: + * // + * // 1 !== 2 + * + * assert.strictEqual(1, 1); + * // OK + * + * assert.strictEqual('Hello foobar', 'Hello World!'); + * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: + * // + actual - expected + * // + * // + 'Hello foobar' + * // - 'Hello World!' + * // ^ + * + * const apples = 1; + * const oranges = 2; + * assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`); + * // AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2 + * + * assert.strictEqual(1, '1', new TypeError('Inputs are not identical')); + * // TypeError: Inputs are not identical + * ``` + * + * If the values are not strictly equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a + * default error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function strictEqual(actual: unknown, expected: T, message?: string | Error): asserts actual is T; + /** + * Tests strict inequality between the `actual` and `expected` parameters as + * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.notStrictEqual(1, 2); + * // OK + * + * assert.notStrictEqual(1, 1); + * // AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to: + * // + * // 1 + * + * assert.notStrictEqual(1, '1'); + * // OK + * ``` + * + * If the values are strictly equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a + * default error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function notStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Tests for deep equality between the `actual` and `expected` parameters. + * "Deep" equality means that the enumerable "own" properties of child objects + * are recursively evaluated also by the following rules. + * @since v1.2.0 + */ + function deepStrictEqual(actual: unknown, expected: T, message?: string | Error): asserts actual is T; + /** + * Tests for deep strict inequality. Opposite of {@link deepStrictEqual}. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.notDeepStrictEqual({ a: 1 }, { a: '1' }); + * // OK + * ``` + * + * If the values are deeply and strictly equal, an `AssertionError` is thrown + * with a `message` property set equal to the value of the `message` parameter. If + * the `message` parameter is undefined, a default error message is assigned. If + * the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v1.2.0 + */ + function notDeepStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Expects the function `fn` to throw an error. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, + * a validation object where each property will be tested for strict deep equality, + * or an instance of error where each property will be tested for strict deep + * equality including the non-enumerable `message` and `name` properties. When + * using an object, it is also possible to use a regular expression, when + * validating against a string property. See below for examples. + * + * If specified, `message` will be appended to the message provided by the `AssertionError` if the `fn` call fails to throw or in case the error validation + * fails. + * + * Custom validation object/error instance: + * + * ```js + * import assert from 'node:assert/strict'; + * + * const err = new TypeError('Wrong value'); + * err.code = 404; + * err.foo = 'bar'; + * err.info = { + * nested: true, + * baz: 'text', + * }; + * err.reg = /abc/i; + * + * assert.throws( + * () => { + * throw err; + * }, + * { + * name: 'TypeError', + * message: 'Wrong value', + * info: { + * nested: true, + * baz: 'text', + * }, + * // Only properties on the validation object will be tested for. + * // Using nested objects requires all properties to be present. Otherwise + * // the validation is going to fail. + * }, + * ); + * + * // Using regular expressions to validate error properties: + * assert.throws( + * () => { + * throw err; + * }, + * { + * // The `name` and `message` properties are strings and using regular + * // expressions on those will match against the string. If they fail, an + * // error is thrown. + * name: /^TypeError$/, + * message: /Wrong/, + * foo: 'bar', + * info: { + * nested: true, + * // It is not possible to use regular expressions for nested properties! + * baz: 'text', + * }, + * // The `reg` property contains a regular expression and only if the + * // validation object contains an identical regular expression, it is going + * // to pass. + * reg: /abc/i, + * }, + * ); + * + * // Fails due to the different `message` and `name` properties: + * assert.throws( + * () => { + * const otherErr = new Error('Not found'); + * // Copy all enumerable properties from `err` to `otherErr`. + * for (const [key, value] of Object.entries(err)) { + * otherErr[key] = value; + * } + * throw otherErr; + * }, + * // The error's `message` and `name` properties will also be checked when using + * // an error as validation object. + * err, + * ); + * ``` + * + * Validate instanceof using constructor: + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * Error, + * ); + * ``` + * + * Validate error message using [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions): + * + * Using a regular expression runs `.toString` on the error object, and will + * therefore also include the error name. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * /^Error: Wrong value$/, + * ); + * ``` + * + * Custom error validation: + * + * The function must return `true` to indicate all internal validations passed. + * It will otherwise fail with an `AssertionError`. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * (err) => { + * assert(err instanceof Error); + * assert(/value/.test(err)); + * // Avoid returning anything from validation functions besides `true`. + * // Otherwise, it's not clear what part of the validation failed. Instead, + * // throw an error about the specific validation that failed (as done in this + * // example) and add as much helpful debugging information to that error as + * // possible. + * return true; + * }, + * 'unexpected error', + * ); + * ``` + * + * `error` cannot be a string. If a string is provided as the second + * argument, then `error` is assumed to be omitted and the string will be used for `message` instead. This can lead to easy-to-miss mistakes. Using the same + * message as the thrown error message is going to result in an `ERR_AMBIGUOUS_ARGUMENT` error. Please read the example below carefully if using + * a string as the second argument gets considered: + * + * ```js + * import assert from 'node:assert/strict'; + * + * function throwingFirst() { + * throw new Error('First'); + * } + * + * function throwingSecond() { + * throw new Error('Second'); + * } + * + * function notThrowing() {} + * + * // The second argument is a string and the input function threw an Error. + * // The first case will not throw as it does not match for the error message + * // thrown by the input function! + * assert.throws(throwingFirst, 'Second'); + * // In the next example the message has no benefit over the message from the + * // error and since it is not clear if the user intended to actually match + * // against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error. + * assert.throws(throwingSecond, 'Second'); + * // TypeError [ERR_AMBIGUOUS_ARGUMENT] + * + * // The string is only used (as message) in case the function does not throw: + * assert.throws(notThrowing, 'Second'); + * // AssertionError [ERR_ASSERTION]: Missing expected exception: Second + * + * // If it was intended to match for the error message do this instead: + * // It does not throw because the error messages match. + * assert.throws(throwingSecond, /Second$/); + * + * // If the error message does not match, an AssertionError is thrown. + * assert.throws(throwingFirst, /Second$/); + * // AssertionError [ERR_ASSERTION] + * ``` + * + * Due to the confusing error-prone notation, avoid a string as the second + * argument. + * @since v0.1.21 + */ + function throws(block: () => unknown, message?: string | Error): void; + function throws(block: () => unknown, error: AssertPredicate, message?: string | Error): void; + /** + * Asserts that the function `fn` does not throw an error. + * + * Using `assert.doesNotThrow()` is actually not useful because there + * is no benefit in catching an error and then rethrowing it. Instead, consider + * adding a comment next to the specific code path that should not throw and keep + * error messages as expressive as possible. + * + * When `assert.doesNotThrow()` is called, it will immediately call the `fn` function. + * + * If an error is thrown and it is the same type as that specified by the `error` parameter, then an `AssertionError` is thrown. If the error is of a + * different type, or if the `error` parameter is undefined, the error is + * propagated back to the caller. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), or a validation + * function. See {@link throws} for more details. + * + * The following, for instance, will throw the `TypeError` because there is no + * matching error type in the assertion: + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError, + * ); + * ``` + * + * However, the following will result in an `AssertionError` with the message + * 'Got unwanted exception...': + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * TypeError, + * ); + * ``` + * + * If an `AssertionError` is thrown and a value is provided for the `message` parameter, the value of `message` will be appended to the `AssertionError` message: + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * /Wrong value/, + * 'Whoops', + * ); + * // Throws: AssertionError: Got unwanted exception: Whoops + * ``` + * @since v0.1.21 + */ + function doesNotThrow(block: () => unknown, message?: string | Error): void; + function doesNotThrow(block: () => unknown, error: AssertPredicate, message?: string | Error): void; + /** + * Throws `value` if `value` is not `undefined` or `null`. This is useful when + * testing the `error` argument in callbacks. The stack trace contains all frames + * from the error passed to `ifError()` including the potential new frames for `ifError()` itself. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.ifError(null); + * // OK + * assert.ifError(0); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0 + * assert.ifError('error'); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error' + * assert.ifError(new Error()); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error + * + * // Create some random error frames. + * let err; + * (function errorFrame() { + * err = new Error('test error'); + * })(); + * + * (function ifErrorFrame() { + * assert.ifError(err); + * })(); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error + * // at ifErrorFrame + * // at errorFrame + * ``` + * @since v0.1.97 + */ + function ifError(value: unknown): asserts value is null | undefined; + /** + * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately + * calls the function and awaits the returned promise to complete. It will then + * check that the promise is rejected. + * + * If `asyncFn` is a function and it throws an error synchronously, `assert.rejects()` will return a rejected `Promise` with that error. If the + * function does not return a promise, `assert.rejects()` will return a rejected `Promise` with an [ERR_INVALID_RETURN_VALUE](https://nodejs.org/docs/latest-v25.x/api/errors.html#err_invalid_return_value) + * error. In both cases the error handler is skipped. + * + * Besides the async nature to await the completion behaves identically to {@link throws}. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, + * an object where each property will be tested for, or an instance of error where + * each property will be tested for including the non-enumerable `message` and `name` properties. + * + * If specified, `message` will be the message provided by the `{@link AssertionError}` if the `asyncFn` fails to reject. + * + * ```js + * import assert from 'node:assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * { + * name: 'TypeError', + * message: 'Wrong value', + * }, + * ); + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * (err) => { + * assert.strictEqual(err.name, 'TypeError'); + * assert.strictEqual(err.message, 'Wrong value'); + * return true; + * }, + * ); + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.rejects( + * Promise.reject(new Error('Wrong value')), + * Error, + * ).then(() => { + * // ... + * }); + * ``` + * + * `error` cannot be a string. If a string is provided as the second argument, then `error` is assumed to + * be omitted and the string will be used for `message` instead. This can lead to easy-to-miss mistakes. Please read the + * example in {@link throws} carefully if using a string as the second argument gets considered. + * @since v10.0.0 + */ + function rejects(block: (() => Promise) | Promise, message?: string | Error): Promise; + function rejects( + block: (() => Promise) | Promise, + error: AssertPredicate, + message?: string | Error, + ): Promise; + /** + * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately + * calls the function and awaits the returned promise to complete. It will then + * check that the promise is not rejected. + * + * If `asyncFn` is a function and it throws an error synchronously, `assert.doesNotReject()` will return a rejected `Promise` with that error. If + * the function does not return a promise, `assert.doesNotReject()` will return a + * rejected `Promise` with an [ERR_INVALID_RETURN_VALUE](https://nodejs.org/docs/latest-v25.x/api/errors.html#err_invalid_return_value) error. In both cases + * the error handler is skipped. + * + * Using `assert.doesNotReject()` is actually not useful because there is little + * benefit in catching a rejection and then rejecting it again. Instead, consider + * adding a comment next to the specific code path that should not reject and keep + * error messages as expressive as possible. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), or a validation + * function. See {@link throws} for more details. + * + * Besides the async nature to await the completion behaves identically to {@link doesNotThrow}. + * + * ```js + * import assert from 'node:assert/strict'; + * + * await assert.doesNotReject( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError, + * ); + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotReject(Promise.reject(new TypeError('Wrong value'))) + * .then(() => { + * // ... + * }); + * ``` + * @since v10.0.0 + */ + function doesNotReject( + block: (() => Promise) | Promise, + message?: string | Error, + ): Promise; + function doesNotReject( + block: (() => Promise) | Promise, + error: AssertPredicate, + message?: string | Error, + ): Promise; + /** + * Expects the `string` input to match the regular expression. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.match('I will fail', /pass/); + * // AssertionError [ERR_ASSERTION]: The input did not match the regular ... + * + * assert.match(123, /pass/); + * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. + * + * assert.match('I will pass', /pass/); + * // OK + * ``` + * + * If the values do not match, or if the `string` argument is of another type than `string`, an `{@link AssertionError}` is thrown with a `message` property set equal + * to the value of the `message` parameter. If the `message` parameter is + * undefined, a default error message is assigned. If the `message` parameter is an + * instance of an [Error](https://nodejs.org/docs/latest-v25.x/api/errors.html#class-error) then it will be thrown instead of the `{@link AssertionError}`. + * @since v13.6.0, v12.16.0 + */ + function match(value: string, regExp: RegExp, message?: string | Error): void; + /** + * Expects the `string` input not to match the regular expression. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotMatch('I will fail', /fail/); + * // AssertionError [ERR_ASSERTION]: The input was expected to not match the ... + * + * assert.doesNotMatch(123, /pass/); + * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. + * + * assert.doesNotMatch('I will pass', /different/); + * // OK + * ``` + * + * If the values do match, or if the `string` argument is of another type than `string`, an `{@link AssertionError}` is thrown with a `message` property set equal + * to the value of the `message` parameter. If the `message` parameter is + * undefined, a default error message is assigned. If the `message` parameter is an + * instance of an [Error](https://nodejs.org/docs/latest-v25.x/api/errors.html#class-error) then it will be thrown instead of the `{@link AssertionError}`. + * @since v13.6.0, v12.16.0 + */ + function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void; + /** + * Tests for partial deep equality between the `actual` and `expected` parameters. + * "Deep" equality means that the enumerable "own" properties of child objects + * are recursively evaluated also by the following rules. "Partial" equality means + * that only properties that exist on the `expected` parameter are going to be + * compared. + * + * This method always passes the same test cases as `assert.deepStrictEqual()`, + * behaving as a super set of it. + * @since v22.13.0 + */ + function partialDeepStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + } + namespace assert { + export { strict }; + } + export = assert; +} +declare module "assert" { + import assert = require("node:assert"); + export = assert; +} diff --git a/backend/node_modules/@types/node/assert/strict.d.ts b/backend/node_modules/@types/node/assert/strict.d.ts new file mode 100644 index 0000000..51bb352 --- /dev/null +++ b/backend/node_modules/@types/node/assert/strict.d.ts @@ -0,0 +1,105 @@ +/** + * In strict assertion mode, non-strict methods behave like their corresponding + * strict methods. For example, `assert.deepEqual()` will behave like + * `assert.deepStrictEqual()`. + * + * In strict assertion mode, error messages for objects display a diff. In legacy + * assertion mode, error messages for objects display the objects, often truncated. + * + * To use strict assertion mode: + * + * ```js + * import { strict as assert } from 'node:assert'; + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * ``` + * + * Example error diff: + * + * ```js + * import { strict as assert } from 'node:assert'; + * + * assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]); + * // AssertionError: Expected inputs to be strictly deep-equal: + * // + actual - expected ... Lines skipped + * // + * // [ + * // [ + * // ... + * // 2, + * // + 3 + * // - '3' + * // ], + * // ... + * // 5 + * // ] + * ``` + * + * To deactivate the colors, use the `NO_COLOR` or `NODE_DISABLE_COLORS` + * environment variables. This will also deactivate the colors in the REPL. For + * more on color support in terminal environments, read the tty + * [`getColorDepth()`](https://nodejs.org/docs/latest-v25.x/api/tty.html#writestreamgetcolordepthenv) documentation. + * @since v15.0.0 + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/assert/strict.js) + */ +declare module "node:assert/strict" { + import { + Assert, + AssertionError, + AssertionErrorOptions, + AssertOptions, + AssertPredicate, + AssertStrict, + deepStrictEqual, + doesNotMatch, + doesNotReject, + doesNotThrow, + fail, + ifError, + match, + notDeepStrictEqual, + notStrictEqual, + ok, + partialDeepStrictEqual, + rejects, + strictEqual, + throws, + } from "node:assert"; + function strict(value: unknown, message?: string | Error): asserts value; + namespace strict { + export { + Assert, + AssertionError, + AssertionErrorOptions, + AssertOptions, + AssertPredicate, + AssertStrict, + deepStrictEqual, + deepStrictEqual as deepEqual, + doesNotMatch, + doesNotReject, + doesNotThrow, + fail, + ifError, + match, + notDeepStrictEqual, + notDeepStrictEqual as notDeepEqual, + notStrictEqual, + notStrictEqual as notEqual, + ok, + partialDeepStrictEqual, + rejects, + strict, + strictEqual, + strictEqual as equal, + throws, + }; + } + export = strict; +} +declare module "assert/strict" { + import strict = require("node:assert/strict"); + export = strict; +} diff --git a/backend/node_modules/@types/node/async_hooks.d.ts b/backend/node_modules/@types/node/async_hooks.d.ts new file mode 100644 index 0000000..aa692c1 --- /dev/null +++ b/backend/node_modules/@types/node/async_hooks.d.ts @@ -0,0 +1,623 @@ +/** + * We strongly discourage the use of the `async_hooks` API. + * Other APIs that can cover most of its use cases include: + * + * * [`AsyncLocalStorage`](https://nodejs.org/docs/latest-v25.x/api/async_context.html#class-asynclocalstorage) tracks async context + * * [`process.getActiveResourcesInfo()`](https://nodejs.org/docs/latest-v25.x/api/process.html#processgetactiveresourcesinfo) tracks active resources + * + * The `node:async_hooks` module provides an API to track asynchronous resources. + * It can be accessed using: + * + * ```js + * import async_hooks from 'node:async_hooks'; + * ``` + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/async_hooks.js) + */ +declare module "node:async_hooks" { + /** + * ```js + * import { executionAsyncId } from 'node:async_hooks'; + * import fs from 'node:fs'; + * + * console.log(executionAsyncId()); // 1 - bootstrap + * const path = '.'; + * fs.open(path, 'r', (err, fd) => { + * console.log(executionAsyncId()); // 6 - open() + * }); + * ``` + * + * The ID returned from `executionAsyncId()` is related to execution timing, not + * causality (which is covered by `triggerAsyncId()`): + * + * ```js + * const server = net.createServer((conn) => { + * // Returns the ID of the server, not of the new connection, because the + * // callback runs in the execution scope of the server's MakeCallback(). + * async_hooks.executionAsyncId(); + * + * }).listen(port, () => { + * // Returns the ID of a TickObject (process.nextTick()) because all + * // callbacks passed to .listen() are wrapped in a nextTick(). + * async_hooks.executionAsyncId(); + * }); + * ``` + * + * Promise contexts may not get precise `executionAsyncIds` by default. + * See the section on [promise execution tracking](https://nodejs.org/docs/latest-v25.x/api/async_hooks.html#promise-execution-tracking). + * @since v8.1.0 + * @return The `asyncId` of the current execution context. Useful to track when something calls. + */ + function executionAsyncId(): number; + /** + * Resource objects returned by `executionAsyncResource()` are most often internal + * Node.js handle objects with undocumented APIs. Using any functions or properties + * on the object is likely to crash your application and should be avoided. + * + * Using `executionAsyncResource()` in the top-level execution context will + * return an empty object as there is no handle or request object to use, + * but having an object representing the top-level can be helpful. + * + * ```js + * import { open } from 'node:fs'; + * import { executionAsyncId, executionAsyncResource } from 'node:async_hooks'; + * + * console.log(executionAsyncId(), executionAsyncResource()); // 1 {} + * open(new URL(import.meta.url), 'r', (err, fd) => { + * console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap + * }); + * ``` + * + * This can be used to implement continuation local storage without the + * use of a tracking `Map` to store the metadata: + * + * ```js + * import { createServer } from 'node:http'; + * import { + * executionAsyncId, + * executionAsyncResource, + * createHook, + * } from 'node:async_hooks'; + * const sym = Symbol('state'); // Private symbol to avoid pollution + * + * createHook({ + * init(asyncId, type, triggerAsyncId, resource) { + * const cr = executionAsyncResource(); + * if (cr) { + * resource[sym] = cr[sym]; + * } + * }, + * }).enable(); + * + * const server = createServer((req, res) => { + * executionAsyncResource()[sym] = { state: req.url }; + * setTimeout(function() { + * res.end(JSON.stringify(executionAsyncResource()[sym])); + * }, 100); + * }).listen(3000); + * ``` + * @since v13.9.0, v12.17.0 + * @return The resource representing the current execution. Useful to store data within the resource. + */ + function executionAsyncResource(): object; + /** + * ```js + * const server = net.createServer((conn) => { + * // The resource that caused (or triggered) this callback to be called + * // was that of the new connection. Thus the return value of triggerAsyncId() + * // is the asyncId of "conn". + * async_hooks.triggerAsyncId(); + * + * }).listen(port, () => { + * // Even though all callbacks passed to .listen() are wrapped in a nextTick() + * // the callback itself exists because the call to the server's .listen() + * // was made. So the return value would be the ID of the server. + * async_hooks.triggerAsyncId(); + * }); + * ``` + * + * Promise contexts may not get valid `triggerAsyncId`s by default. See + * the section on [promise execution tracking](https://nodejs.org/docs/latest-v25.x/api/async_hooks.html#promise-execution-tracking). + * @return The ID of the resource responsible for calling the callback that is currently being executed. + */ + function triggerAsyncId(): number; + interface HookCallbacks { + /** + * Called when a class is constructed that has the possibility to emit an asynchronous event. + * @param asyncId A unique ID for the async resource + * @param type The type of the async resource + * @param triggerAsyncId The unique ID of the async resource in whose execution context this async resource was created + * @param resource Reference to the resource representing the async operation, needs to be released during destroy + */ + init?(asyncId: number, type: string, triggerAsyncId: number, resource: object): void; + /** + * When an asynchronous operation is initiated or completes a callback is called to notify the user. + * The before callback is called just before said callback is executed. + * @param asyncId the unique identifier assigned to the resource about to execute the callback. + */ + before?(asyncId: number): void; + /** + * Called immediately after the callback specified in `before` is completed. + * + * If an uncaught exception occurs during execution of the callback, then `after` will run after the `'uncaughtException'` event is emitted or a `domain`'s handler runs. + * @param asyncId the unique identifier assigned to the resource which has executed the callback. + */ + after?(asyncId: number): void; + /** + * Called when a promise has resolve() called. This may not be in the same execution id + * as the promise itself. + * @param asyncId the unique id for the promise that was resolve()d. + */ + promiseResolve?(asyncId: number): void; + /** + * Called after the resource corresponding to asyncId is destroyed + * @param asyncId a unique ID for the async resource + */ + destroy?(asyncId: number): void; + } + interface AsyncHook { + /** + * Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop. + */ + enable(): this; + /** + * Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled. + */ + disable(): this; + } + /** + * Registers functions to be called for different lifetime events of each async + * operation. + * + * The callbacks `init()`/`before()`/`after()`/`destroy()` are called for the + * respective asynchronous event during a resource's lifetime. + * + * All callbacks are optional. For example, if only resource cleanup needs to + * be tracked, then only the `destroy` callback needs to be passed. The + * specifics of all functions that can be passed to `callbacks` is in the `Hook Callbacks` section. + * + * ```js + * import { createHook } from 'node:async_hooks'; + * + * const asyncHook = createHook({ + * init(asyncId, type, triggerAsyncId, resource) { }, + * destroy(asyncId) { }, + * }); + * ``` + * + * The callbacks will be inherited via the prototype chain: + * + * ```js + * class MyAsyncCallbacks { + * init(asyncId, type, triggerAsyncId, resource) { } + * destroy(asyncId) {} + * } + * + * class MyAddedCallbacks extends MyAsyncCallbacks { + * before(asyncId) { } + * after(asyncId) { } + * } + * + * const asyncHook = async_hooks.createHook(new MyAddedCallbacks()); + * ``` + * + * Because promises are asynchronous resources whose lifecycle is tracked + * via the async hooks mechanism, the `init()`, `before()`, `after()`, and`destroy()` callbacks _must not_ be async functions that return promises. + * @since v8.1.0 + * @param callbacks The `Hook Callbacks` to register + * @return Instance used for disabling and enabling hooks + */ + function createHook(callbacks: HookCallbacks): AsyncHook; + interface AsyncResourceOptions { + /** + * The ID of the execution context that created this async event. + * @default executionAsyncId() + */ + triggerAsyncId?: number | undefined; + /** + * Disables automatic `emitDestroy` when the object is garbage collected. + * This usually does not need to be set (even if `emitDestroy` is called + * manually), unless the resource's `asyncId` is retrieved and the + * sensitive API's `emitDestroy` is called with it. + * @default false + */ + requireManualDestroy?: boolean | undefined; + } + /** + * The class `AsyncResource` is designed to be extended by the embedder's async + * resources. Using this, users can easily trigger the lifetime events of their + * own resources. + * + * The `init` hook will trigger when an `AsyncResource` is instantiated. + * + * The following is an overview of the `AsyncResource` API. + * + * ```js + * import { AsyncResource, executionAsyncId } from 'node:async_hooks'; + * + * // AsyncResource() is meant to be extended. Instantiating a + * // new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * // async_hook.executionAsyncId() is used. + * const asyncResource = new AsyncResource( + * type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false }, + * ); + * + * // Run a function in the execution context of the resource. This will + * // * establish the context of the resource + * // * trigger the AsyncHooks before callbacks + * // * call the provided function `fn` with the supplied arguments + * // * trigger the AsyncHooks after callbacks + * // * restore the original execution context + * asyncResource.runInAsyncScope(fn, thisArg, ...args); + * + * // Call AsyncHooks destroy callbacks. + * asyncResource.emitDestroy(); + * + * // Return the unique ID assigned to the AsyncResource instance. + * asyncResource.asyncId(); + * + * // Return the trigger ID for the AsyncResource instance. + * asyncResource.triggerAsyncId(); + * ``` + */ + class AsyncResource { + /** + * AsyncResource() is meant to be extended. Instantiating a + * new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * async_hook.executionAsyncId() is used. + * @param type The type of async event. + * @param triggerAsyncId The ID of the execution context that created + * this async event (default: `executionAsyncId()`), or an + * AsyncResourceOptions object (since v9.3.0) + */ + constructor(type: string, triggerAsyncId?: number | AsyncResourceOptions); + /** + * Binds the given function to the current execution context. + * @since v14.8.0, v12.19.0 + * @param fn The function to bind to the current execution context. + * @param type An optional name to associate with the underlying `AsyncResource`. + */ + static bind any, ThisArg>( + fn: Func, + type?: string, + thisArg?: ThisArg, + ): Func; + /** + * Binds the given function to execute to this `AsyncResource`'s scope. + * @since v14.8.0, v12.19.0 + * @param fn The function to bind to the current `AsyncResource`. + */ + bind any>(fn: Func): Func; + /** + * Call the provided function with the provided arguments in the execution context + * of the async resource. This will establish the context, trigger the AsyncHooks + * before callbacks, call the function, trigger the AsyncHooks after callbacks, and + * then restore the original execution context. + * @since v9.6.0 + * @param fn The function to call in the execution context of this async resource. + * @param thisArg The receiver to be used for the function call. + * @param args Optional arguments to pass to the function. + */ + runInAsyncScope( + fn: (this: This, ...args: any[]) => Result, + thisArg?: This, + ...args: any[] + ): Result; + /** + * Call all `destroy` hooks. This should only ever be called once. An error will + * be thrown if it is called more than once. This **must** be manually called. If + * the resource is left to be collected by the GC then the `destroy` hooks will + * never be called. + * @return A reference to `asyncResource`. + */ + emitDestroy(): this; + /** + * @return The unique `asyncId` assigned to the resource. + */ + asyncId(): number; + /** + * @return The same `triggerAsyncId` that is passed to the `AsyncResource` constructor. + */ + triggerAsyncId(): number; + } + interface AsyncLocalStorageOptions { + /** + * The default value to be used when no store is provided. + */ + defaultValue?: any; + /** + * A name for the `AsyncLocalStorage` value. + */ + name?: string | undefined; + } + /** + * This class creates stores that stay coherent through asynchronous operations. + * + * While you can create your own implementation on top of the `node:async_hooks` module, `AsyncLocalStorage` should be preferred as it is a performant and memory + * safe implementation that involves significant optimizations that are non-obvious + * to implement. + * + * The following example uses `AsyncLocalStorage` to build a simple logger + * that assigns IDs to incoming HTTP requests and includes them in messages + * logged within each request. + * + * ```js + * import http from 'node:http'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const asyncLocalStorage = new AsyncLocalStorage(); + * + * function logWithId(msg) { + * const id = asyncLocalStorage.getStore(); + * console.log(`${id !== undefined ? id : '-'}:`, msg); + * } + * + * let idSeq = 0; + * http.createServer((req, res) => { + * asyncLocalStorage.run(idSeq++, () => { + * logWithId('start'); + * // Imagine any chain of async operations here + * setImmediate(() => { + * logWithId('finish'); + * res.end(); + * }); + * }); + * }).listen(8080); + * + * http.get('http://localhost:8080'); + * http.get('http://localhost:8080'); + * // Prints: + * // 0: start + * // 0: finish + * // 1: start + * // 1: finish + * ``` + * + * Each instance of `AsyncLocalStorage` maintains an independent storage context. + * Multiple instances can safely exist simultaneously without risk of interfering + * with each other's data. + * @since v13.10.0, v12.17.0 + */ + class AsyncLocalStorage { + /** + * Creates a new instance of `AsyncLocalStorage`. Store is only provided within a + * `run()` call or after an `enterWith()` call. + */ + constructor(options?: AsyncLocalStorageOptions); + /** + * Binds the given function to the current execution context. + * @since v19.8.0 + * @param fn The function to bind to the current execution context. + * @return A new function that calls `fn` within the captured execution context. + */ + static bind any>(fn: Func): Func; + /** + * Captures the current execution context and returns a function that accepts a + * function as an argument. Whenever the returned function is called, it + * calls the function passed to it within the captured context. + * + * ```js + * const asyncLocalStorage = new AsyncLocalStorage(); + * const runInAsyncScope = asyncLocalStorage.run(123, () => AsyncLocalStorage.snapshot()); + * const result = asyncLocalStorage.run(321, () => runInAsyncScope(() => asyncLocalStorage.getStore())); + * console.log(result); // returns 123 + * ``` + * + * AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple + * async context tracking purposes, for example: + * + * ```js + * class Foo { + * #runInAsyncScope = AsyncLocalStorage.snapshot(); + * + * get() { return this.#runInAsyncScope(() => asyncLocalStorage.getStore()); } + * } + * + * const foo = asyncLocalStorage.run(123, () => new Foo()); + * console.log(asyncLocalStorage.run(321, () => foo.get())); // returns 123 + * ``` + * @since v19.8.0 + * @return A new function with the signature `(fn: (...args) : R, ...args) : R`. + */ + static snapshot(): (fn: (...args: TArgs) => R, ...args: TArgs) => R; + /** + * Disables the instance of `AsyncLocalStorage`. All subsequent calls + * to `asyncLocalStorage.getStore()` will return `undefined` until `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()` is called again. + * + * When calling `asyncLocalStorage.disable()`, all current contexts linked to the + * instance will be exited. + * + * Calling `asyncLocalStorage.disable()` is required before the `asyncLocalStorage` can be garbage collected. This does not apply to stores + * provided by the `asyncLocalStorage`, as those objects are garbage collected + * along with the corresponding async resources. + * + * Use this method when the `asyncLocalStorage` is not in use anymore + * in the current process. + * @since v13.10.0, v12.17.0 + * @experimental + */ + disable(): void; + /** + * Returns the current store. + * If called outside of an asynchronous context initialized by + * calling `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()`, it + * returns `undefined`. + * @since v13.10.0, v12.17.0 + */ + getStore(): T | undefined; + /** + * The name of the `AsyncLocalStorage` instance if provided. + * @since v24.0.0 + */ + readonly name: string; + /** + * Runs a function synchronously within a context and returns its + * return value. The store is not accessible outside of the callback function. + * The store is accessible to any asynchronous operations created within the + * callback. + * + * The optional `args` are passed to the callback function. + * + * If the callback function throws an error, the error is thrown by `run()` too. + * The stacktrace is not impacted by this call and the context is exited. + * + * Example: + * + * ```js + * const store = { id: 2 }; + * try { + * asyncLocalStorage.run(store, () => { + * asyncLocalStorage.getStore(); // Returns the store object + * setTimeout(() => { + * asyncLocalStorage.getStore(); // Returns the store object + * }, 200); + * throw new Error(); + * }); + * } catch (e) { + * asyncLocalStorage.getStore(); // Returns undefined + * // The error will be caught here + * } + * ``` + * @since v13.10.0, v12.17.0 + */ + run(store: T, callback: () => R): R; + run(store: T, callback: (...args: TArgs) => R, ...args: TArgs): R; + /** + * Runs a function synchronously outside of a context and returns its + * return value. The store is not accessible within the callback function or + * the asynchronous operations created within the callback. Any `getStore()` call done within the callback function will always return `undefined`. + * + * The optional `args` are passed to the callback function. + * + * If the callback function throws an error, the error is thrown by `exit()` too. + * The stacktrace is not impacted by this call and the context is re-entered. + * + * Example: + * + * ```js + * // Within a call to run + * try { + * asyncLocalStorage.getStore(); // Returns the store object or value + * asyncLocalStorage.exit(() => { + * asyncLocalStorage.getStore(); // Returns undefined + * throw new Error(); + * }); + * } catch (e) { + * asyncLocalStorage.getStore(); // Returns the same object or value + * // The error will be caught here + * } + * ``` + * @since v13.10.0, v12.17.0 + * @experimental + */ + exit(callback: (...args: TArgs) => R, ...args: TArgs): R; + /** + * Transitions into the context for the remainder of the current + * synchronous execution and then persists the store through any following + * asynchronous calls. + * + * Example: + * + * ```js + * const store = { id: 1 }; + * // Replaces previous store with the given store object + * asyncLocalStorage.enterWith(store); + * asyncLocalStorage.getStore(); // Returns the store object + * someAsyncOperation(() => { + * asyncLocalStorage.getStore(); // Returns the same object + * }); + * ``` + * + * This transition will continue for the _entire_ synchronous execution. + * This means that if, for example, the context is entered within an event + * handler subsequent event handlers will also run within that context unless + * specifically bound to another context with an `AsyncResource`. That is why `run()` should be preferred over `enterWith()` unless there are strong reasons + * to use the latter method. + * + * ```js + * const store = { id: 1 }; + * + * emitter.on('my-event', () => { + * asyncLocalStorage.enterWith(store); + * }); + * emitter.on('my-event', () => { + * asyncLocalStorage.getStore(); // Returns the same object + * }); + * + * asyncLocalStorage.getStore(); // Returns undefined + * emitter.emit('my-event'); + * asyncLocalStorage.getStore(); // Returns the same object + * ``` + * @since v13.11.0, v12.17.0 + * @experimental + */ + enterWith(store: T): void; + } + /** + * @since v17.2.0, v16.14.0 + * @return A map of provider types to the corresponding numeric id. + * This map contains all the event types that might be emitted by the `async_hooks.init()` event. + */ + namespace asyncWrapProviders { + const NONE: number; + const DIRHANDLE: number; + const DNSCHANNEL: number; + const ELDHISTOGRAM: number; + const FILEHANDLE: number; + const FILEHANDLECLOSEREQ: number; + const FIXEDSIZEBLOBCOPY: number; + const FSEVENTWRAP: number; + const FSREQCALLBACK: number; + const FSREQPROMISE: number; + const GETADDRINFOREQWRAP: number; + const GETNAMEINFOREQWRAP: number; + const HEAPSNAPSHOT: number; + const HTTP2SESSION: number; + const HTTP2STREAM: number; + const HTTP2PING: number; + const HTTP2SETTINGS: number; + const HTTPINCOMINGMESSAGE: number; + const HTTPCLIENTREQUEST: number; + const JSSTREAM: number; + const JSUDPWRAP: number; + const MESSAGEPORT: number; + const PIPECONNECTWRAP: number; + const PIPESERVERWRAP: number; + const PIPEWRAP: number; + const PROCESSWRAP: number; + const PROMISE: number; + const QUERYWRAP: number; + const SHUTDOWNWRAP: number; + const SIGNALWRAP: number; + const STATWATCHER: number; + const STREAMPIPE: number; + const TCPCONNECTWRAP: number; + const TCPSERVERWRAP: number; + const TCPWRAP: number; + const TTYWRAP: number; + const UDPSENDWRAP: number; + const UDPWRAP: number; + const SIGINTWATCHDOG: number; + const WORKER: number; + const WORKERHEAPSNAPSHOT: number; + const WRITEWRAP: number; + const ZLIB: number; + const CHECKPRIMEREQUEST: number; + const PBKDF2REQUEST: number; + const KEYPAIRGENREQUEST: number; + const KEYGENREQUEST: number; + const KEYEXPORTREQUEST: number; + const CIPHERREQUEST: number; + const DERIVEBITSREQUEST: number; + const HASHREQUEST: number; + const RANDOMBYTESREQUEST: number; + const RANDOMPRIMEREQUEST: number; + const SCRYPTREQUEST: number; + const SIGNREQUEST: number; + const TLSWRAP: number; + const VERIFYREQUEST: number; + } +} +declare module "async_hooks" { + export * from "node:async_hooks"; +} diff --git a/backend/node_modules/@types/node/buffer.buffer.d.ts b/backend/node_modules/@types/node/buffer.buffer.d.ts new file mode 100644 index 0000000..a3c2304 --- /dev/null +++ b/backend/node_modules/@types/node/buffer.buffer.d.ts @@ -0,0 +1,466 @@ +declare module "node:buffer" { + type ImplicitArrayBuffer> = T extends + { valueOf(): infer V extends ArrayBufferLike } ? V : T; + global { + interface BufferConstructor { + // see buffer.d.ts for implementation shared with all TypeScript versions + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. + */ + new(str: string, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). + */ + new(size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: ArrayLike): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}/{SharedArrayBuffer}. + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. + */ + new(arrayBuffer: TArrayBuffer): Buffer; + /** + * Allocates a new `Buffer` using an `array` of bytes in the range `0` – `255`. + * Array entries outside that range will be truncated to fit into it. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'. + * const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); + * ``` + * + * If `array` is an `Array`-like object (that is, one with a `length` property of + * type `number`), it is treated as if it is an array, unless it is a `Buffer` or + * a `Uint8Array`. This means all other `TypedArray` variants get treated as an + * `Array`. To create a `Buffer` from the bytes backing a `TypedArray`, use + * `Buffer.copyBytesFrom()`. + * + * A `TypeError` will be thrown if `array` is not an `Array` or another type + * appropriate for `Buffer.from()` variants. + * + * `Buffer.from(array)` and `Buffer.from(string)` may also use the internal + * `Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v5.10.0 + */ + from(array: WithImplicitCoercion>): Buffer; + /** + * This creates a view of the `ArrayBuffer` without copying the underlying + * memory. For example, when passed a reference to the `.buffer` property of a + * `TypedArray` instance, the newly created `Buffer` will share the same + * allocated memory as the `TypedArray`'s underlying `ArrayBuffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const arr = new Uint16Array(2); + * + * arr[0] = 5000; + * arr[1] = 4000; + * + * // Shares memory with `arr`. + * const buf = Buffer.from(arr.buffer); + * + * console.log(buf); + * // Prints: + * + * // Changing the original Uint16Array changes the Buffer also. + * arr[1] = 6000; + * + * console.log(buf); + * // Prints: + * ``` + * + * The optional `byteOffset` and `length` arguments specify a memory range within + * the `arrayBuffer` that will be shared by the `Buffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const ab = new ArrayBuffer(10); + * const buf = Buffer.from(ab, 0, 2); + * + * console.log(buf.length); + * // Prints: 2 + * ``` + * + * A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer` or a + * `SharedArrayBuffer` or another type appropriate for `Buffer.from()` + * variants. + * + * It is important to remember that a backing `ArrayBuffer` can cover a range + * of memory that extends beyond the bounds of a `TypedArray` view. A new + * `Buffer` created using the `buffer` property of a `TypedArray` may extend + * beyond the range of the `TypedArray`: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements + * const arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements + * console.log(arrA.buffer === arrB.buffer); // true + * + * const buf = Buffer.from(arrB.buffer); + * console.log(buf); + * // Prints: + * ``` + * @since v5.10.0 + * @param arrayBuffer An `ArrayBuffer`, `SharedArrayBuffer`, for example the + * `.buffer` property of a `TypedArray`. + * @param byteOffset Index of first byte to expose. **Default:** `0`. + * @param length Number of bytes to expose. **Default:** + * `arrayBuffer.byteLength - byteOffset`. + */ + from>( + arrayBuffer: TArrayBuffer, + byteOffset?: number, + length?: number, + ): Buffer>; + /** + * Creates a new `Buffer` containing `string`. The `encoding` parameter identifies + * the character encoding to be used when converting `string` into bytes. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('this is a tést'); + * const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); + * + * console.log(buf1.toString()); + * // Prints: this is a tést + * console.log(buf2.toString()); + * // Prints: this is a tést + * console.log(buf1.toString('latin1')); + * // Prints: this is a tést + * ``` + * + * A `TypeError` will be thrown if `string` is not a string or another type + * appropriate for `Buffer.from()` variants. + * + * `Buffer.from(string)` may also use the internal `Buffer` pool like + * `Buffer.allocUnsafe()` does. + * @since v5.10.0 + * @param string A string to encode. + * @param encoding The encoding of `string`. **Default:** `'utf8'`. + */ + from(string: WithImplicitCoercion, encoding?: BufferEncoding): Buffer; + from(arrayOrString: WithImplicitCoercion | string>): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + of(...items: number[]): Buffer; + /** + * Returns a new `Buffer` which is the result of concatenating all the `Buffer` instances in the `list` together. + * + * If the list has no items, or if the `totalLength` is 0, then a new zero-length `Buffer` is returned. + * + * If `totalLength` is not provided, it is calculated from the `Buffer` instances + * in `list` by adding their lengths. + * + * If `totalLength` is provided, it is coerced to an unsigned integer. If the + * combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is + * truncated to `totalLength`. If the combined length of the `Buffer`s in `list` is + * less than `totalLength`, the remaining space is filled with zeros. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a single `Buffer` from a list of three `Buffer` instances. + * + * const buf1 = Buffer.alloc(10); + * const buf2 = Buffer.alloc(14); + * const buf3 = Buffer.alloc(18); + * const totalLength = buf1.length + buf2.length + buf3.length; + * + * console.log(totalLength); + * // Prints: 42 + * + * const bufA = Buffer.concat([buf1, buf2, buf3], totalLength); + * + * console.log(bufA); + * // Prints: + * console.log(bufA.length); + * // Prints: 42 + * ``` + * + * `Buffer.concat()` may also use the internal `Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v0.7.11 + * @param list List of `Buffer` or {@link Uint8Array} instances to concatenate. + * @param totalLength Total length of the `Buffer` instances in `list` when concatenated. + */ + concat(list: readonly Uint8Array[], totalLength?: number): Buffer; + /** + * Copies the underlying memory of `view` into a new `Buffer`. + * + * ```js + * const u16 = new Uint16Array([0, 0xffff]); + * const buf = Buffer.copyBytesFrom(u16, 1, 1); + * u16[1] = 0; + * console.log(buf.length); // 2 + * console.log(buf[0]); // 255 + * console.log(buf[1]); // 255 + * ``` + * @since v19.8.0 + * @param view The {TypedArray} to copy. + * @param [offset=0] The starting offset within `view`. + * @param [length=view.length - offset] The number of elements from `view` to copy. + */ + copyBytesFrom(view: NodeJS.TypedArray, offset?: number, length?: number): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(5); + * + * console.log(buf); + * // Prints: + * ``` + * + * If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. + * + * If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(5, 'a'); + * + * console.log(buf); + * // Prints: + * ``` + * + * If both `fill` and `encoding` are specified, the allocated `Buffer` will be + * initialized by calling `buf.fill(fill, encoding)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); + * + * console.log(buf); + * // Prints: + * ``` + * + * Calling `Buffer.alloc()` can be measurably slower than the alternative `Buffer.allocUnsafe()` but ensures that the newly created `Buffer` instance + * contents will never contain sensitive data from previous allocations, including + * data that might not have been allocated for `Buffer`s. + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + * @param [fill=0] A value to pre-fill the new `Buffer` with. + * @param [encoding='utf8'] If `fill` is a string, this is its encoding. + */ + alloc(size: number, fill?: string | Uint8Array | number, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `Buffer.alloc()` instead to initialize`Buffer` instances with zeroes. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(10); + * + * console.log(buf); + * // Prints (contents may vary): + * + * buf.fill(0); + * + * console.log(buf); + * // Prints: + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * + * The `Buffer` module pre-allocates an internal `Buffer` instance of + * size `Buffer.poolSize` that is used as a pool for the fast allocation of new `Buffer` instances created using `Buffer.allocUnsafe()`, `Buffer.from(array)`, + * and `Buffer.concat()` only when `size` is less than `Buffer.poolSize >>> 1` (floor of `Buffer.poolSize` divided by two). + * + * Use of this pre-allocated internal memory pool is a key difference between + * calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. + * Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`pool, while `Buffer.allocUnsafe(size).fill(fill)`_will_ use the internal`Buffer` pool if `size` is less + * than or equal to half `Buffer.poolSize`. The + * difference is subtle but can be important when an application requires the + * additional performance that `Buffer.allocUnsafe()` provides. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafe(size: number): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. A zero-length `Buffer` is created if + * `size` is 0. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `buf.fill(0)` to initialize + * such `Buffer` instances with zeroes. + * + * When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, + * allocations under 4 KiB are sliced from a single pre-allocated `Buffer`. This + * allows applications to avoid the garbage collection overhead of creating many + * individually allocated `Buffer` instances. This approach improves both + * performance and memory usage by eliminating the need to track and clean up as + * many individual `ArrayBuffer` objects. + * + * However, in the case where a developer may need to retain a small chunk of + * memory from a pool for an indeterminate amount of time, it may be appropriate + * to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and + * then copying out the relevant bits. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Need to keep around a few small chunks of memory. + * const store = []; + * + * socket.on('readable', () => { + * let data; + * while (null !== (data = readable.read())) { + * // Allocate for retained data. + * const sb = Buffer.allocUnsafeSlow(10); + * + * // Copy the data into the new allocation. + * data.copy(sb, 0, 0, 10); + * + * store.push(sb); + * } + * }); + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.12.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafeSlow(size: number): Buffer; + } + interface Buffer extends Uint8Array { + // see buffer.d.ts for implementation shared with all TypeScript versions + + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * This method is not compatible with the `Uint8Array.prototype.slice()`, + * which is a superclass of `Buffer`. To copy the slice, use`Uint8Array.prototype.slice()`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * const copiedBuf = Uint8Array.prototype.slice.call(buf); + * copiedBuf[0]++; + * console.log(copiedBuf.toString()); + * // Prints: cuffer + * + * console.log(buf.toString()); + * // Prints: buffer + * + * // With buf.slice(), the original buffer is modified. + * const notReallyCopiedBuf = buf.slice(); + * notReallyCopiedBuf[0]++; + * console.log(notReallyCopiedBuf.toString()); + * // Prints: cuffer + * console.log(buf.toString()); + * // Also prints: cuffer (!) + * ``` + * @since v0.3.0 + * @deprecated Use `subarray` instead. + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + slice(start?: number, end?: number): Buffer; + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * Specifying `end` greater than `buf.length` will return the same result as + * that of `end` equal to `buf.length`. + * + * This method is inherited from [`TypedArray.prototype.subarray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray). + * + * Modifying the new `Buffer` slice will modify the memory in the original `Buffer`because the allocated memory of the two objects overlap. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte + * // from the original `Buffer`. + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * const buf2 = buf1.subarray(0, 3); + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: abc + * + * buf1[0] = 33; + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: !bc + * ``` + * + * Specifying negative indexes causes the slice to be generated relative to the + * end of `buf` rather than the beginning. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * console.log(buf.subarray(-6, -1).toString()); + * // Prints: buffe + * // (Equivalent to buf.subarray(0, 5).) + * + * console.log(buf.subarray(-6, -2).toString()); + * // Prints: buff + * // (Equivalent to buf.subarray(0, 4).) + * + * console.log(buf.subarray(-5, -2).toString()); + * // Prints: uff + * // (Equivalent to buf.subarray(1, 4).) + * ``` + * @since v3.0.0 + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + subarray(start?: number, end?: number): Buffer; + } + // TODO: remove globals in future version + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedBuffer = Buffer; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type AllowSharedBuffer = Buffer; + } +} diff --git a/backend/node_modules/@types/node/buffer.d.ts b/backend/node_modules/@types/node/buffer.d.ts new file mode 100644 index 0000000..bb0f004 --- /dev/null +++ b/backend/node_modules/@types/node/buffer.d.ts @@ -0,0 +1,1810 @@ +/** + * `Buffer` objects are used to represent a fixed-length sequence of bytes. Many + * Node.js APIs support `Buffer`s. + * + * The `Buffer` class is a subclass of JavaScript's [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) class and + * extends it with methods that cover additional use cases. Node.js APIs accept + * plain [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) s wherever `Buffer`s are supported as well. + * + * While the `Buffer` class is available within the global scope, it is still + * recommended to explicitly reference it via an import or require statement. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Creates a zero-filled Buffer of length 10. + * const buf1 = Buffer.alloc(10); + * + * // Creates a Buffer of length 10, + * // filled with bytes which all have the value `1`. + * const buf2 = Buffer.alloc(10, 1); + * + * // Creates an uninitialized buffer of length 10. + * // This is faster than calling Buffer.alloc() but the returned + * // Buffer instance might contain old data that needs to be + * // overwritten using fill(), write(), or other functions that fill the Buffer's + * // contents. + * const buf3 = Buffer.allocUnsafe(10); + * + * // Creates a Buffer containing the bytes [1, 2, 3]. + * const buf4 = Buffer.from([1, 2, 3]); + * + * // Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries + * // are all truncated using `(value & 255)` to fit into the range 0–255. + * const buf5 = Buffer.from([257, 257.5, -255, '1']); + * + * // Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést': + * // [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation) + * // [116, 195, 169, 115, 116] (in decimal notation) + * const buf6 = Buffer.from('tést'); + * + * // Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74]. + * const buf7 = Buffer.from('tést', 'latin1'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/buffer.js) + */ +declare module "node:buffer" { + import { ReadableStream } from "node:stream/web"; + /** + * This function returns `true` if `input` contains only valid UTF-8-encoded data, + * including the case in which `input` is empty. + * + * Throws if the `input` is a detached array buffer. + * @since v19.4.0, v18.14.0 + * @param input The input to validate. + */ + export function isUtf8(input: ArrayBuffer | NodeJS.TypedArray): boolean; + /** + * This function returns `true` if `input` contains only valid ASCII-encoded data, + * including the case in which `input` is empty. + * + * Throws if the `input` is a detached array buffer. + * @since v19.6.0, v18.15.0 + * @param input The input to validate. + */ + export function isAscii(input: ArrayBuffer | NodeJS.TypedArray): boolean; + export let INSPECT_MAX_BYTES: number; + export const kMaxLength: number; + export const kStringMaxLength: number; + export const constants: { + MAX_LENGTH: number; + MAX_STRING_LENGTH: number; + }; + export type TranscodeEncoding = + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "utf-16le" + | "ucs2" + | "ucs-2" + | "latin1" + | "binary"; + /** + * Re-encodes the given `Buffer` or `Uint8Array` instance from one character + * encoding to another. Returns a new `Buffer` instance. + * + * Throws if the `fromEnc` or `toEnc` specify invalid character encodings or if + * conversion from `fromEnc` to `toEnc` is not permitted. + * + * Encodings supported by `buffer.transcode()` are: `'ascii'`, `'utf8'`, `'utf16le'`, `'ucs2'`, `'latin1'`, and `'binary'`. + * + * The transcoding process will use substitution characters if a given byte + * sequence cannot be adequately represented in the target encoding. For instance: + * + * ```js + * import { Buffer, transcode } from 'node:buffer'; + * + * const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii'); + * console.log(newBuf.toString('ascii')); + * // Prints: '?' + * ``` + * + * Because the Euro (`€`) sign is not representable in US-ASCII, it is replaced + * with `?` in the transcoded `Buffer`. + * @since v7.1.0 + * @param source A `Buffer` or `Uint8Array` instance. + * @param fromEnc The current encoding. + * @param toEnc To target encoding. + */ + export function transcode( + source: Uint8Array, + fromEnc: TranscodeEncoding, + toEnc: TranscodeEncoding, + ): NonSharedBuffer; + /** + * Resolves a `'blob:nodedata:...'` an associated `Blob` object registered using + * a prior call to `URL.createObjectURL()`. + * @since v16.7.0 + * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. + */ + export function resolveObjectURL(id: string): Blob | undefined; + export { type AllowSharedBuffer, Buffer, type NonSharedBuffer }; + /** @deprecated This alias will be removed in a future version. Use the canonical `BlobPropertyBag` instead. */ + // TODO: remove in future major + export interface BlobOptions extends BlobPropertyBag {} + /** @deprecated This alias will be removed in a future version. Use the canonical `FilePropertyBag` instead. */ + export interface FileOptions extends FilePropertyBag {} + export type WithImplicitCoercion = + | T + | { valueOf(): T } + | (T extends string ? { [Symbol.toPrimitive](hint: "string"): T } : never); + global { + namespace NodeJS { + export { BufferEncoding }; + } + // Buffer class + type BufferEncoding = + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "utf-16le" + | "ucs2" + | "ucs-2" + | "base64" + | "base64url" + | "latin1" + | "binary" + | "hex"; + /** + * Raw data is stored in instances of the Buffer class. + * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. + * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'base64url'|'binary'(deprecated)|'hex' + */ + interface BufferConstructor { + // see buffer.buffer.d.ts for implementation specific to TypeScript 5.7 and later + // see ts5.6/buffer.buffer.d.ts for implementation specific to TypeScript 5.6 and earlier + + /** + * Returns `true` if `obj` is a `Buffer`, `false` otherwise. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * Buffer.isBuffer(Buffer.alloc(10)); // true + * Buffer.isBuffer(Buffer.from('foo')); // true + * Buffer.isBuffer('a string'); // false + * Buffer.isBuffer([]); // false + * Buffer.isBuffer(new Uint8Array(1024)); // false + * ``` + * @since v0.1.101 + */ + isBuffer(obj: any): obj is Buffer; + /** + * Returns `true` if `encoding` is the name of a supported character encoding, + * or `false` otherwise. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * console.log(Buffer.isEncoding('utf8')); + * // Prints: true + * + * console.log(Buffer.isEncoding('hex')); + * // Prints: true + * + * console.log(Buffer.isEncoding('utf/8')); + * // Prints: false + * + * console.log(Buffer.isEncoding('')); + * // Prints: false + * ``` + * @since v0.9.1 + * @param encoding A character encoding name to check. + */ + isEncoding(encoding: string): encoding is BufferEncoding; + /** + * Returns the byte length of a string when encoded using `encoding`. + * This is not the same as [`String.prototype.length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length), which does not account + * for the encoding that is used to convert the string into bytes. + * + * For `'base64'`, `'base64url'`, and `'hex'`, this function assumes valid input. + * For strings that contain non-base64/hex-encoded data (e.g. whitespace), the + * return value might be greater than the length of a `Buffer` created from the + * string. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const str = '\u00bd + \u00bc = \u00be'; + * + * console.log(`${str}: ${str.length} characters, ` + + * `${Buffer.byteLength(str, 'utf8')} bytes`); + * // Prints: ½ + ¼ = ¾: 9 characters, 12 bytes + * ``` + * + * When `string` is a + * `Buffer`/[`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)/[`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/- + * Reference/Global_Objects/TypedArray)/[`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)/[`SharedArrayBuffer`](https://develop- + * er.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer), the byte length as reported by `.byteLength`is returned. + * @since v0.1.90 + * @param string A value to calculate the length of. + * @param [encoding='utf8'] If `string` is a string, this is its encoding. + * @return The number of bytes contained within `string`. + */ + byteLength( + string: string | NodeJS.ArrayBufferView | ArrayBufferLike, + encoding?: BufferEncoding, + ): number; + /** + * Compares `buf1` to `buf2`, typically for the purpose of sorting arrays of `Buffer` instances. This is equivalent to calling `buf1.compare(buf2)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('1234'); + * const buf2 = Buffer.from('0123'); + * const arr = [buf1, buf2]; + * + * console.log(arr.sort(Buffer.compare)); + * // Prints: [ , ] + * // (This result is equal to: [buf2, buf1].) + * ``` + * @since v0.11.13 + * @return Either `-1`, `0`, or `1`, depending on the result of the comparison. See `compare` for details. + */ + compare(buf1: Uint8Array, buf2: Uint8Array): -1 | 0 | 1; + /** + * This is the size (in bytes) of pre-allocated internal `Buffer` instances used + * for pooling. This value may be modified. + * @since v0.11.3 + */ + poolSize: number; + } + interface Buffer { + // see buffer.buffer.d.ts for implementation specific to TypeScript 5.7 and later + // see ts5.6/buffer.buffer.d.ts for implementation specific to TypeScript 5.6 and earlier + + /** + * Writes `string` to `buf` at `offset` according to the character encoding in`encoding`. The `length` parameter is the number of bytes to write. If `buf` did + * not contain enough space to fit the entire string, only part of `string` will be + * written. However, partially encoded characters will not be written. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(256); + * + * const len = buf.write('\u00bd + \u00bc = \u00be', 0); + * + * console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`); + * // Prints: 12 bytes: ½ + ¼ = ¾ + * + * const buffer = Buffer.alloc(10); + * + * const length = buffer.write('abcd', 8); + * + * console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`); + * // Prints: 2 bytes : ab + * ``` + * @since v0.1.90 + * @param string String to write to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write `string`. + * @param [length=buf.length - offset] Maximum number of bytes to write (written bytes will not exceed `buf.length - offset`). + * @param [encoding='utf8'] The character encoding of `string`. + * @return Number of bytes written. + */ + write(string: string, encoding?: BufferEncoding): number; + write(string: string, offset: number, encoding?: BufferEncoding): number; + write(string: string, offset: number, length: number, encoding?: BufferEncoding): number; + /** + * Decodes `buf` to a string according to the specified character encoding in`encoding`. `start` and `end` may be passed to decode only a subset of `buf`. + * + * If `encoding` is `'utf8'` and a byte sequence in the input is not valid UTF-8, + * then each invalid byte is replaced with the replacement character `U+FFFD`. + * + * The maximum length of a string instance (in UTF-16 code units) is available + * as {@link constants.MAX_STRING_LENGTH}. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * console.log(buf1.toString('utf8')); + * // Prints: abcdefghijklmnopqrstuvwxyz + * console.log(buf1.toString('utf8', 0, 5)); + * // Prints: abcde + * + * const buf2 = Buffer.from('tést'); + * + * console.log(buf2.toString('hex')); + * // Prints: 74c3a97374 + * console.log(buf2.toString('utf8', 0, 3)); + * // Prints: té + * console.log(buf2.toString(undefined, 0, 3)); + * // Prints: té + * ``` + * @since v0.1.90 + * @param [encoding='utf8'] The character encoding to use. + * @param [start=0] The byte offset to start decoding at. + * @param [end=buf.length] The byte offset to stop decoding at (not inclusive). + */ + toString(encoding?: BufferEncoding, start?: number, end?: number): string; + /** + * Returns a JSON representation of `buf`. [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) implicitly calls + * this function when stringifying a `Buffer` instance. + * + * `Buffer.from()` accepts objects in the format returned from this method. + * In particular, `Buffer.from(buf.toJSON())` works like `Buffer.from(buf)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]); + * const json = JSON.stringify(buf); + * + * console.log(json); + * // Prints: {"type":"Buffer","data":[1,2,3,4,5]} + * + * const copy = JSON.parse(json, (key, value) => { + * return value && value.type === 'Buffer' ? + * Buffer.from(value) : + * value; + * }); + * + * console.log(copy); + * // Prints: + * ``` + * @since v0.9.2 + */ + toJSON(): { + type: "Buffer"; + data: number[]; + }; + /** + * Returns `true` if both `buf` and `otherBuffer` have exactly the same bytes,`false` otherwise. Equivalent to `buf.compare(otherBuffer) === 0`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('ABC'); + * const buf2 = Buffer.from('414243', 'hex'); + * const buf3 = Buffer.from('ABCD'); + * + * console.log(buf1.equals(buf2)); + * // Prints: true + * console.log(buf1.equals(buf3)); + * // Prints: false + * ``` + * @since v0.11.13 + * @param otherBuffer A `Buffer` or {@link Uint8Array} with which to compare `buf`. + */ + equals(otherBuffer: Uint8Array): boolean; + /** + * Compares `buf` with `target` and returns a number indicating whether `buf`comes before, after, or is the same as `target` in sort order. + * Comparison is based on the actual sequence of bytes in each `Buffer`. + * + * * `0` is returned if `target` is the same as `buf` + * * `1` is returned if `target` should come _before_`buf` when sorted. + * * `-1` is returned if `target` should come _after_`buf` when sorted. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('ABC'); + * const buf2 = Buffer.from('BCD'); + * const buf3 = Buffer.from('ABCD'); + * + * console.log(buf1.compare(buf1)); + * // Prints: 0 + * console.log(buf1.compare(buf2)); + * // Prints: -1 + * console.log(buf1.compare(buf3)); + * // Prints: -1 + * console.log(buf2.compare(buf1)); + * // Prints: 1 + * console.log(buf2.compare(buf3)); + * // Prints: 1 + * console.log([buf1, buf2, buf3].sort(Buffer.compare)); + * // Prints: [ , , ] + * // (This result is equal to: [buf1, buf3, buf2].) + * ``` + * + * The optional `targetStart`, `targetEnd`, `sourceStart`, and `sourceEnd` arguments can be used to limit the comparison to specific ranges within `target` and `buf` respectively. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]); + * const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]); + * + * console.log(buf1.compare(buf2, 5, 9, 0, 4)); + * // Prints: 0 + * console.log(buf1.compare(buf2, 0, 6, 4)); + * // Prints: -1 + * console.log(buf1.compare(buf2, 5, 6, 5)); + * // Prints: 1 + * ``` + * + * `ERR_OUT_OF_RANGE` is thrown if `targetStart < 0`, `sourceStart < 0`, `targetEnd > target.byteLength`, or `sourceEnd > source.byteLength`. + * @since v0.11.13 + * @param target A `Buffer` or {@link Uint8Array} with which to compare `buf`. + * @param [targetStart=0] The offset within `target` at which to begin comparison. + * @param [targetEnd=target.length] The offset within `target` at which to end comparison (not inclusive). + * @param [sourceStart=0] The offset within `buf` at which to begin comparison. + * @param [sourceEnd=buf.length] The offset within `buf` at which to end comparison (not inclusive). + */ + compare( + target: Uint8Array, + targetStart?: number, + targetEnd?: number, + sourceStart?: number, + sourceEnd?: number, + ): -1 | 0 | 1; + /** + * Copies data from a region of `buf` to a region in `target`, even if the `target`memory region overlaps with `buf`. + * + * [`TypedArray.prototype.set()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set) performs the same operation, and is available + * for all TypedArrays, including Node.js `Buffer`s, although it takes + * different function arguments. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create two `Buffer` instances. + * const buf1 = Buffer.allocUnsafe(26); + * const buf2 = Buffer.allocUnsafe(26).fill('!'); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * // Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`. + * buf1.copy(buf2, 8, 16, 20); + * // This is equivalent to: + * // buf2.set(buf1.subarray(16, 20), 8); + * + * console.log(buf2.toString('ascii', 0, 25)); + * // Prints: !!!!!!!!qrst!!!!!!!!!!!!! + * ``` + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a `Buffer` and copy data from one region to an overlapping region + * // within the same `Buffer`. + * + * const buf = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf[i] = i + 97; + * } + * + * buf.copy(buf, 0, 4, 10); + * + * console.log(buf.toString()); + * // Prints: efghijghijklmnopqrstuvwxyz + * ``` + * @since v0.1.90 + * @param target A `Buffer` or {@link Uint8Array} to copy into. + * @param [targetStart=0] The offset within `target` at which to begin writing. + * @param [sourceStart=0] The offset within `buf` from which to begin copying. + * @param [sourceEnd=buf.length] The offset within `buf` at which to stop copying (not inclusive). + * @return The number of bytes copied. + */ + copy(target: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigInt64BE(0x0102030405060708n, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigInt64BE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigInt64LE(0x0102030405060708n, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigInt64LE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. + * + * This function is also available under the `writeBigUint64BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigUInt64BE(0xdecafafecacefaden, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigUInt64BE(value: bigint, offset?: number): number; + /** + * @alias Buffer.writeBigUInt64BE + * @since v14.10.0, v12.19.0 + */ + writeBigUint64BE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigUInt64LE(0xdecafafecacefaden, 0); + * + * console.log(buf); + * // Prints: + * ``` + * + * This function is also available under the `writeBigUint64LE` alias. + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigUInt64LE(value: bigint, offset?: number): number; + /** + * @alias Buffer.writeBigUInt64LE + * @since v14.10.0, v12.19.0 + */ + writeBigUint64LE(value: bigint, offset?: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than an unsigned integer. + * + * This function is also available under the `writeUintLE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeUIntLE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeUIntLE(value: number, offset: number, byteLength: number): number; + /** + * @alias Buffer.writeUIntLE + * @since v14.9.0, v12.19.0 + */ + writeUintLE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than an unsigned integer. + * + * This function is also available under the `writeUintBE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeUIntBE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeUIntBE(value: number, offset: number, byteLength: number): number; + /** + * @alias Buffer.writeUIntBE + * @since v14.9.0, v12.19.0 + */ + writeUintBE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than a signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeIntLE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeIntLE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when`value` is anything other than a + * signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeIntBE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeIntBE(value: number, offset: number, byteLength: number): number; + /** + * Reads an unsigned, big-endian 64-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readBigUint64BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + * + * console.log(buf.readBigUInt64BE(0)); + * // Prints: 4294967295n + * ``` + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigUInt64BE(offset?: number): bigint; + /** + * @alias Buffer.readBigUInt64BE + * @since v14.10.0, v12.19.0 + */ + readBigUint64BE(offset?: number): bigint; + /** + * Reads an unsigned, little-endian 64-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readBigUint64LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + * + * console.log(buf.readBigUInt64LE(0)); + * // Prints: 18446744069414584320n + * ``` + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigUInt64LE(offset?: number): bigint; + /** + * @alias Buffer.readBigUInt64LE + * @since v14.10.0, v12.19.0 + */ + readBigUint64LE(offset?: number): bigint; + /** + * Reads a signed, big-endian 64-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed + * values. + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigInt64BE(offset?: number): bigint; + /** + * Reads a signed, little-endian 64-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed + * values. + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigInt64LE(offset?: number): bigint; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as an unsigned, little-endian integer supporting + * up to 48 bits of accuracy. + * + * This function is also available under the `readUintLE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readUIntLE(0, 6).toString(16)); + * // Prints: ab9078563412 + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readUIntLE(offset: number, byteLength: number): number; + /** + * @alias Buffer.readUIntLE + * @since v14.9.0, v12.19.0 + */ + readUintLE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as an unsigned big-endian integer supporting + * up to 48 bits of accuracy. + * + * This function is also available under the `readUintBE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readUIntBE(0, 6).toString(16)); + * // Prints: 1234567890ab + * console.log(buf.readUIntBE(1, 6).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readUIntBE(offset: number, byteLength: number): number; + /** + * @alias Buffer.readUIntBE + * @since v14.9.0, v12.19.0 + */ + readUintBE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as a little-endian, two's complement signed value + * supporting up to 48 bits of accuracy. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readIntLE(0, 6).toString(16)); + * // Prints: -546f87a9cbee + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readIntLE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as a big-endian, two's complement signed value + * supporting up to 48 bits of accuracy. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readIntBE(0, 6).toString(16)); + * // Prints: 1234567890ab + * console.log(buf.readIntBE(1, 6).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * console.log(buf.readIntBE(1, 0).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readIntBE(offset: number, byteLength: number): number; + /** + * Reads an unsigned 8-bit integer from `buf` at the specified `offset`. + * + * This function is also available under the `readUint8` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, -2]); + * + * console.log(buf.readUInt8(0)); + * // Prints: 1 + * console.log(buf.readUInt8(1)); + * // Prints: 254 + * console.log(buf.readUInt8(2)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. + */ + readUInt8(offset?: number): number; + /** + * @alias Buffer.readUInt8 + * @since v14.9.0, v12.19.0 + */ + readUint8(offset?: number): number; + /** + * Reads an unsigned, little-endian 16-bit integer from `buf` at the specified `offset`. + * + * This function is also available under the `readUint16LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56]); + * + * console.log(buf.readUInt16LE(0).toString(16)); + * // Prints: 3412 + * console.log(buf.readUInt16LE(1).toString(16)); + * // Prints: 5634 + * console.log(buf.readUInt16LE(2).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readUInt16LE(offset?: number): number; + /** + * @alias Buffer.readUInt16LE + * @since v14.9.0, v12.19.0 + */ + readUint16LE(offset?: number): number; + /** + * Reads an unsigned, big-endian 16-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint16BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56]); + * + * console.log(buf.readUInt16BE(0).toString(16)); + * // Prints: 1234 + * console.log(buf.readUInt16BE(1).toString(16)); + * // Prints: 3456 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readUInt16BE(offset?: number): number; + /** + * @alias Buffer.readUInt16BE + * @since v14.9.0, v12.19.0 + */ + readUint16BE(offset?: number): number; + /** + * Reads an unsigned, little-endian 32-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint32LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + * + * console.log(buf.readUInt32LE(0).toString(16)); + * // Prints: 78563412 + * console.log(buf.readUInt32LE(1).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readUInt32LE(offset?: number): number; + /** + * @alias Buffer.readUInt32LE + * @since v14.9.0, v12.19.0 + */ + readUint32LE(offset?: number): number; + /** + * Reads an unsigned, big-endian 32-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint32BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + * + * console.log(buf.readUInt32BE(0).toString(16)); + * // Prints: 12345678 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readUInt32BE(offset?: number): number; + /** + * @alias Buffer.readUInt32BE + * @since v14.9.0, v12.19.0 + */ + readUint32BE(offset?: number): number; + /** + * Reads a signed 8-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([-1, 5]); + * + * console.log(buf.readInt8(0)); + * // Prints: -1 + * console.log(buf.readInt8(1)); + * // Prints: 5 + * console.log(buf.readInt8(2)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. + */ + readInt8(offset?: number): number; + /** + * Reads a signed, little-endian 16-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 5]); + * + * console.log(buf.readInt16LE(0)); + * // Prints: 1280 + * console.log(buf.readInt16LE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readInt16LE(offset?: number): number; + /** + * Reads a signed, big-endian 16-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 5]); + * + * console.log(buf.readInt16BE(0)); + * // Prints: 5 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readInt16BE(offset?: number): number; + /** + * Reads a signed, little-endian 32-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 0, 0, 5]); + * + * console.log(buf.readInt32LE(0)); + * // Prints: 83886080 + * console.log(buf.readInt32LE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readInt32LE(offset?: number): number; + /** + * Reads a signed, big-endian 32-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 0, 0, 5]); + * + * console.log(buf.readInt32BE(0)); + * // Prints: 5 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readInt32BE(offset?: number): number; + /** + * Reads a 32-bit, little-endian float from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4]); + * + * console.log(buf.readFloatLE(0)); + * // Prints: 1.539989614439558e-36 + * console.log(buf.readFloatLE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readFloatLE(offset?: number): number; + /** + * Reads a 32-bit, big-endian float from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4]); + * + * console.log(buf.readFloatBE(0)); + * // Prints: 2.387939260590663e-38 + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readFloatBE(offset?: number): number; + /** + * Reads a 64-bit, little-endian double from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + * + * console.log(buf.readDoubleLE(0)); + * // Prints: 5.447603722011605e-270 + * console.log(buf.readDoubleLE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. + */ + readDoubleLE(offset?: number): number; + /** + * Reads a 64-bit, big-endian double from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + * + * console.log(buf.readDoubleBE(0)); + * // Prints: 8.20788039913184e-304 + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. + */ + readDoubleBE(offset?: number): number; + reverse(): this; + /** + * Interprets `buf` as an array of unsigned 16-bit integers and swaps the + * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 2. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap16(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap16(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * + * One convenient use of `buf.swap16()` is to perform a fast in-place conversion + * between UTF-16 little-endian and UTF-16 big-endian: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('This is little-endian UTF-16', 'utf16le'); + * buf.swap16(); // Convert to big-endian UTF-16 text. + * ``` + * @since v5.10.0 + * @return A reference to `buf`. + */ + swap16(): this; + /** + * Interprets `buf` as an array of unsigned 32-bit integers and swaps the + * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 4. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap32(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap32(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * @since v5.10.0 + * @return A reference to `buf`. + */ + swap32(): this; + /** + * Interprets `buf` as an array of 64-bit numbers and swaps byte order _in-place_. + * Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 8. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap64(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap64(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * @since v6.3.0 + * @return A reference to `buf`. + */ + swap64(): this; + /** + * Writes `value` to `buf` at the specified `offset`. `value` must be a + * valid unsigned 8-bit integer. Behavior is undefined when `value` is anything + * other than an unsigned 8-bit integer. + * + * This function is also available under the `writeUint8` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt8(0x3, 0); + * buf.writeUInt8(0x4, 1); + * buf.writeUInt8(0x23, 2); + * buf.writeUInt8(0x42, 3); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. + * @return `offset` plus the number of bytes written. + */ + writeUInt8(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt8 + * @since v14.9.0, v12.19.0 + */ + writeUint8(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid unsigned 16-bit integer. Behavior is undefined when `value` is + * anything other than an unsigned 16-bit integer. + * + * This function is also available under the `writeUint16LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt16LE(0xdead, 0); + * buf.writeUInt16LE(0xbeef, 2); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeUInt16LE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt16LE + * @since v14.9.0, v12.19.0 + */ + writeUint16LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid unsigned 16-bit integer. Behavior is undefined when `value`is anything other than an + * unsigned 16-bit integer. + * + * This function is also available under the `writeUint16BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt16BE(0xdead, 0); + * buf.writeUInt16BE(0xbeef, 2); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeUInt16BE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt16BE + * @since v14.9.0, v12.19.0 + */ + writeUint16BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid unsigned 32-bit integer. Behavior is undefined when `value` is + * anything other than an unsigned 32-bit integer. + * + * This function is also available under the `writeUint32LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt32LE(0xfeedface, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeUInt32LE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt32LE + * @since v14.9.0, v12.19.0 + */ + writeUint32LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid unsigned 32-bit integer. Behavior is undefined when `value`is anything other than an + * unsigned 32-bit integer. + * + * This function is also available under the `writeUint32BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt32BE(0xfeedface, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeUInt32BE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt32BE + * @since v14.9.0, v12.19.0 + */ + writeUint32BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset`. `value` must be a valid + * signed 8-bit integer. Behavior is undefined when `value` is anything other than + * a signed 8-bit integer. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt8(2, 0); + * buf.writeInt8(-2, 1); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. + * @return `offset` plus the number of bytes written. + */ + writeInt8(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * anything other than a signed 16-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt16LE(0x0304, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeInt16LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * anything other than a signed 16-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt16BE(0x0102, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeInt16BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * anything other than a signed 32-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeInt32LE(0x05060708, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeInt32LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * anything other than a signed 32-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeInt32BE(0x01020304, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeInt32BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. Behavior is + * undefined when `value` is anything other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeFloatLE(0xcafebabe, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeFloatLE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. Behavior is + * undefined when `value` is anything other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeFloatBE(0xcafebabe, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeFloatBE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a JavaScript number. Behavior is undefined when `value` is anything + * other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeDoubleLE(123.456, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeDoubleLE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a JavaScript number. Behavior is undefined when `value` is anything + * other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeDoubleBE(123.456, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeDoubleBE(value: number, offset?: number): number; + /** + * Fills `buf` with the specified `value`. If the `offset` and `end` are not given, + * the entire `buf` will be filled: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Fill a `Buffer` with the ASCII character 'h'. + * + * const b = Buffer.allocUnsafe(50).fill('h'); + * + * console.log(b.toString()); + * // Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh + * + * // Fill a buffer with empty string + * const c = Buffer.allocUnsafe(5).fill(''); + * + * console.log(c.fill('')); + * // Prints: + * ``` + * + * `value` is coerced to a `uint32` value if it is not a string, `Buffer`, or + * integer. If the resulting integer is greater than `255` (decimal), `buf` will be + * filled with `value & 255`. + * + * If the final write of a `fill()` operation falls on a multi-byte character, + * then only the bytes of that character that fit into `buf` are written: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Fill a `Buffer` with character that takes up two bytes in UTF-8. + * + * console.log(Buffer.allocUnsafe(5).fill('\u0222')); + * // Prints: + * ``` + * + * If `value` contains invalid characters, it is truncated; if no valid + * fill data remains, an exception is thrown: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(5); + * + * console.log(buf.fill('a')); + * // Prints: + * console.log(buf.fill('aazz', 'hex')); + * // Prints: + * console.log(buf.fill('zz', 'hex')); + * // Throws an exception. + * ``` + * @since v0.5.0 + * @param value The value with which to fill `buf`. Empty value (string, Uint8Array, Buffer) is coerced to `0`. + * @param [offset=0] Number of bytes to skip before starting to fill `buf`. + * @param [end=buf.length] Where to stop filling `buf` (not inclusive). + * @param [encoding='utf8'] The encoding for `value` if `value` is a string. + * @return A reference to `buf`. + */ + fill(value: string | Uint8Array | number, offset?: number, end?: number, encoding?: BufferEncoding): this; + fill(value: string | Uint8Array | number, offset: number, encoding: BufferEncoding): this; + fill(value: string | Uint8Array | number, encoding: BufferEncoding): this; + /** + * If `value` is: + * + * * a string, `value` is interpreted according to the character encoding in `encoding`. + * * a `Buffer` or [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array), `value` will be used in its entirety. + * To compare a partial `Buffer`, use `buf.subarray`. + * * a number, `value` will be interpreted as an unsigned 8-bit integer + * value between `0` and `255`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('this is a buffer'); + * + * console.log(buf.indexOf('this')); + * // Prints: 0 + * console.log(buf.indexOf('is')); + * // Prints: 2 + * console.log(buf.indexOf(Buffer.from('a buffer'))); + * // Prints: 8 + * console.log(buf.indexOf(97)); + * // Prints: 8 (97 is the decimal ASCII value for 'a') + * console.log(buf.indexOf(Buffer.from('a buffer example'))); + * // Prints: -1 + * console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8))); + * // Prints: 8 + * + * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); + * + * console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le')); + * // Prints: 4 + * console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le')); + * // Prints: 6 + * ``` + * + * If `value` is not a string, number, or `Buffer`, this method will throw a `TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * an integer between 0 and 255. + * + * If `byteOffset` is not a number, it will be coerced to a number. If the result + * of coercion is `NaN` or `0`, then the entire buffer will be searched. This + * behavior matches [`String.prototype.indexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf). + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const b = Buffer.from('abcdef'); + * + * // Passing a value that's a number, but not a valid byte. + * // Prints: 2, equivalent to searching for 99 or 'c'. + * console.log(b.indexOf(99.9)); + * console.log(b.indexOf(256 + 99)); + * + * // Passing a byteOffset that coerces to NaN or 0. + * // Prints: 1, searching the whole buffer. + * console.log(b.indexOf('b', undefined)); + * console.log(b.indexOf('b', {})); + * console.log(b.indexOf('b', null)); + * console.log(b.indexOf('b', [])); + * ``` + * + * If `value` is an empty string or empty `Buffer` and `byteOffset` is less + * than `buf.length`, `byteOffset` will be returned. If `value` is empty and`byteOffset` is at least `buf.length`, `buf.length` will be returned. + * @since v1.5.0 + * @param value What to search for. + * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. + * @return The index of the first occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. + */ + indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + indexOf(value: string | number | Uint8Array, encoding: BufferEncoding): number; + /** + * Identical to `buf.indexOf()`, except the last occurrence of `value` is found + * rather than the first occurrence. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('this buffer is a buffer'); + * + * console.log(buf.lastIndexOf('this')); + * // Prints: 0 + * console.log(buf.lastIndexOf('buffer')); + * // Prints: 17 + * console.log(buf.lastIndexOf(Buffer.from('buffer'))); + * // Prints: 17 + * console.log(buf.lastIndexOf(97)); + * // Prints: 15 (97 is the decimal ASCII value for 'a') + * console.log(buf.lastIndexOf(Buffer.from('yolo'))); + * // Prints: -1 + * console.log(buf.lastIndexOf('buffer', 5)); + * // Prints: 5 + * console.log(buf.lastIndexOf('buffer', 4)); + * // Prints: -1 + * + * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); + * + * console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le')); + * // Prints: 6 + * console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le')); + * // Prints: 4 + * ``` + * + * If `value` is not a string, number, or `Buffer`, this method will throw a `TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * an integer between 0 and 255. + * + * If `byteOffset` is not a number, it will be coerced to a number. Any arguments + * that coerce to `NaN`, like `{}` or `undefined`, will search the whole buffer. + * This behavior matches [`String.prototype.lastIndexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf). + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const b = Buffer.from('abcdef'); + * + * // Passing a value that's a number, but not a valid byte. + * // Prints: 2, equivalent to searching for 99 or 'c'. + * console.log(b.lastIndexOf(99.9)); + * console.log(b.lastIndexOf(256 + 99)); + * + * // Passing a byteOffset that coerces to NaN. + * // Prints: 1, searching the whole buffer. + * console.log(b.lastIndexOf('b', undefined)); + * console.log(b.lastIndexOf('b', {})); + * + * // Passing a byteOffset that coerces to 0. + * // Prints: -1, equivalent to passing 0. + * console.log(b.lastIndexOf('b', null)); + * console.log(b.lastIndexOf('b', [])); + * ``` + * + * If `value` is an empty string or empty `Buffer`, `byteOffset` will be returned. + * @since v6.0.0 + * @param value What to search for. + * @param [byteOffset=buf.length - 1] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. + * @return The index of the last occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. + */ + lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + lastIndexOf(value: string | number | Uint8Array, encoding: BufferEncoding): number; + /** + * Equivalent to `buf.indexOf() !== -1`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('this is a buffer'); + * + * console.log(buf.includes('this')); + * // Prints: true + * console.log(buf.includes('is')); + * // Prints: true + * console.log(buf.includes(Buffer.from('a buffer'))); + * // Prints: true + * console.log(buf.includes(97)); + * // Prints: true (97 is the decimal ASCII value for 'a') + * console.log(buf.includes(Buffer.from('a buffer example'))); + * // Prints: false + * console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8))); + * // Prints: true + * console.log(buf.includes('this', 4)); + * // Prints: false + * ``` + * @since v5.3.0 + * @param value What to search for. + * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is its encoding. + * @return `true` if `value` was found in `buf`, `false` otherwise. + */ + includes(value: string | number | Buffer, byteOffset?: number, encoding?: BufferEncoding): boolean; + includes(value: string | number | Buffer, encoding: BufferEncoding): boolean; + } + var Buffer: BufferConstructor; + } + // #region web types + export type BlobPart = NodeJS.BufferSource | Blob | string; + export interface BlobPropertyBag { + endings?: "native" | "transparent"; + type?: string; + } + export interface FilePropertyBag extends BlobPropertyBag { + lastModified?: number; + } + export interface Blob { + readonly size: number; + readonly type: string; + arrayBuffer(): Promise; + bytes(): Promise; + slice(start?: number, end?: number, contentType?: string): Blob; + stream(): ReadableStream; + text(): Promise; + } + export var Blob: { + prototype: Blob; + new(blobParts?: BlobPart[], options?: BlobPropertyBag): Blob; + }; + export interface File extends Blob { + readonly lastModified: number; + readonly name: string; + readonly webkitRelativePath: string; + } + export var File: { + prototype: File; + new(fileBits: BlobPart[], fileName: string, options?: FilePropertyBag): File; + }; + export import atob = globalThis.atob; + export import btoa = globalThis.btoa; + // #endregion +} +declare module "buffer" { + export * from "node:buffer"; +} diff --git a/backend/node_modules/@types/node/child_process.d.ts b/backend/node_modules/@types/node/child_process.d.ts new file mode 100644 index 0000000..e546fe6 --- /dev/null +++ b/backend/node_modules/@types/node/child_process.d.ts @@ -0,0 +1,1428 @@ +/** + * The `node:child_process` module provides the ability to spawn subprocesses in + * a manner that is similar, but not identical, to [`popen(3)`](http://man7.org/linux/man-pages/man3/popen.3.html). This capability + * is primarily provided by the {@link spawn} function: + * + * ```js + * import { spawn } from 'node:child_process'; + * const ls = spawn('ls', ['-lh', '/usr']); + * + * ls.stdout.on('data', (data) => { + * console.log(`stdout: ${data}`); + * }); + * + * ls.stderr.on('data', (data) => { + * console.error(`stderr: ${data}`); + * }); + * + * ls.on('close', (code) => { + * console.log(`child process exited with code ${code}`); + * }); + * ``` + * + * By default, pipes for `stdin`, `stdout`, and `stderr` are established between + * the parent Node.js process and the spawned subprocess. These pipes have + * limited (and platform-specific) capacity. If the subprocess writes to + * stdout in excess of that limit without the output being captured, the + * subprocess blocks, waiting for the pipe buffer to accept more data. This is + * identical to the behavior of pipes in the shell. Use the `{ stdio: 'ignore' }` option if the output will not be consumed. + * + * The command lookup is performed using the `options.env.PATH` environment + * variable if `env` is in the `options` object. Otherwise, `process.env.PATH` is + * used. If `options.env` is set without `PATH`, lookup on Unix is performed + * on a default search path search of `/usr/bin:/bin` (see your operating system's + * manual for execvpe/execvp), on Windows the current processes environment + * variable `PATH` is used. + * + * On Windows, environment variables are case-insensitive. Node.js + * lexicographically sorts the `env` keys and uses the first one that + * case-insensitively matches. Only first (in lexicographic order) entry will be + * passed to the subprocess. This might lead to issues on Windows when passing + * objects to the `env` option that have multiple variants of the same key, such as `PATH` and `Path`. + * + * The {@link spawn} method spawns the child process asynchronously, + * without blocking the Node.js event loop. The {@link spawnSync} function provides equivalent functionality in a synchronous manner that blocks + * the event loop until the spawned process either exits or is terminated. + * + * For convenience, the `node:child_process` module provides a handful of + * synchronous and asynchronous alternatives to {@link spawn} and {@link spawnSync}. Each of these alternatives are implemented on + * top of {@link spawn} or {@link spawnSync}. + * + * * {@link exec}: spawns a shell and runs a command within that + * shell, passing the `stdout` and `stderr` to a callback function when + * complete. + * * {@link execFile}: similar to {@link exec} except + * that it spawns the command directly without first spawning a shell by + * default. + * * {@link fork}: spawns a new Node.js process and invokes a + * specified module with an IPC communication channel established that allows + * sending messages between parent and child. + * * {@link execSync}: a synchronous version of {@link exec} that will block the Node.js event loop. + * * {@link execFileSync}: a synchronous version of {@link execFile} that will block the Node.js event loop. + * + * For certain use cases, such as automating shell scripts, the `synchronous counterparts` may be more convenient. In many cases, however, + * the synchronous methods can have significant impact on performance due to + * stalling the event loop while spawned processes complete. + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/child_process.js) + */ +declare module "node:child_process" { + import { NonSharedBuffer } from "node:buffer"; + import * as dgram from "node:dgram"; + import { Abortable, EventEmitter, InternalEventEmitter } from "node:events"; + import * as net from "node:net"; + import { Readable, Stream, Writable } from "node:stream"; + import { URL } from "node:url"; + type Serializable = string | object | number | boolean | bigint; + type SendHandle = net.Socket | net.Server | dgram.Socket | undefined; + interface ChildProcessEventMap { + "close": [code: number | null, signal: NodeJS.Signals | null]; + "disconnect": []; + "error": [err: Error]; + "exit": [code: number | null, signal: NodeJS.Signals | null]; + "message": [message: Serializable, sendHandle: SendHandle]; + "spawn": []; + } + /** + * Instances of the `ChildProcess` represent spawned child processes. + * + * Instances of `ChildProcess` are not intended to be created directly. Rather, + * use the {@link spawn}, {@link exec},{@link execFile}, or {@link fork} methods to create + * instances of `ChildProcess`. + * @since v2.2.0 + */ + class ChildProcess implements EventEmitter { + /** + * A `Writable Stream` that represents the child process's `stdin`. + * + * If a child process waits to read all of its input, the child will not continue + * until this stream has been closed via `end()`. + * + * If the child was spawned with `stdio[0]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stdin` is an alias for `subprocess.stdio[0]`. Both properties will + * refer to the same value. + * + * The `subprocess.stdin` property can be `null` or `undefined` if the child process could not be successfully spawned. + * @since v0.1.90 + */ + stdin: Writable | null; + /** + * A `Readable Stream` that represents the child process's `stdout`. + * + * If the child was spawned with `stdio[1]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stdout` is an alias for `subprocess.stdio[1]`. Both properties will + * refer to the same value. + * + * ```js + * import { spawn } from 'node:child_process'; + * + * const subprocess = spawn('ls'); + * + * subprocess.stdout.on('data', (data) => { + * console.log(`Received chunk ${data}`); + * }); + * ``` + * + * The `subprocess.stdout` property can be `null` or `undefined` if the child process could not be successfully spawned. + * @since v0.1.90 + */ + stdout: Readable | null; + /** + * A `Readable Stream` that represents the child process's `stderr`. + * + * If the child was spawned with `stdio[2]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stderr` is an alias for `subprocess.stdio[2]`. Both properties will + * refer to the same value. + * + * The `subprocess.stderr` property can be `null` or `undefined` if the child process could not be successfully spawned. + * @since v0.1.90 + */ + stderr: Readable | null; + /** + * The `subprocess.channel` property is a reference to the child's IPC channel. If + * no IPC channel exists, this property is `undefined`. + * @since v7.1.0 + */ + readonly channel?: Control | null; + /** + * A sparse array of pipes to the child process, corresponding with positions in + * the `stdio` option passed to {@link spawn} that have been set + * to the value `'pipe'`. `subprocess.stdio[0]`, `subprocess.stdio[1]`, and `subprocess.stdio[2]` are also available as `subprocess.stdin`, `subprocess.stdout`, and `subprocess.stderr`, + * respectively. + * + * In the following example, only the child's fd `1` (stdout) is configured as a + * pipe, so only the parent's `subprocess.stdio[1]` is a stream, all other values + * in the array are `null`. + * + * ```js + * import assert from 'node:assert'; + * import fs from 'node:fs'; + * import child_process from 'node:child_process'; + * + * const subprocess = child_process.spawn('ls', { + * stdio: [ + * 0, // Use parent's stdin for child. + * 'pipe', // Pipe child's stdout to parent. + * fs.openSync('err.out', 'w'), // Direct child's stderr to a file. + * ], + * }); + * + * assert.strictEqual(subprocess.stdio[0], null); + * assert.strictEqual(subprocess.stdio[0], subprocess.stdin); + * + * assert(subprocess.stdout); + * assert.strictEqual(subprocess.stdio[1], subprocess.stdout); + * + * assert.strictEqual(subprocess.stdio[2], null); + * assert.strictEqual(subprocess.stdio[2], subprocess.stderr); + * ``` + * + * The `subprocess.stdio` property can be `undefined` if the child process could + * not be successfully spawned. + * @since v0.7.10 + */ + readonly stdio: [ + Writable | null, + // stdin + Readable | null, + // stdout + Readable | null, + // stderr + Readable | Writable | null | undefined, + // extra + Readable | Writable | null | undefined, // extra + ]; + /** + * The `subprocess.killed` property indicates whether the child process + * successfully received a signal from `subprocess.kill()`. The `killed` property + * does not indicate that the child process has been terminated. + * @since v0.5.10 + */ + readonly killed: boolean; + /** + * Returns the process identifier (PID) of the child process. If the child process + * fails to spawn due to errors, then the value is `undefined` and `error` is + * emitted. + * + * ```js + * import { spawn } from 'node:child_process'; + * const grep = spawn('grep', ['ssh']); + * + * console.log(`Spawned child pid: ${grep.pid}`); + * grep.stdin.end(); + * ``` + * @since v0.1.90 + */ + readonly pid?: number | undefined; + /** + * The `subprocess.connected` property indicates whether it is still possible to + * send and receive messages from a child process. When `subprocess.connected` is `false`, it is no longer possible to send or receive messages. + * @since v0.7.2 + */ + readonly connected: boolean; + /** + * The `subprocess.exitCode` property indicates the exit code of the child process. + * If the child process is still running, the field will be `null`. + */ + readonly exitCode: number | null; + /** + * The `subprocess.signalCode` property indicates the signal received by + * the child process if any, else `null`. + */ + readonly signalCode: NodeJS.Signals | null; + /** + * The `subprocess.spawnargs` property represents the full list of command-line + * arguments the child process was launched with. + */ + readonly spawnargs: string[]; + /** + * The `subprocess.spawnfile` property indicates the executable file name of + * the child process that is launched. + * + * For {@link fork}, its value will be equal to `process.execPath`. + * For {@link spawn}, its value will be the name of + * the executable file. + * For {@link exec}, its value will be the name of the shell + * in which the child process is launched. + */ + readonly spawnfile: string; + /** + * The `subprocess.kill()` method sends a signal to the child process. If no + * argument is given, the process will be sent the `'SIGTERM'` signal. See [`signal(7)`](http://man7.org/linux/man-pages/man7/signal.7.html) for a list of available signals. This function + * returns `true` if [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) succeeds, and `false` otherwise. + * + * ```js + * import { spawn } from 'node:child_process'; + * const grep = spawn('grep', ['ssh']); + * + * grep.on('close', (code, signal) => { + * console.log( + * `child process terminated due to receipt of signal ${signal}`); + * }); + * + * // Send SIGHUP to process. + * grep.kill('SIGHUP'); + * ``` + * + * The `ChildProcess` object may emit an `'error'` event if the signal + * cannot be delivered. Sending a signal to a child process that has already exited + * is not an error but may have unforeseen consequences. Specifically, if the + * process identifier (PID) has been reassigned to another process, the signal will + * be delivered to that process instead which can have unexpected results. + * + * While the function is called `kill`, the signal delivered to the child process + * may not actually terminate the process. + * + * See [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for reference. + * + * On Windows, where POSIX signals do not exist, the `signal` argument will be + * ignored, and the process will be killed forcefully and abruptly (similar to `'SIGKILL'`). + * See `Signal Events` for more details. + * + * On Linux, child processes of child processes will not be terminated + * when attempting to kill their parent. This is likely to happen when running a + * new process in a shell or with the use of the `shell` option of `ChildProcess`: + * + * ```js + * 'use strict'; + * import { spawn } from 'node:child_process'; + * + * const subprocess = spawn( + * 'sh', + * [ + * '-c', + * `node -e "setInterval(() => { + * console.log(process.pid, 'is alive') + * }, 500);"`, + * ], { + * stdio: ['inherit', 'inherit', 'inherit'], + * }, + * ); + * + * setTimeout(() => { + * subprocess.kill(); // Does not terminate the Node.js process in the shell. + * }, 2000); + * ``` + * @since v0.1.90 + */ + kill(signal?: NodeJS.Signals | number): boolean; + /** + * Calls {@link ChildProcess.kill} with `'SIGTERM'`. + * @since v20.5.0 + */ + [Symbol.dispose](): void; + /** + * When an IPC channel has been established between the parent and child ( + * i.e. when using {@link fork}), the `subprocess.send()` method can + * be used to send messages to the child process. When the child process is a + * Node.js instance, these messages can be received via the `'message'` event. + * + * The message goes through serialization and parsing. The resulting + * message might not be the same as what is originally sent. + * + * For example, in the parent script: + * + * ```js + * import cp from 'node:child_process'; + * const n = cp.fork(`${__dirname}/sub.js`); + * + * n.on('message', (m) => { + * console.log('PARENT got message:', m); + * }); + * + * // Causes the child to print: CHILD got message: { hello: 'world' } + * n.send({ hello: 'world' }); + * ``` + * + * And then the child script, `'sub.js'` might look like this: + * + * ```js + * process.on('message', (m) => { + * console.log('CHILD got message:', m); + * }); + * + * // Causes the parent to print: PARENT got message: { foo: 'bar', baz: null } + * process.send({ foo: 'bar', baz: NaN }); + * ``` + * + * Child Node.js processes will have a `process.send()` method of their own + * that allows the child to send messages back to the parent. + * + * There is a special case when sending a `{cmd: 'NODE_foo'}` message. Messages + * containing a `NODE_` prefix in the `cmd` property are reserved for use within + * Node.js core and will not be emitted in the child's `'message'` event. Rather, such messages are emitted using the `'internalMessage'` event and are consumed internally by Node.js. + * Applications should avoid using such messages or listening for `'internalMessage'` events as it is subject to change without notice. + * + * The optional `sendHandle` argument that may be passed to `subprocess.send()` is + * for passing a TCP server or socket object to the child process. The child will + * receive the object as the second argument passed to the callback function + * registered on the `'message'` event. Any data that is received and buffered in + * the socket will not be sent to the child. Sending IPC sockets is not supported on Windows. + * + * The optional `callback` is a function that is invoked after the message is + * sent but before the child may have received it. The function is called with a + * single argument: `null` on success, or an `Error` object on failure. + * + * If no `callback` function is provided and the message cannot be sent, an `'error'` event will be emitted by the `ChildProcess` object. This can + * happen, for instance, when the child process has already exited. + * + * `subprocess.send()` will return `false` if the channel has closed or when the + * backlog of unsent messages exceeds a threshold that makes it unwise to send + * more. Otherwise, the method returns `true`. The `callback` function can be + * used to implement flow control. + * + * #### Example: sending a server object + * + * The `sendHandle` argument can be used, for instance, to pass the handle of + * a TCP server object to the child process as illustrated in the example below: + * + * ```js + * import { createServer } from 'node:net'; + * import { fork } from 'node:child_process'; + * const subprocess = fork('subprocess.js'); + * + * // Open up the server object and send the handle. + * const server = createServer(); + * server.on('connection', (socket) => { + * socket.end('handled by parent'); + * }); + * server.listen(1337, () => { + * subprocess.send('server', server); + * }); + * ``` + * + * The child would then receive the server object as: + * + * ```js + * process.on('message', (m, server) => { + * if (m === 'server') { + * server.on('connection', (socket) => { + * socket.end('handled by child'); + * }); + * } + * }); + * ``` + * + * Once the server is now shared between the parent and child, some connections + * can be handled by the parent and some by the child. + * + * While the example above uses a server created using the `node:net` module, `node:dgram` module servers use exactly the same workflow with the exceptions of + * listening on a `'message'` event instead of `'connection'` and using `server.bind()` instead of `server.listen()`. This is, however, only + * supported on Unix platforms. + * + * #### Example: sending a socket object + * + * Similarly, the `sendHandler` argument can be used to pass the handle of a + * socket to the child process. The example below spawns two children that each + * handle connections with "normal" or "special" priority: + * + * ```js + * import { createServer } from 'node:net'; + * import { fork } from 'node:child_process'; + * const normal = fork('subprocess.js', ['normal']); + * const special = fork('subprocess.js', ['special']); + * + * // Open up the server and send sockets to child. Use pauseOnConnect to prevent + * // the sockets from being read before they are sent to the child process. + * const server = createServer({ pauseOnConnect: true }); + * server.on('connection', (socket) => { + * + * // If this is special priority... + * if (socket.remoteAddress === '74.125.127.100') { + * special.send('socket', socket); + * return; + * } + * // This is normal priority. + * normal.send('socket', socket); + * }); + * server.listen(1337); + * ``` + * + * The `subprocess.js` would receive the socket handle as the second argument + * passed to the event callback function: + * + * ```js + * process.on('message', (m, socket) => { + * if (m === 'socket') { + * if (socket) { + * // Check that the client socket exists. + * // It is possible for the socket to be closed between the time it is + * // sent and the time it is received in the child process. + * socket.end(`Request handled with ${process.argv[2]} priority`); + * } + * } + * }); + * ``` + * + * Do not use `.maxConnections` on a socket that has been passed to a subprocess. + * The parent cannot track when the socket is destroyed. + * + * Any `'message'` handlers in the subprocess should verify that `socket` exists, + * as the connection may have been closed during the time it takes to send the + * connection to the child. + * @since v0.5.9 + * @param sendHandle `undefined`, or a [`net.Socket`](https://nodejs.org/docs/latest-v25.x/api/net.html#class-netsocket), [`net.Server`](https://nodejs.org/docs/latest-v25.x/api/net.html#class-netserver), or [`dgram.Socket`](https://nodejs.org/docs/latest-v25.x/api/dgram.html#class-dgramsocket) object. + * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties: + */ + send(message: Serializable, callback?: (error: Error | null) => void): boolean; + send(message: Serializable, sendHandle?: SendHandle, callback?: (error: Error | null) => void): boolean; + send( + message: Serializable, + sendHandle?: SendHandle, + options?: MessageOptions, + callback?: (error: Error | null) => void, + ): boolean; + /** + * Closes the IPC channel between parent and child, allowing the child to exit + * gracefully once there are no other connections keeping it alive. After calling + * this method the `subprocess.connected` and `process.connected` properties in + * both the parent and child (respectively) will be set to `false`, and it will be + * no longer possible to pass messages between the processes. + * + * The `'disconnect'` event will be emitted when there are no messages in the + * process of being received. This will most often be triggered immediately after + * calling `subprocess.disconnect()`. + * + * When the child process is a Node.js instance (e.g. spawned using {@link fork}), the `process.disconnect()` method can be invoked + * within the child process to close the IPC channel as well. + * @since v0.7.2 + */ + disconnect(): void; + /** + * By default, the parent will wait for the detached child to exit. To prevent the + * parent from waiting for a given `subprocess` to exit, use the `subprocess.unref()` method. Doing so will cause the parent's event loop to not + * include the child in its reference count, allowing the parent to exit + * independently of the child, unless there is an established IPC channel between + * the child and the parent. + * + * ```js + * import { spawn } from 'node:child_process'; + * + * const subprocess = spawn(process.argv[0], ['child_program.js'], { + * detached: true, + * stdio: 'ignore', + * }); + * + * subprocess.unref(); + * ``` + * @since v0.7.10 + */ + unref(): void; + /** + * Calling `subprocess.ref()` after making a call to `subprocess.unref()` will + * restore the removed reference count for the child process, forcing the parent + * to wait for the child to exit before exiting itself. + * + * ```js + * import { spawn } from 'node:child_process'; + * + * const subprocess = spawn(process.argv[0], ['child_program.js'], { + * detached: true, + * stdio: 'ignore', + * }); + * + * subprocess.unref(); + * subprocess.ref(); + * ``` + * @since v0.7.10 + */ + ref(): void; + } + interface ChildProcess extends InternalEventEmitter {} + // return this object when stdio option is undefined or not specified + interface ChildProcessWithoutNullStreams extends ChildProcess { + stdin: Writable; + stdout: Readable; + stderr: Readable; + readonly stdio: [ + Writable, + Readable, + Readable, + // stderr + Readable | Writable | null | undefined, + // extra, no modification + Readable | Writable | null | undefined, // extra, no modification + ]; + } + // return this object when stdio option is a tuple of 3 + interface ChildProcessByStdio + extends ChildProcess + { + stdin: I; + stdout: O; + stderr: E; + readonly stdio: [ + I, + O, + E, + Readable | Writable | null | undefined, + // extra, no modification + Readable | Writable | null | undefined, // extra, no modification + ]; + } + interface Control extends EventEmitter { + ref(): void; + unref(): void; + } + interface MessageOptions { + keepOpen?: boolean | undefined; + } + type IOType = "overlapped" | "pipe" | "ignore" | "inherit"; + type StdioOptions = IOType | Array; + type SerializationType = "json" | "advanced"; + interface MessagingOptions extends Abortable { + /** + * Specify the kind of serialization used for sending messages between processes. + * @default 'json' + */ + serialization?: SerializationType | undefined; + /** + * The signal value to be used when the spawned process will be killed by the abort signal. + * @default 'SIGTERM' + */ + killSignal?: NodeJS.Signals | number | undefined; + /** + * In milliseconds the maximum amount of time the process is allowed to run. + */ + timeout?: number | undefined; + } + interface ProcessEnvOptions { + uid?: number | undefined; + gid?: number | undefined; + cwd?: string | URL | undefined; + env?: NodeJS.ProcessEnv | undefined; + } + interface CommonOptions extends ProcessEnvOptions { + /** + * @default false + */ + windowsHide?: boolean | undefined; + /** + * @default 0 + */ + timeout?: number | undefined; + } + interface CommonSpawnOptions extends CommonOptions, MessagingOptions, Abortable { + argv0?: string | undefined; + /** + * Can be set to 'pipe', 'inherit', 'overlapped', or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ + stdio?: StdioOptions | undefined; + shell?: boolean | string | undefined; + windowsVerbatimArguments?: boolean | undefined; + } + interface SpawnOptions extends CommonSpawnOptions { + detached?: boolean | undefined; + } + interface SpawnOptionsWithoutStdio extends SpawnOptions { + stdio?: StdioPipeNamed | StdioPipe[] | undefined; + } + type StdioNull = "inherit" | "ignore" | Stream; + type StdioPipeNamed = "pipe" | "overlapped"; + type StdioPipe = undefined | null | StdioPipeNamed; + interface SpawnOptionsWithStdioTuple< + Stdin extends StdioNull | StdioPipe, + Stdout extends StdioNull | StdioPipe, + Stderr extends StdioNull | StdioPipe, + > extends SpawnOptions { + stdio: [Stdin, Stdout, Stderr]; + } + /** + * The `child_process.spawn()` method spawns a new process using the given `command`, with command-line arguments in `args`. If omitted, `args` defaults + * to an empty array. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * + * A third argument may be used to specify additional options, with these defaults: + * + * ```js + * const defaults = { + * cwd: undefined, + * env: process.env, + * }; + * ``` + * + * Use `cwd` to specify the working directory from which the process is spawned. + * If not given, the default is to inherit the current working directory. If given, + * but the path does not exist, the child process emits an `ENOENT` error + * and exits immediately. `ENOENT` is also emitted when the command + * does not exist. + * + * Use `env` to specify environment variables that will be visible to the new + * process, the default is `process.env`. + * + * `undefined` values in `env` will be ignored. + * + * Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the + * exit code: + * + * ```js + * import { spawn } from 'node:child_process'; + * const ls = spawn('ls', ['-lh', '/usr']); + * + * ls.stdout.on('data', (data) => { + * console.log(`stdout: ${data}`); + * }); + * + * ls.stderr.on('data', (data) => { + * console.error(`stderr: ${data}`); + * }); + * + * ls.on('close', (code) => { + * console.log(`child process exited with code ${code}`); + * }); + * ``` + * + * Example: A very elaborate way to run `ps ax | grep ssh` + * + * ```js + * import { spawn } from 'node:child_process'; + * const ps = spawn('ps', ['ax']); + * const grep = spawn('grep', ['ssh']); + * + * ps.stdout.on('data', (data) => { + * grep.stdin.write(data); + * }); + * + * ps.stderr.on('data', (data) => { + * console.error(`ps stderr: ${data}`); + * }); + * + * ps.on('close', (code) => { + * if (code !== 0) { + * console.log(`ps process exited with code ${code}`); + * } + * grep.stdin.end(); + * }); + * + * grep.stdout.on('data', (data) => { + * console.log(data.toString()); + * }); + * + * grep.stderr.on('data', (data) => { + * console.error(`grep stderr: ${data}`); + * }); + * + * grep.on('close', (code) => { + * if (code !== 0) { + * console.log(`grep process exited with code ${code}`); + * } + * }); + * ``` + * + * Example of checking for failed `spawn`: + * + * ```js + * import { spawn } from 'node:child_process'; + * const subprocess = spawn('bad_command'); + * + * subprocess.on('error', (err) => { + * console.error('Failed to start subprocess.'); + * }); + * ``` + * + * Certain platforms (macOS, Linux) will use the value of `argv[0]` for the process + * title while others (Windows, SunOS) will use `command`. + * + * Node.js overwrites `argv[0]` with `process.execPath` on startup, so `process.argv[0]` in a Node.js child process will not match the `argv0` parameter passed to `spawn` from the parent. Retrieve + * it with the `process.argv0` property instead. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * import { spawn } from 'node:child_process'; + * const controller = new AbortController(); + * const { signal } = controller; + * const grep = spawn('grep', ['ssh'], { signal }); + * grep.on('error', (err) => { + * // This will be called with err being an AbortError if the controller aborts + * }); + * controller.abort(); // Stops the child process + * ``` + * @since v0.1.90 + * @param command The command to run. + * @param args List of string arguments. + */ + function spawn(command: string, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptions): ChildProcess; + // overloads of spawn with 'args' + function spawn( + command: string, + args?: readonly string[], + options?: SpawnOptionsWithoutStdio, + ): ChildProcessWithoutNullStreams; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn(command: string, args: readonly string[], options: SpawnOptions): ChildProcess; + interface ExecOptions extends CommonOptions { + shell?: string | undefined; + signal?: AbortSignal | undefined; + maxBuffer?: number | undefined; + killSignal?: NodeJS.Signals | number | undefined; + encoding?: string | null | undefined; + } + interface ExecOptionsWithStringEncoding extends ExecOptions { + encoding?: BufferEncoding | undefined; + } + interface ExecOptionsWithBufferEncoding extends ExecOptions { + encoding: "buffer" | null; // specify `null`. + } + // TODO: Just Plain Wrong™ (see also nodejs/node#57392) + interface ExecException extends Error { + cmd?: string; + killed?: boolean; + code?: number; + signal?: NodeJS.Signals; + stdout?: string; + stderr?: string; + } + /** + * Spawns a shell then executes the `command` within that shell, buffering any + * generated output. The `command` string passed to the exec function is processed + * directly by the shell and special characters (vary based on [shell](https://en.wikipedia.org/wiki/List_of_command-line_interpreters)) + * need to be dealt with accordingly: + * + * ```js + * import { exec } from 'node:child_process'; + * + * exec('"/path/to/test file/test.sh" arg1 arg2'); + * // Double quotes are used so that the space in the path is not interpreted as + * // a delimiter of multiple arguments. + * + * exec('echo "The \\$HOME variable is $HOME"'); + * // The $HOME variable is escaped in the first instance, but not in the second. + * ``` + * + * **Never pass unsanitized user input to this function. Any input containing shell** + * **metacharacters may be used to trigger arbitrary command execution.** + * + * If a `callback` function is provided, it is called with the arguments `(error, stdout, stderr)`. On success, `error` will be `null`. On error, `error` will be an instance of `Error`. The + * `error.code` property will be + * the exit code of the process. By convention, any exit code other than `0` indicates an error. `error.signal` will be the signal that terminated the + * process. + * + * The `stdout` and `stderr` arguments passed to the callback will contain the + * stdout and stderr output of the child process. By default, Node.js will decode + * the output as UTF-8 and pass strings to the callback. The `encoding` option + * can be used to specify the character encoding used to decode the stdout and + * stderr output. If `encoding` is `'buffer'`, or an unrecognized character + * encoding, `Buffer` objects will be passed to the callback instead. + * + * ```js + * import { exec } from 'node:child_process'; + * exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => { + * if (error) { + * console.error(`exec error: ${error}`); + * return; + * } + * console.log(`stdout: ${stdout}`); + * console.error(`stderr: ${stderr}`); + * }); + * ``` + * + * If `timeout` is greater than `0`, the parent will send the signal + * identified by the `killSignal` property (the default is `'SIGTERM'`) if the + * child runs longer than `timeout` milliseconds. + * + * Unlike the [`exec(3)`](http://man7.org/linux/man-pages/man3/exec.3.html) POSIX system call, `child_process.exec()` does not replace + * the existing process and uses a shell to execute the command. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned `ChildProcess` instance is attached to the `Promise` as a `child` property. In + * case of an error (including any error resulting in an exit code other than 0), a + * rejected promise is returned, with the same `error` object given in the + * callback, but with two additional properties `stdout` and `stderr`. + * + * ```js + * import util from 'node:util'; + * import child_process from 'node:child_process'; + * const exec = util.promisify(child_process.exec); + * + * async function lsExample() { + * const { stdout, stderr } = await exec('ls'); + * console.log('stdout:', stdout); + * console.error('stderr:', stderr); + * } + * lsExample(); + * ``` + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * import { exec } from 'node:child_process'; + * const controller = new AbortController(); + * const { signal } = controller; + * const child = exec('grep ssh', { signal }, (error) => { + * console.error(error); // an AbortError + * }); + * controller.abort(); + * ``` + * @since v0.1.90 + * @param command The command to run, with space-separated arguments. + * @param callback called with the output when process terminates. + */ + function exec( + command: string, + callback?: (error: ExecException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function exec( + command: string, + options: ExecOptionsWithBufferEncoding, + callback?: (error: ExecException | null, stdout: NonSharedBuffer, stderr: NonSharedBuffer) => void, + ): ChildProcess; + // `options` with well-known or absent `encoding` means stdout/stderr are definitely `string`. + function exec( + command: string, + options: ExecOptionsWithStringEncoding, + callback?: (error: ExecException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function exec( + command: string, + options: ExecOptions | undefined | null, + callback?: ( + error: ExecException | null, + stdout: string | NonSharedBuffer, + stderr: string | NonSharedBuffer, + ) => void, + ): ChildProcess; + interface PromiseWithChild extends Promise { + child: ChildProcess; + } + namespace exec { + function __promisify__(command: string): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: ExecOptionsWithBufferEncoding, + ): PromiseWithChild<{ + stdout: NonSharedBuffer; + stderr: NonSharedBuffer; + }>; + function __promisify__( + command: string, + options: ExecOptionsWithStringEncoding, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: ExecOptions | undefined | null, + ): PromiseWithChild<{ + stdout: string | NonSharedBuffer; + stderr: string | NonSharedBuffer; + }>; + } + interface ExecFileOptions extends CommonOptions, Abortable { + maxBuffer?: number | undefined; + killSignal?: NodeJS.Signals | number | undefined; + windowsVerbatimArguments?: boolean | undefined; + shell?: boolean | string | undefined; + signal?: AbortSignal | undefined; + encoding?: string | null | undefined; + } + interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { + encoding?: BufferEncoding | undefined; + } + interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { + encoding: "buffer" | null; + } + /** @deprecated Use `ExecFileOptions` instead. */ + interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions {} + // TODO: execFile exceptions can take many forms... this accurately describes none of them + type ExecFileException = + & Omit + & Omit + & { code?: string | number | null }; + /** + * The `child_process.execFile()` function is similar to {@link exec} except that it does not spawn a shell by default. Rather, the specified + * executable `file` is spawned directly as a new process making it slightly more + * efficient than {@link exec}. + * + * The same options as {@link exec} are supported. Since a shell is + * not spawned, behaviors such as I/O redirection and file globbing are not + * supported. + * + * ```js + * import { execFile } from 'node:child_process'; + * const child = execFile('node', ['--version'], (error, stdout, stderr) => { + * if (error) { + * throw error; + * } + * console.log(stdout); + * }); + * ``` + * + * The `stdout` and `stderr` arguments passed to the callback will contain the + * stdout and stderr output of the child process. By default, Node.js will decode + * the output as UTF-8 and pass strings to the callback. The `encoding` option + * can be used to specify the character encoding used to decode the stdout and + * stderr output. If `encoding` is `'buffer'`, or an unrecognized character + * encoding, `Buffer` objects will be passed to the callback instead. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned `ChildProcess` instance is attached to the `Promise` as a `child` property. In + * case of an error (including any error resulting in an exit code other than 0), a + * rejected promise is returned, with the same `error` object given in the + * callback, but with two additional properties `stdout` and `stderr`. + * + * ```js + * import util from 'node:util'; + * import child_process from 'node:child_process'; + * const execFile = util.promisify(child_process.execFile); + * async function getVersion() { + * const { stdout } = await execFile('node', ['--version']); + * console.log(stdout); + * } + * getVersion(); + * ``` + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * import { execFile } from 'node:child_process'; + * const controller = new AbortController(); + * const { signal } = controller; + * const child = execFile('node', ['--version'], { signal }, (error) => { + * console.error(error); // an AbortError + * }); + * controller.abort(); + * ``` + * @since v0.1.91 + * @param file The name or path of the executable file to run. + * @param args List of string arguments. + * @param callback Called with the output when process terminates. + */ + // no `options` definitely means stdout/stderr are `string`. + function execFile( + file: string, + callback?: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + callback?: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function execFile( + file: string, + options: ExecFileOptionsWithBufferEncoding, + callback?: (error: ExecFileException | null, stdout: NonSharedBuffer, stderr: NonSharedBuffer) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithBufferEncoding, + callback?: (error: ExecFileException | null, stdout: NonSharedBuffer, stderr: NonSharedBuffer) => void, + ): ChildProcess; + // `options` with well-known or absent `encoding` means stdout/stderr are definitely `string`. + function execFile( + file: string, + options: ExecFileOptionsWithStringEncoding, + callback?: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithStringEncoding, + callback?: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function execFile( + file: string, + options: ExecFileOptions | undefined | null, + callback: + | (( + error: ExecFileException | null, + stdout: string | NonSharedBuffer, + stderr: string | NonSharedBuffer, + ) => void) + | undefined + | null, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptions | undefined | null, + callback: + | (( + error: ExecFileException | null, + stdout: string | NonSharedBuffer, + stderr: string | NonSharedBuffer, + ) => void) + | undefined + | null, + ): ChildProcess; + namespace execFile { + function __promisify__(file: string): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithBufferEncoding, + ): PromiseWithChild<{ + stdout: NonSharedBuffer; + stderr: NonSharedBuffer; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithBufferEncoding, + ): PromiseWithChild<{ + stdout: NonSharedBuffer; + stderr: NonSharedBuffer; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithStringEncoding, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithStringEncoding, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptions | undefined | null, + ): PromiseWithChild<{ + stdout: string | NonSharedBuffer; + stderr: string | NonSharedBuffer; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptions | undefined | null, + ): PromiseWithChild<{ + stdout: string | NonSharedBuffer; + stderr: string | NonSharedBuffer; + }>; + } + interface ForkOptions extends ProcessEnvOptions, MessagingOptions, Abortable { + execPath?: string | undefined; + execArgv?: string[] | undefined; + silent?: boolean | undefined; + /** + * Can be set to 'pipe', 'inherit', 'overlapped', or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ + stdio?: StdioOptions | undefined; + detached?: boolean | undefined; + windowsVerbatimArguments?: boolean | undefined; + } + /** + * The `child_process.fork()` method is a special case of {@link spawn} used specifically to spawn new Node.js processes. + * Like {@link spawn}, a `ChildProcess` object is returned. The + * returned `ChildProcess` will have an additional communication channel + * built-in that allows messages to be passed back and forth between the parent and + * child. See `subprocess.send()` for details. + * + * Keep in mind that spawned Node.js child processes are + * independent of the parent with exception of the IPC communication channel + * that is established between the two. Each process has its own memory, with + * their own V8 instances. Because of the additional resource allocations + * required, spawning a large number of child Node.js processes is not + * recommended. + * + * By default, `child_process.fork()` will spawn new Node.js instances using the `process.execPath` of the parent process. The `execPath` property in the `options` object allows for an alternative + * execution path to be used. + * + * Node.js processes launched with a custom `execPath` will communicate with the + * parent process using the file descriptor (fd) identified using the + * environment variable `NODE_CHANNEL_FD` on the child process. + * + * Unlike the [`fork(2)`](http://man7.org/linux/man-pages/man2/fork.2.html) POSIX system call, `child_process.fork()` does not clone the + * current process. + * + * The `shell` option available in {@link spawn} is not supported by `child_process.fork()` and will be ignored if set. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * if (process.argv[2] === 'child') { + * setTimeout(() => { + * console.log(`Hello from ${process.argv[2]}!`); + * }, 1_000); + * } else { + * import { fork } from 'node:child_process'; + * const controller = new AbortController(); + * const { signal } = controller; + * const child = fork(__filename, ['child'], { signal }); + * child.on('error', (err) => { + * // This will be called with err being an AbortError if the controller aborts + * }); + * controller.abort(); // Stops the child process + * } + * ``` + * @since v0.5.0 + * @param modulePath The module to run in the child. + * @param args List of string arguments. + */ + function fork(modulePath: string | URL, options?: ForkOptions): ChildProcess; + function fork(modulePath: string | URL, args?: readonly string[], options?: ForkOptions): ChildProcess; + interface SpawnSyncOptions extends CommonSpawnOptions { + input?: string | NodeJS.ArrayBufferView | undefined; + maxBuffer?: number | undefined; + encoding?: BufferEncoding | "buffer" | null | undefined; + } + interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { + encoding: BufferEncoding; + } + interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { + encoding?: "buffer" | null | undefined; + } + interface SpawnSyncReturns { + pid: number; + output: Array; + stdout: T; + stderr: T; + status: number | null; + signal: NodeJS.Signals | null; + error?: Error; + } + /** + * The `child_process.spawnSync()` method is generally identical to {@link spawn} with the exception that the function will not return + * until the child process has fully closed. When a timeout has been encountered + * and `killSignal` is sent, the method won't return until the process has + * completely exited. If the process intercepts and handles the `SIGTERM` signal + * and doesn't exit, the parent process will wait until the child process has + * exited. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * @since v0.11.12 + * @param command The command to run. + * @param args List of string arguments. + */ + function spawnSync(command: string): SpawnSyncReturns; + function spawnSync(command: string, options: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + function spawnSync(command: string, options: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; + function spawnSync(command: string, args: readonly string[]): SpawnSyncReturns; + function spawnSync( + command: string, + args: readonly string[], + options: SpawnSyncOptionsWithStringEncoding, + ): SpawnSyncReturns; + function spawnSync( + command: string, + args: readonly string[], + options: SpawnSyncOptionsWithBufferEncoding, + ): SpawnSyncReturns; + function spawnSync( + command: string, + args?: readonly string[], + options?: SpawnSyncOptions, + ): SpawnSyncReturns; + interface CommonExecOptions extends CommonOptions { + input?: string | NodeJS.ArrayBufferView | undefined; + /** + * Can be set to 'pipe', 'inherit, or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ + stdio?: StdioOptions | undefined; + killSignal?: NodeJS.Signals | number | undefined; + maxBuffer?: number | undefined; + encoding?: BufferEncoding | "buffer" | null | undefined; + } + interface ExecSyncOptions extends CommonExecOptions { + shell?: string | undefined; + } + interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { + encoding: BufferEncoding; + } + interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { + encoding?: "buffer" | null | undefined; + } + /** + * The `child_process.execSync()` method is generally identical to {@link exec} with the exception that the method will not return + * until the child process has fully closed. When a timeout has been encountered + * and `killSignal` is sent, the method won't return until the process has + * completely exited. If the child process intercepts and handles the `SIGTERM` signal and doesn't exit, the parent process will wait until the child process + * has exited. + * + * If the process times out or has a non-zero exit code, this method will throw. + * The `Error` object will contain the entire result from {@link spawnSync}. + * + * **Never pass unsanitized user input to this function. Any input containing shell** + * **metacharacters may be used to trigger arbitrary command execution.** + * @since v0.11.12 + * @param command The command to run. + * @return The stdout from the command. + */ + function execSync(command: string): NonSharedBuffer; + function execSync(command: string, options: ExecSyncOptionsWithStringEncoding): string; + function execSync(command: string, options: ExecSyncOptionsWithBufferEncoding): NonSharedBuffer; + function execSync(command: string, options?: ExecSyncOptions): string | NonSharedBuffer; + interface ExecFileSyncOptions extends CommonExecOptions { + shell?: boolean | string | undefined; + } + interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { + encoding: BufferEncoding; + } + interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { + encoding?: "buffer" | null | undefined; // specify `null`. + } + /** + * The `child_process.execFileSync()` method is generally identical to {@link execFile} with the exception that the method will not + * return until the child process has fully closed. When a timeout has been + * encountered and `killSignal` is sent, the method won't return until the process + * has completely exited. + * + * If the child process intercepts and handles the `SIGTERM` signal and + * does not exit, the parent process will still wait until the child process has + * exited. + * + * If the process times out or has a non-zero exit code, this method will throw an `Error` that will include the full result of the underlying {@link spawnSync}. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * @since v0.11.12 + * @param file The name or path of the executable file to run. + * @param args List of string arguments. + * @return The stdout from the command. + */ + function execFileSync(file: string): NonSharedBuffer; + function execFileSync(file: string, options: ExecFileSyncOptionsWithStringEncoding): string; + function execFileSync(file: string, options: ExecFileSyncOptionsWithBufferEncoding): NonSharedBuffer; + function execFileSync(file: string, options?: ExecFileSyncOptions): string | NonSharedBuffer; + function execFileSync(file: string, args: readonly string[]): NonSharedBuffer; + function execFileSync( + file: string, + args: readonly string[], + options: ExecFileSyncOptionsWithStringEncoding, + ): string; + function execFileSync( + file: string, + args: readonly string[], + options: ExecFileSyncOptionsWithBufferEncoding, + ): NonSharedBuffer; + function execFileSync( + file: string, + args?: readonly string[], + options?: ExecFileSyncOptions, + ): string | NonSharedBuffer; +} +declare module "child_process" { + export * from "node:child_process"; +} diff --git a/backend/node_modules/@types/node/cluster.d.ts b/backend/node_modules/@types/node/cluster.d.ts new file mode 100644 index 0000000..4e5efbf --- /dev/null +++ b/backend/node_modules/@types/node/cluster.d.ts @@ -0,0 +1,486 @@ +/** + * Clusters of Node.js processes can be used to run multiple instances of Node.js + * that can distribute workloads among their application threads. When process isolation + * is not needed, use the [`worker_threads`](https://nodejs.org/docs/latest-v25.x/api/worker_threads.html) + * module instead, which allows running multiple application threads within a single Node.js instance. + * + * The cluster module allows easy creation of child processes that all share + * server ports. + * + * ```js + * import cluster from 'node:cluster'; + * import http from 'node:http'; + * import { availableParallelism } from 'node:os'; + * import process from 'node:process'; + * + * const numCPUs = availableParallelism(); + * + * if (cluster.isPrimary) { + * console.log(`Primary ${process.pid} is running`); + * + * // Fork workers. + * for (let i = 0; i < numCPUs; i++) { + * cluster.fork(); + * } + * + * cluster.on('exit', (worker, code, signal) => { + * console.log(`worker ${worker.process.pid} died`); + * }); + * } else { + * // Workers can share any TCP connection + * // In this case it is an HTTP server + * http.createServer((req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * + * console.log(`Worker ${process.pid} started`); + * } + * ``` + * + * Running Node.js will now share port 8000 between the workers: + * + * ```console + * $ node server.js + * Primary 3596 is running + * Worker 4324 started + * Worker 4520 started + * Worker 6056 started + * Worker 5644 started + * ``` + * + * On Windows, it is not yet possible to set up a named pipe server in a worker. + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/cluster.js) + */ +declare module "node:cluster" { + import * as child_process from "node:child_process"; + import { EventEmitter, InternalEventEmitter } from "node:events"; + class Worker implements EventEmitter { + constructor(options?: cluster.WorkerOptions); + /** + * Each new worker is given its own unique id, this id is stored in the `id`. + * + * While a worker is alive, this is the key that indexes it in `cluster.workers`. + * @since v0.8.0 + */ + id: number; + /** + * All workers are created using [`child_process.fork()`](https://nodejs.org/docs/latest-v25.x/api/child_process.html#child_processforkmodulepath-args-options), the returned object + * from this function is stored as `.process`. In a worker, the global `process` is stored. + * + * See: [Child Process module](https://nodejs.org/docs/latest-v25.x/api/child_process.html#child_processforkmodulepath-args-options). + * + * Workers will call `process.exit(0)` if the `'disconnect'` event occurs + * on `process` and `.exitedAfterDisconnect` is not `true`. This protects against + * accidental disconnection. + * @since v0.7.0 + */ + process: child_process.ChildProcess; + /** + * Send a message to a worker or primary, optionally with a handle. + * + * In the primary, this sends a message to a specific worker. It is identical to [`ChildProcess.send()`](https://nodejs.org/docs/latest-v25.x/api/child_process.html#subprocesssendmessage-sendhandle-options-callback). + * + * In a worker, this sends a message to the primary. It is identical to `process.send()`. + * + * This example will echo back all messages from the primary: + * + * ```js + * if (cluster.isPrimary) { + * const worker = cluster.fork(); + * worker.send('hi there'); + * + * } else if (cluster.isWorker) { + * process.on('message', (msg) => { + * process.send(msg); + * }); + * } + * ``` + * @since v0.7.0 + * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. + */ + send(message: child_process.Serializable, callback?: (error: Error | null) => void): boolean; + send( + message: child_process.Serializable, + sendHandle: child_process.SendHandle, + callback?: (error: Error | null) => void, + ): boolean; + send( + message: child_process.Serializable, + sendHandle: child_process.SendHandle, + options?: child_process.MessageOptions, + callback?: (error: Error | null) => void, + ): boolean; + /** + * This function will kill the worker. In the primary worker, it does this by + * disconnecting the `worker.process`, and once disconnected, killing with `signal`. In the worker, it does it by killing the process with `signal`. + * + * The `kill()` function kills the worker process without waiting for a graceful + * disconnect, it has the same behavior as `worker.process.kill()`. + * + * This method is aliased as `worker.destroy()` for backwards compatibility. + * + * In a worker, `process.kill()` exists, but it is not this function; + * it is [`kill()`](https://nodejs.org/docs/latest-v25.x/api/process.html#processkillpid-signal). + * @since v0.9.12 + * @param [signal='SIGTERM'] Name of the kill signal to send to the worker process. + */ + kill(signal?: string): void; + destroy(signal?: string): void; + /** + * In a worker, this function will close all servers, wait for the `'close'` event + * on those servers, and then disconnect the IPC channel. + * + * In the primary, an internal message is sent to the worker causing it to call `.disconnect()` on itself. + * + * Causes `.exitedAfterDisconnect` to be set. + * + * After a server is closed, it will no longer accept new connections, + * but connections may be accepted by any other listening worker. Existing + * connections will be allowed to close as usual. When no more connections exist, + * see `server.close()`, the IPC channel to the worker will close allowing it + * to die gracefully. + * + * The above applies _only_ to server connections, client connections are not + * automatically closed by workers, and disconnect does not wait for them to close + * before exiting. + * + * In a worker, `process.disconnect` exists, but it is not this function; + * it is `disconnect()`. + * + * Because long living server connections may block workers from disconnecting, it + * may be useful to send a message, so application specific actions may be taken to + * close them. It also may be useful to implement a timeout, killing a worker if + * the `'disconnect'` event has not been emitted after some time. + * + * ```js + * import net from 'node:net'; + * + * if (cluster.isPrimary) { + * const worker = cluster.fork(); + * let timeout; + * + * worker.on('listening', (address) => { + * worker.send('shutdown'); + * worker.disconnect(); + * timeout = setTimeout(() => { + * worker.kill(); + * }, 2000); + * }); + * + * worker.on('disconnect', () => { + * clearTimeout(timeout); + * }); + * + * } else if (cluster.isWorker) { + * const server = net.createServer((socket) => { + * // Connections never end + * }); + * + * server.listen(8000); + * + * process.on('message', (msg) => { + * if (msg === 'shutdown') { + * // Initiate graceful close of any connections to server + * } + * }); + * } + * ``` + * @since v0.7.7 + * @return A reference to `worker`. + */ + disconnect(): this; + /** + * This function returns `true` if the worker is connected to its primary via its + * IPC channel, `false` otherwise. A worker is connected to its primary after it + * has been created. It is disconnected after the `'disconnect'` event is emitted. + * @since v0.11.14 + */ + isConnected(): boolean; + /** + * This function returns `true` if the worker's process has terminated (either + * because of exiting or being signaled). Otherwise, it returns `false`. + * + * ```js + * import cluster from 'node:cluster'; + * import http from 'node:http'; + * import { availableParallelism } from 'node:os'; + * import process from 'node:process'; + * + * const numCPUs = availableParallelism(); + * + * if (cluster.isPrimary) { + * console.log(`Primary ${process.pid} is running`); + * + * // Fork workers. + * for (let i = 0; i < numCPUs; i++) { + * cluster.fork(); + * } + * + * cluster.on('fork', (worker) => { + * console.log('worker is dead:', worker.isDead()); + * }); + * + * cluster.on('exit', (worker, code, signal) => { + * console.log('worker is dead:', worker.isDead()); + * }); + * } else { + * // Workers can share any TCP connection. In this case, it is an HTTP server. + * http.createServer((req, res) => { + * res.writeHead(200); + * res.end(`Current process\n ${process.pid}`); + * process.kill(process.pid); + * }).listen(8000); + * } + * ``` + * @since v0.11.14 + */ + isDead(): boolean; + /** + * This property is `true` if the worker exited due to `.disconnect()`. + * If the worker exited any other way, it is `false`. If the + * worker has not exited, it is `undefined`. + * + * The boolean `worker.exitedAfterDisconnect` allows distinguishing between + * voluntary and accidental exit, the primary may choose not to respawn a worker + * based on this value. + * + * ```js + * cluster.on('exit', (worker, code, signal) => { + * if (worker.exitedAfterDisconnect === true) { + * console.log('Oh, it was just voluntary – no need to worry'); + * } + * }); + * + * // kill worker + * worker.kill(); + * ``` + * @since v6.0.0 + */ + exitedAfterDisconnect: boolean; + } + interface Worker extends InternalEventEmitter {} + type _Worker = Worker; + namespace cluster { + interface Worker extends _Worker {} + interface WorkerOptions { + id?: number | undefined; + process?: child_process.ChildProcess | undefined; + state?: string | undefined; + } + interface WorkerEventMap { + "disconnect": []; + "error": [error: Error]; + "exit": [code: number, signal: string]; + "listening": [address: Address]; + "message": [message: any, handle: child_process.SendHandle]; + "online": []; + } + interface ClusterSettings { + /** + * List of string arguments passed to the Node.js executable. + * @default process.execArgv + */ + execArgv?: string[] | undefined; + /** + * File path to worker file. + * @default process.argv[1] + */ + exec?: string | undefined; + /** + * String arguments passed to worker. + * @default process.argv.slice(2) + */ + args?: readonly string[] | undefined; + /** + * Whether or not to send output to parent's stdio. + * @default false + */ + silent?: boolean | undefined; + /** + * Configures the stdio of forked processes. Because the cluster module relies on IPC to function, this configuration must + * contain an `'ipc'` entry. When this option is provided, it overrides `silent`. See [`child_prcess.spawn()`](https://nodejs.org/docs/latest-v25.x/api/child_process.html#child_processspawncommand-args-options)'s + * [`stdio`](https://nodejs.org/docs/latest-v25.x/api/child_process.html#optionsstdio). + */ + stdio?: any[] | undefined; + /** + * Sets the user identity of the process. (See [`setuid(2)`](https://man7.org/linux/man-pages/man2/setuid.2.html).) + */ + uid?: number | undefined; + /** + * Sets the group identity of the process. (See [`setgid(2)`](https://man7.org/linux/man-pages/man2/setgid.2.html).) + */ + gid?: number | undefined; + /** + * Sets inspector port of worker. This can be a number, or a function that takes no arguments and returns a number. + * By default each worker gets its own port, incremented from the primary's `process.debugPort`. + */ + inspectPort?: number | (() => number) | undefined; + /** + * Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`. + * See [Advanced serialization for `child_process`](https://nodejs.org/docs/latest-v25.x/api/child_process.html#advanced-serialization) for more details. + * @default false + */ + serialization?: "json" | "advanced" | undefined; + /** + * Current working directory of the worker process. + * @default undefined (inherits from parent process) + */ + cwd?: string | undefined; + /** + * Hide the forked processes console window that would normally be created on Windows systems. + * @default false + */ + windowsHide?: boolean | undefined; + } + interface Address { + address: string; + port: number; + /** + * The `addressType` is one of: + * + * * `4` (TCPv4) + * * `6` (TCPv6) + * * `-1` (Unix domain socket) + * * `'udp4'` or `'udp6'` (UDPv4 or UDPv6) + */ + addressType: 4 | 6 | -1 | "udp4" | "udp6"; + } + interface ClusterEventMap { + "disconnect": [worker: Worker]; + "exit": [worker: Worker, code: number, signal: string]; + "fork": [worker: Worker]; + "listening": [worker: Worker, address: Address]; + "message": [worker: Worker, message: any, handle: child_process.SendHandle]; + "online": [worker: Worker]; + "setup": [settings: ClusterSettings]; + } + interface Cluster extends InternalEventEmitter { + /** + * A `Worker` object contains all public information and method about a worker. + * In the primary it can be obtained using `cluster.workers`. In a worker + * it can be obtained using `cluster.worker`. + * @since v0.7.0 + */ + Worker: typeof Worker; + disconnect(callback?: () => void): void; + /** + * Spawn a new worker process. + * + * This can only be called from the primary process. + * @param env Key/value pairs to add to worker process environment. + * @since v0.6.0 + */ + fork(env?: any): Worker; + /** @deprecated since v16.0.0 - use isPrimary. */ + readonly isMaster: boolean; + /** + * True if the process is a primary. This is determined by the `process.env.NODE_UNIQUE_ID`. If `process.env.NODE_UNIQUE_ID` + * is undefined, then `isPrimary` is `true`. + * @since v16.0.0 + */ + readonly isPrimary: boolean; + /** + * True if the process is not a primary (it is the negation of `cluster.isPrimary`). + * @since v0.6.0 + */ + readonly isWorker: boolean; + /** + * The scheduling policy, either `cluster.SCHED_RR` for round-robin or `cluster.SCHED_NONE` to leave it to the operating system. This is a + * global setting and effectively frozen once either the first worker is spawned, or [`.setupPrimary()`](https://nodejs.org/docs/latest-v25.x/api/cluster.html#clustersetupprimarysettings) + * is called, whichever comes first. + * + * `SCHED_RR` is the default on all operating systems except Windows. Windows will change to `SCHED_RR` once libuv is able to effectively distribute + * IOCP handles without incurring a large performance hit. + * + * `cluster.schedulingPolicy` can also be set through the `NODE_CLUSTER_SCHED_POLICY` environment variable. Valid values are `'rr'` and `'none'`. + * @since v0.11.2 + */ + schedulingPolicy: number; + /** + * After calling [`.setupPrimary()`](https://nodejs.org/docs/latest-v25.x/api/cluster.html#clustersetupprimarysettings) + * (or [`.fork()`](https://nodejs.org/docs/latest-v25.x/api/cluster.html#clusterforkenv)) this settings object will contain + * the settings, including the default values. + * + * This object is not intended to be changed or set manually. + * @since v0.7.1 + */ + readonly settings: ClusterSettings; + /** @deprecated since v16.0.0 - use [`.setupPrimary()`](https://nodejs.org/docs/latest-v25.x/api/cluster.html#clustersetupprimarysettings) instead. */ + setupMaster(settings?: ClusterSettings): void; + /** + * `setupPrimary` is used to change the default 'fork' behavior. Once called, the settings will be present in `cluster.settings`. + * + * Any settings changes only affect future calls to [`.fork()`](https://nodejs.org/docs/latest-v25.x/api/cluster.html#clusterforkenv) + * and have no effect on workers that are already running. + * + * The only attribute of a worker that cannot be set via `.setupPrimary()` is the `env` passed to + * [`.fork()`](https://nodejs.org/docs/latest-v25.x/api/cluster.html#clusterforkenv). + * + * The defaults above apply to the first call only; the defaults for later calls are the current values at the time of + * `cluster.setupPrimary()` is called. + * + * ```js + * import cluster from 'node:cluster'; + * + * cluster.setupPrimary({ + * exec: 'worker.js', + * args: ['--use', 'https'], + * silent: true, + * }); + * cluster.fork(); // https worker + * cluster.setupPrimary({ + * exec: 'worker.js', + * args: ['--use', 'http'], + * }); + * cluster.fork(); // http worker + * ``` + * + * This can only be called from the primary process. + * @since v16.0.0 + */ + setupPrimary(settings?: ClusterSettings): void; + /** + * A reference to the current worker object. Not available in the primary process. + * + * ```js + * import cluster from 'node:cluster'; + * + * if (cluster.isPrimary) { + * console.log('I am primary'); + * cluster.fork(); + * cluster.fork(); + * } else if (cluster.isWorker) { + * console.log(`I am worker #${cluster.worker.id}`); + * } + * ``` + * @since v0.7.0 + */ + readonly worker?: Worker; + /** + * A hash that stores the active worker objects, keyed by `id` field. This makes it easy to loop through all the workers. It is only available in the primary process. + * + * A worker is removed from `cluster.workers` after the worker has disconnected _and_ exited. The order between these two events cannot be determined in advance. However, it + * is guaranteed that the removal from the `cluster.workers` list happens before the last `'disconnect'` or `'exit'` event is emitted. + * + * ```js + * import cluster from 'node:cluster'; + * + * for (const worker of Object.values(cluster.workers)) { + * worker.send('big announcement to all workers'); + * } + * ``` + * @since v0.7.0 + */ + readonly workers?: NodeJS.Dict; + readonly SCHED_NONE: number; + readonly SCHED_RR: number; + } + } + var cluster: cluster.Cluster; + export = cluster; +} +declare module "cluster" { + import cluster = require("node:cluster"); + export = cluster; +} diff --git a/backend/node_modules/@types/node/compatibility/iterators.d.ts b/backend/node_modules/@types/node/compatibility/iterators.d.ts new file mode 100644 index 0000000..156e785 --- /dev/null +++ b/backend/node_modules/@types/node/compatibility/iterators.d.ts @@ -0,0 +1,21 @@ +// Backwards-compatible iterator interfaces, augmented with iterator helper methods by lib.esnext.iterator in TypeScript 5.6. +// The IterableIterator interface does not contain these methods, which creates assignability issues in places where IteratorObjects +// are expected (eg. DOM-compatible APIs) if lib.esnext.iterator is loaded. +// Also ensures that iterators returned by the Node API, which inherit from Iterator.prototype, correctly expose the iterator helper methods +// if lib.esnext.iterator is loaded. +// TODO: remove once this package no longer supports TS 5.5, and replace NodeJS.BuiltinIteratorReturn with BuiltinIteratorReturn. + +// Placeholders for TS <5.6 +interface IteratorObject {} +interface AsyncIteratorObject {} + +declare namespace NodeJS { + // Populate iterator methods for TS <5.6 + interface Iterator extends globalThis.Iterator {} + interface AsyncIterator extends globalThis.AsyncIterator {} + + // Polyfill for TS 5.6's instrinsic BuiltinIteratorReturn type, required for DOM-compatible iterators + type BuiltinIteratorReturn = ReturnType extends + globalThis.Iterator ? TReturn + : any; +} diff --git a/backend/node_modules/@types/node/console.d.ts b/backend/node_modules/@types/node/console.d.ts new file mode 100644 index 0000000..3943442 --- /dev/null +++ b/backend/node_modules/@types/node/console.d.ts @@ -0,0 +1,151 @@ +/** + * The `node:console` module provides a simple debugging console that is similar to + * the JavaScript console mechanism provided by web browsers. + * + * The module exports two specific components: + * + * * A `Console` class with methods such as `console.log()`, `console.error()`, and `console.warn()` that can be used to write to any Node.js stream. + * * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v25.x/api/process.html#processstdout) and + * [`process.stderr`](https://nodejs.org/docs/latest-v25.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. + * + * _**Warning**_: The global console object's methods are neither consistently + * synchronous like the browser APIs they resemble, nor are they consistently + * asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v25.x/api/process.html#a-note-on-process-io) for + * more information. + * + * Example using the global `console`: + * + * ```js + * console.log('hello world'); + * // Prints: hello world, to stdout + * console.log('hello %s', 'world'); + * // Prints: hello world, to stdout + * console.error(new Error('Whoops, something bad happened')); + * // Prints error message and stack trace to stderr: + * // Error: Whoops, something bad happened + * // at [eval]:5:15 + * // at Script.runInThisContext (node:vm:132:18) + * // at Object.runInThisContext (node:vm:309:38) + * // at node:internal/process/execution:77:19 + * // at [eval]-wrapper:6:22 + * // at evalScript (node:internal/process/execution:76:60) + * // at node:internal/main/eval_string:23:3 + * + * const name = 'Will Robinson'; + * console.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to stderr + * ``` + * + * Example using the `Console` class: + * + * ```js + * const out = getStreamSomehow(); + * const err = getStreamSomehow(); + * const myConsole = new console.Console(out, err); + * + * myConsole.log('hello world'); + * // Prints: hello world, to out + * myConsole.log('hello %s', 'world'); + * // Prints: hello world, to out + * myConsole.error(new Error('Whoops, something bad happened')); + * // Prints: [Error: Whoops, something bad happened], to err + * + * const name = 'Will Robinson'; + * myConsole.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to err + * ``` + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/console.js) + */ +declare module "node:console" { + import { InspectOptions } from "node:util"; + namespace console { + interface ConsoleOptions { + stdout: NodeJS.WritableStream; + stderr?: NodeJS.WritableStream | undefined; + /** + * Ignore errors when writing to the underlying streams. + * @default true + */ + ignoreErrors?: boolean | undefined; + /** + * Set color support for this `Console` instance. Setting to true enables coloring while inspecting + * values. Setting to `false` disables coloring while inspecting values. Setting to `'auto'` makes color + * support depend on the value of the `isTTY` property and the value returned by `getColorDepth()` on the + * respective stream. This option can not be used, if `inspectOptions.colors` is set as well. + * @default 'auto' + */ + colorMode?: boolean | "auto" | undefined; + /** + * Specifies options that are passed along to + * [`util.inspect()`](https://nodejs.org/docs/latest-v25.x/api/util.html#utilinspectobject-options). + */ + inspectOptions?: InspectOptions | ReadonlyMap | undefined; + /** + * Set group indentation. + * @default 2 + */ + groupIndentation?: number | undefined; + } + interface Console { + readonly Console: { + prototype: Console; + new(stdout: NodeJS.WritableStream, stderr?: NodeJS.WritableStream, ignoreErrors?: boolean): Console; + new(options: ConsoleOptions): Console; + }; + assert(condition?: unknown, ...data: any[]): void; + clear(): void; + count(label?: string): void; + countReset(label?: string): void; + debug(...data: any[]): void; + dir(item?: any, options?: InspectOptions): void; + dirxml(...data: any[]): void; + error(...data: any[]): void; + group(...data: any[]): void; + groupCollapsed(...data: any[]): void; + groupEnd(): void; + info(...data: any[]): void; + log(...data: any[]): void; + table(tabularData?: any, properties?: string[]): void; + time(label?: string): void; + timeEnd(label?: string): void; + timeLog(label?: string, ...data: any[]): void; + trace(...data: any[]): void; + warn(...data: any[]): void; + /** + * This method does not display anything unless used in the inspector. The `console.profile()` + * method starts a JavaScript CPU profile with an optional label until {@link profileEnd} + * is called. The profile is then added to the Profile panel of the inspector. + * + * ```js + * console.profile('MyLabel'); + * // Some code + * console.profileEnd('MyLabel'); + * // Adds the profile 'MyLabel' to the Profiles panel of the inspector. + * ``` + * @since v8.0.0 + */ + profile(label?: string): void; + /** + * This method does not display anything unless used in the inspector. Stops the current + * JavaScript CPU profiling session if one has been started and prints the report to the + * Profiles panel of the inspector. See {@link profile} for an example. + * + * If this method is called without a label, the most recently started profile is stopped. + * @since v8.0.0 + */ + profileEnd(label?: string): void; + /** + * This method does not display anything unless used in the inspector. The `console.timeStamp()` + * method adds an event with the label `'label'` to the Timeline panel of the inspector. + * @since v8.0.0 + */ + timeStamp(label?: string): void; + } + } + var console: console.Console; + export = console; +} +declare module "console" { + import console = require("node:console"); + export = console; +} diff --git a/backend/node_modules/@types/node/constants.d.ts b/backend/node_modules/@types/node/constants.d.ts new file mode 100644 index 0000000..c24ad98 --- /dev/null +++ b/backend/node_modules/@types/node/constants.d.ts @@ -0,0 +1,20 @@ +/** + * @deprecated The `node:constants` module is deprecated. When requiring access to constants + * relevant to specific Node.js builtin modules, developers should instead refer + * to the `constants` property exposed by the relevant module. For instance, + * `require('node:fs').constants` and `require('node:os').constants`. + */ +declare module "node:constants" { + const constants: + & typeof import("node:os").constants.dlopen + & typeof import("node:os").constants.errno + & typeof import("node:os").constants.priority + & typeof import("node:os").constants.signals + & typeof import("node:fs").constants + & typeof import("node:crypto").constants; + export = constants; +} +declare module "constants" { + import constants = require("node:constants"); + export = constants; +} diff --git a/backend/node_modules/@types/node/crypto.d.ts b/backend/node_modules/@types/node/crypto.d.ts new file mode 100644 index 0000000..0ae42e4 --- /dev/null +++ b/backend/node_modules/@types/node/crypto.d.ts @@ -0,0 +1,4065 @@ +/** + * The `node:crypto` module provides cryptographic functionality that includes a + * set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify + * functions. + * + * ```js + * const { createHmac } = await import('node:crypto'); + * + * const secret = 'abcdefg'; + * const hash = createHmac('sha256', secret) + * .update('I love cupcakes') + * .digest('hex'); + * console.log(hash); + * // Prints: + * // c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e + * ``` + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/crypto.js) + */ +declare module "node:crypto" { + import { NonSharedBuffer } from "node:buffer"; + import * as stream from "node:stream"; + import { PeerCertificate } from "node:tls"; + /** + * SPKAC is a Certificate Signing Request mechanism originally implemented by + * Netscape and was specified formally as part of HTML5's `keygen` element. + * + * `` is deprecated since [HTML 5.2](https://www.w3.org/TR/html52/changes.html#features-removed) and new projects + * should not use this element anymore. + * + * The `node:crypto` module provides the `Certificate` class for working with SPKAC + * data. The most common usage is handling output generated by the HTML5 `` element. Node.js uses [OpenSSL's SPKAC + * implementation](https://www.openssl.org/docs/man3.0/man1/openssl-spkac.html) internally. + * @since v0.11.8 + */ + class Certificate { + /** + * ```js + * const { Certificate } = await import('node:crypto'); + * const spkac = getSpkacSomehow(); + * const challenge = Certificate.exportChallenge(spkac); + * console.log(challenge.toString('utf8')); + * // Prints: the challenge as a UTF8 string + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return The challenge component of the `spkac` data structure, which includes a public key and a challenge. + */ + static exportChallenge(spkac: BinaryLike): NonSharedBuffer; + /** + * ```js + * const { Certificate } = await import('node:crypto'); + * const spkac = getSpkacSomehow(); + * const publicKey = Certificate.exportPublicKey(spkac); + * console.log(publicKey); + * // Prints: the public key as + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return The public key component of the `spkac` data structure, which includes a public key and a challenge. + */ + static exportPublicKey(spkac: BinaryLike, encoding?: string): NonSharedBuffer; + /** + * ```js + * import { Buffer } from 'node:buffer'; + * const { Certificate } = await import('node:crypto'); + * + * const spkac = getSpkacSomehow(); + * console.log(Certificate.verifySpkac(Buffer.from(spkac))); + * // Prints: true or false + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return `true` if the given `spkac` data structure is valid, `false` otherwise. + */ + static verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; + /** + * @deprecated + * @param spkac + * @returns The challenge component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportChallenge(spkac: BinaryLike): NonSharedBuffer; + /** + * @deprecated + * @param spkac + * @param encoding The encoding of the spkac string. + * @returns The public key component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportPublicKey(spkac: BinaryLike, encoding?: string): NonSharedBuffer; + /** + * @deprecated + * @param spkac + * @returns `true` if the given `spkac` data structure is valid, + * `false` otherwise. + */ + verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; + } + namespace constants { + // https://nodejs.org/dist/latest-v25.x/docs/api/crypto.html#crypto-constants + const OPENSSL_VERSION_NUMBER: number; + /** Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for detail. */ + const SSL_OP_ALL: number; + /** Instructs OpenSSL to allow a non-[EC]DHE-based key exchange mode for TLS v1.3 */ + const SSL_OP_ALLOW_NO_DHE_KEX: number; + /** Allows legacy insecure renegotiation between OpenSSL and unpatched clients or servers. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; + /** Attempts to use the server's preferences instead of the client's when selecting a cipher. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_CIPHER_SERVER_PREFERENCE: number; + /** Instructs OpenSSL to use Cisco's version identifier of DTLS_BAD_VER. */ + const SSL_OP_CISCO_ANYCONNECT: number; + /** Instructs OpenSSL to turn on cookie exchange. */ + const SSL_OP_COOKIE_EXCHANGE: number; + /** Instructs OpenSSL to add server-hello extension from an early version of the cryptopro draft. */ + const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; + /** Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d. */ + const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; + /** Allows initial connection to servers that do not support RI. */ + const SSL_OP_LEGACY_SERVER_CONNECT: number; + /** Instructs OpenSSL to disable support for SSL/TLS compression. */ + const SSL_OP_NO_COMPRESSION: number; + /** Instructs OpenSSL to disable encrypt-then-MAC. */ + const SSL_OP_NO_ENCRYPT_THEN_MAC: number; + const SSL_OP_NO_QUERY_MTU: number; + /** Instructs OpenSSL to disable renegotiation. */ + const SSL_OP_NO_RENEGOTIATION: number; + /** Instructs OpenSSL to always start a new session when performing renegotiation. */ + const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + /** Instructs OpenSSL to turn off SSL v2 */ + const SSL_OP_NO_SSLv2: number; + /** Instructs OpenSSL to turn off SSL v3 */ + const SSL_OP_NO_SSLv3: number; + /** Instructs OpenSSL to disable use of RFC4507bis tickets. */ + const SSL_OP_NO_TICKET: number; + /** Instructs OpenSSL to turn off TLS v1 */ + const SSL_OP_NO_TLSv1: number; + /** Instructs OpenSSL to turn off TLS v1.1 */ + const SSL_OP_NO_TLSv1_1: number; + /** Instructs OpenSSL to turn off TLS v1.2 */ + const SSL_OP_NO_TLSv1_2: number; + /** Instructs OpenSSL to turn off TLS v1.3 */ + const SSL_OP_NO_TLSv1_3: number; + /** Instructs OpenSSL server to prioritize ChaCha20-Poly1305 when the client does. This option has no effect if `SSL_OP_CIPHER_SERVER_PREFERENCE` is not enabled. */ + const SSL_OP_PRIORITIZE_CHACHA: number; + /** Instructs OpenSSL to disable version rollback attack detection. */ + const SSL_OP_TLS_ROLLBACK_BUG: number; + const ENGINE_METHOD_RSA: number; + const ENGINE_METHOD_DSA: number; + const ENGINE_METHOD_DH: number; + const ENGINE_METHOD_RAND: number; + const ENGINE_METHOD_EC: number; + const ENGINE_METHOD_CIPHERS: number; + const ENGINE_METHOD_DIGESTS: number; + const ENGINE_METHOD_PKEY_METHS: number; + const ENGINE_METHOD_PKEY_ASN1_METHS: number; + const ENGINE_METHOD_ALL: number; + const ENGINE_METHOD_NONE: number; + const DH_CHECK_P_NOT_SAFE_PRIME: number; + const DH_CHECK_P_NOT_PRIME: number; + const DH_UNABLE_TO_CHECK_GENERATOR: number; + const DH_NOT_SUITABLE_GENERATOR: number; + const RSA_PKCS1_PADDING: number; + const RSA_SSLV23_PADDING: number; + const RSA_NO_PADDING: number; + const RSA_PKCS1_OAEP_PADDING: number; + const RSA_X931_PADDING: number; + const RSA_PKCS1_PSS_PADDING: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the digest size when signing or verifying. */ + const RSA_PSS_SALTLEN_DIGEST: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the maximum permissible value when signing data. */ + const RSA_PSS_SALTLEN_MAX_SIGN: number; + /** Causes the salt length for RSA_PKCS1_PSS_PADDING to be determined automatically when verifying a signature. */ + const RSA_PSS_SALTLEN_AUTO: number; + const POINT_CONVERSION_COMPRESSED: number; + const POINT_CONVERSION_UNCOMPRESSED: number; + const POINT_CONVERSION_HYBRID: number; + /** Specifies the built-in default cipher list used by Node.js (colon-separated values). */ + const defaultCoreCipherList: string; + /** Specifies the active default cipher list used by the current Node.js process (colon-separated values). */ + const defaultCipherList: string; + } + interface HashOptions extends stream.TransformOptions { + /** + * For XOF hash functions such as `shake256`, the + * outputLength option can be used to specify the desired output length in bytes. + */ + outputLength?: number | undefined; + } + /** @deprecated since v10.0.0 */ + const fips: boolean; + /** + * Creates and returns a `Hash` object that can be used to generate hash digests + * using the given `algorithm`. Optional `options` argument controls stream + * behavior. For XOF hash functions such as `'shake256'`, the `outputLength` option + * can be used to specify the desired output length in bytes. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms` will + * display the available digest algorithms. + * + * Example: generating the sha256 sum of a file + * + * ```js + * import { + * createReadStream, + * } from 'node:fs'; + * import { argv } from 'node:process'; + * const { + * createHash, + * } = await import('node:crypto'); + * + * const filename = argv[2]; + * + * const hash = createHash('sha256'); + * + * const input = createReadStream(filename); + * input.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = input.read(); + * if (data) + * hash.update(data); + * else { + * console.log(`${hash.digest('hex')} ${filename}`); + * } + * }); + * ``` + * @since v0.1.92 + * @param options `stream.transform` options + */ + function createHash(algorithm: string, options?: HashOptions): Hash; + /** + * Creates and returns an `Hmac` object that uses the given `algorithm` and `key`. + * Optional `options` argument controls stream behavior. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms` will + * display the available digest algorithms. + * + * The `key` is the HMAC key used to generate the cryptographic HMAC hash. If it is + * a `KeyObject`, its type must be `secret`. If it is a string, please consider `caveats when using strings as inputs to cryptographic APIs`. If it was + * obtained from a cryptographically secure source of entropy, such as {@link randomBytes} or {@link generateKey}, its length should not + * exceed the block size of `algorithm` (e.g., 512 bits for SHA-256). + * + * Example: generating the sha256 HMAC of a file + * + * ```js + * import { + * createReadStream, + * } from 'node:fs'; + * import { argv } from 'node:process'; + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const filename = argv[2]; + * + * const hmac = createHmac('sha256', 'a secret'); + * + * const input = createReadStream(filename); + * input.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = input.read(); + * if (data) + * hmac.update(data); + * else { + * console.log(`${hmac.digest('hex')} ${filename}`); + * } + * }); + * ``` + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createHmac(algorithm: string, key: BinaryLike | KeyObject, options?: stream.TransformOptions): Hmac; + // https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings + type BinaryToTextEncoding = "base64" | "base64url" | "hex" | "binary"; + type CharacterEncoding = "utf8" | "utf-8" | "utf16le" | "utf-16le" | "latin1"; + type LegacyCharacterEncoding = "ascii" | "binary" | "ucs2" | "ucs-2"; + type Encoding = BinaryToTextEncoding | CharacterEncoding | LegacyCharacterEncoding; + type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid"; + /** + * The `Hash` class is a utility for creating hash digests of data. It can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where data is written + * to produce a computed hash digest on the readable side, or + * * Using the `hash.update()` and `hash.digest()` methods to produce the + * computed hash. + * + * The {@link createHash} method is used to create `Hash` instances. `Hash`objects are not to be created directly using the `new` keyword. + * + * Example: Using `Hash` objects as streams: + * + * ```js + * const { + * createHash, + * } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * hash.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = hash.read(); + * if (data) { + * console.log(data.toString('hex')); + * // Prints: + * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 + * } + * }); + * + * hash.write('some data to hash'); + * hash.end(); + * ``` + * + * Example: Using `Hash` and piped streams: + * + * ```js + * import { createReadStream } from 'node:fs'; + * import { stdout } from 'node:process'; + * const { createHash } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * const input = createReadStream('test.js'); + * input.pipe(hash).setEncoding('hex').pipe(stdout); + * ``` + * + * Example: Using the `hash.update()` and `hash.digest()` methods: + * + * ```js + * const { + * createHash, + * } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * hash.update('some data to hash'); + * console.log(hash.digest('hex')); + * // Prints: + * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 + * ``` + * @since v0.1.92 + */ + class Hash extends stream.Transform { + private constructor(); + /** + * Creates a new `Hash` object that contains a deep copy of the internal state + * of the current `Hash` object. + * + * The optional `options` argument controls stream behavior. For XOF hash + * functions such as `'shake256'`, the `outputLength` option can be used to + * specify the desired output length in bytes. + * + * An error is thrown when an attempt is made to copy the `Hash` object after + * its `hash.digest()` method has been called. + * + * ```js + * // Calculate a rolling hash. + * const { + * createHash, + * } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * hash.update('one'); + * console.log(hash.copy().digest('hex')); + * + * hash.update('two'); + * console.log(hash.copy().digest('hex')); + * + * hash.update('three'); + * console.log(hash.copy().digest('hex')); + * + * // Etc. + * ``` + * @since v13.1.0 + * @param options `stream.transform` options + */ + copy(options?: HashOptions): Hash; + /** + * Updates the hash content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Hash; + update(data: string, inputEncoding: Encoding): Hash; + /** + * Calculates the digest of all of the data passed to be hashed (using the `hash.update()` method). + * If `encoding` is provided a string will be returned; otherwise + * a `Buffer` is returned. + * + * The `Hash` object can not be used again after `hash.digest()` method has been + * called. Multiple calls will cause an error to be thrown. + * @since v0.1.92 + * @param encoding The `encoding` of the return value. + */ + digest(): NonSharedBuffer; + digest(encoding: BinaryToTextEncoding): string; + } + /** + * The `Hmac` class is a utility for creating cryptographic HMAC digests. It can + * be used in one of two ways: + * + * * As a `stream` that is both readable and writable, where data is written + * to produce a computed HMAC digest on the readable side, or + * * Using the `hmac.update()` and `hmac.digest()` methods to produce the + * computed HMAC digest. + * + * The {@link createHmac} method is used to create `Hmac` instances. `Hmac`objects are not to be created directly using the `new` keyword. + * + * Example: Using `Hmac` objects as streams: + * + * ```js + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = hmac.read(); + * if (data) { + * console.log(data.toString('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * } + * }); + * + * hmac.write('some data to hash'); + * hmac.end(); + * ``` + * + * Example: Using `Hmac` and piped streams: + * + * ```js + * import { createReadStream } from 'node:fs'; + * import { stdout } from 'node:process'; + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * const input = createReadStream('test.js'); + * input.pipe(hmac).pipe(stdout); + * ``` + * + * Example: Using the `hmac.update()` and `hmac.digest()` methods: + * + * ```js + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.update('some data to hash'); + * console.log(hmac.digest('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * ``` + * @since v0.1.94 + */ + class Hmac extends stream.Transform { + private constructor(); + /** + * Updates the `Hmac` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Hmac; + update(data: string, inputEncoding: Encoding): Hmac; + /** + * Calculates the HMAC digest of all of the data passed using `hmac.update()`. + * If `encoding` is + * provided a string is returned; otherwise a `Buffer` is returned; + * + * The `Hmac` object can not be used again after `hmac.digest()` has been + * called. Multiple calls to `hmac.digest()` will result in an error being thrown. + * @since v0.1.94 + * @param encoding The `encoding` of the return value. + */ + digest(): NonSharedBuffer; + digest(encoding: BinaryToTextEncoding): string; + } + type KeyFormat = "pem" | "der" | "jwk"; + type KeyObjectType = "secret" | "public" | "private"; + type PublicKeyExportType = "pkcs1" | "spki"; + type PrivateKeyExportType = "pkcs1" | "pkcs8" | "sec1"; + type KeyExportOptions = + | SymmetricKeyExportOptions + | PublicKeyExportOptions + | PrivateKeyExportOptions + | JwkKeyExportOptions; + interface SymmetricKeyExportOptions { + format?: "buffer" | undefined; + } + interface PublicKeyExportOptions { + type: T; + format: Exclude; + } + interface PrivateKeyExportOptions { + type: T; + format: Exclude; + cipher?: string | undefined; + passphrase?: string | Buffer | undefined; + } + interface JwkKeyExportOptions { + format: "jwk"; + } + interface KeyPairExportOptions< + TPublic extends PublicKeyExportType = PublicKeyExportType, + TPrivate extends PrivateKeyExportType = PrivateKeyExportType, + > { + publicKeyEncoding?: PublicKeyExportOptions | JwkKeyExportOptions | undefined; + privateKeyEncoding?: PrivateKeyExportOptions | JwkKeyExportOptions | undefined; + } + type KeyExportResult = T extends { format: infer F extends KeyFormat } + ? { der: NonSharedBuffer; jwk: webcrypto.JsonWebKey; pem: string }[F] + : Default; + interface KeyPairExportResult { + publicKey: KeyExportResult; + privateKey: KeyExportResult; + } + type KeyPairExportCallback = ( + err: Error | null, + publicKey: KeyExportResult, + privateKey: KeyExportResult, + ) => void; + type MLDSAKeyType = `ml-dsa-${44 | 65 | 87}`; + type MLKEMKeyType = `ml-kem-${1024 | 512 | 768}`; + type SLHDSAKeyType = `slh-dsa-${"sha2" | "shake"}-${128 | 192 | 256}${"f" | "s"}`; + type AsymmetricKeyType = + | "dh" + | "dsa" + | "ec" + | "ed25519" + | "ed448" + | MLDSAKeyType + | MLKEMKeyType + | "rsa-pss" + | "rsa" + | SLHDSAKeyType + | "x25519" + | "x448"; + interface AsymmetricKeyDetails { + /** + * Key size in bits (RSA, DSA). + */ + modulusLength?: number; + /** + * Public exponent (RSA). + */ + publicExponent?: bigint; + /** + * Name of the message digest (RSA-PSS). + */ + hashAlgorithm?: string; + /** + * Name of the message digest used by MGF1 (RSA-PSS). + */ + mgf1HashAlgorithm?: string; + /** + * Minimal salt length in bytes (RSA-PSS). + */ + saltLength?: number; + /** + * Size of q in bits (DSA). + */ + divisorLength?: number; + /** + * Name of the curve (EC). + */ + namedCurve?: string; + } + /** + * Node.js uses a `KeyObject` class to represent a symmetric or asymmetric key, + * and each kind of key exposes different functions. The {@link createSecretKey}, {@link createPublicKey} and {@link createPrivateKey} methods are used to create `KeyObject`instances. `KeyObject` + * objects are not to be created directly using the `new`keyword. + * + * Most applications should consider using the new `KeyObject` API instead of + * passing keys as strings or `Buffer`s due to improved security features. + * + * `KeyObject` instances can be passed to other threads via `postMessage()`. + * The receiver obtains a cloned `KeyObject`, and the `KeyObject` does not need to + * be listed in the `transferList` argument. + * @since v11.6.0 + */ + class KeyObject { + private constructor(); + /** + * Example: Converting a `CryptoKey` instance to a `KeyObject`: + * + * ```js + * const { KeyObject } = await import('node:crypto'); + * const { subtle } = globalThis.crypto; + * + * const key = await subtle.generateKey({ + * name: 'HMAC', + * hash: 'SHA-256', + * length: 256, + * }, true, ['sign', 'verify']); + * + * const keyObject = KeyObject.from(key); + * console.log(keyObject.symmetricKeySize); + * // Prints: 32 (symmetric key size in bytes) + * ``` + * @since v15.0.0 + */ + static from(key: webcrypto.CryptoKey): KeyObject; + /** + * For asymmetric keys, this property represents the type of the key. See the + * supported [asymmetric key types](https://nodejs.org/docs/latest-v25.x/api/crypto.html#asymmetric-key-types). + * + * This property is `undefined` for unrecognized `KeyObject` types and symmetric + * keys. + * @since v11.6.0 + */ + asymmetricKeyType?: AsymmetricKeyType; + /** + * This property exists only on asymmetric keys. Depending on the type of the key, + * this object contains information about the key. None of the information obtained + * through this property can be used to uniquely identify a key or to compromise + * the security of the key. + * + * For RSA-PSS keys, if the key material contains a `RSASSA-PSS-params` sequence, + * the `hashAlgorithm`, `mgf1HashAlgorithm`, and `saltLength` properties will be + * set. + * + * Other key details might be exposed via this API using additional attributes. + * @since v15.7.0 + */ + asymmetricKeyDetails?: AsymmetricKeyDetails; + /** + * For symmetric keys, the following encoding options can be used: + * + * For public keys, the following encoding options can be used: + * + * For private keys, the following encoding options can be used: + * + * The result type depends on the selected encoding format, when PEM the + * result is a string, when DER it will be a buffer containing the data + * encoded as DER, when [JWK](https://tools.ietf.org/html/rfc7517) it will be an object. + * + * When [JWK](https://tools.ietf.org/html/rfc7517) encoding format was selected, all other encoding options are + * ignored. + * + * PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of + * the `cipher` and `format` options. The PKCS#8 `type` can be used with any`format` to encrypt any key algorithm (RSA, EC, or DH) by specifying a`cipher`. PKCS#1 and SEC1 can only be + * encrypted by specifying a `cipher`when the PEM `format` is used. For maximum compatibility, use PKCS#8 for + * encrypted private keys. Since PKCS#8 defines its own + * encryption mechanism, PEM-level encryption is not supported when encrypting + * a PKCS#8 key. See [RFC 5208](https://www.rfc-editor.org/rfc/rfc5208.txt) for PKCS#8 encryption and [RFC 1421](https://www.rfc-editor.org/rfc/rfc1421.txt) for + * PKCS#1 and SEC1 encryption. + * @since v11.6.0 + */ + export(options?: T): KeyExportResult; + /** + * Returns `true` or `false` depending on whether the keys have exactly the same + * type, value, and parameters. This method is not [constant time](https://en.wikipedia.org/wiki/Timing_attack). + * @since v17.7.0, v16.15.0 + * @param otherKeyObject A `KeyObject` with which to compare `keyObject`. + */ + equals(otherKeyObject: KeyObject): boolean; + /** + * For secret keys, this property represents the size of the key in bytes. This + * property is `undefined` for asymmetric keys. + * @since v11.6.0 + */ + symmetricKeySize?: number; + /** + * Converts a `KeyObject` instance to a `CryptoKey`. + * @since 22.10.0 + */ + toCryptoKey( + algorithm: + | webcrypto.AlgorithmIdentifier + | webcrypto.RsaHashedImportParams + | webcrypto.EcKeyImportParams + | webcrypto.HmacImportParams, + extractable: boolean, + keyUsages: readonly webcrypto.KeyUsage[], + ): webcrypto.CryptoKey; + /** + * Depending on the type of this `KeyObject`, this property is either`'secret'` for secret (symmetric) keys, `'public'` for public (asymmetric) keys + * or `'private'` for private (asymmetric) keys. + * @since v11.6.0 + */ + type: KeyObjectType; + } + type CipherCCMTypes = "aes-128-ccm" | "aes-192-ccm" | "aes-256-ccm"; + type CipherGCMTypes = "aes-128-gcm" | "aes-192-gcm" | "aes-256-gcm"; + type CipherOCBTypes = "aes-128-ocb" | "aes-192-ocb" | "aes-256-ocb"; + type CipherChaCha20Poly1305Types = "chacha20-poly1305"; + type BinaryLike = string | NodeJS.ArrayBufferView; + type CipherKey = BinaryLike | KeyObject; + interface CipherCCMOptions extends stream.TransformOptions { + authTagLength: number; + } + interface CipherGCMOptions extends stream.TransformOptions { + authTagLength?: number | undefined; + } + interface CipherOCBOptions extends stream.TransformOptions { + authTagLength: number; + } + interface CipherChaCha20Poly1305Options extends stream.TransformOptions { + /** @default 16 */ + authTagLength?: number | undefined; + } + /** + * Creates and returns a `Cipher` object, with the given `algorithm`, `key` and + * initialization vector (`iv`). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication + * tag that will be returned by `getAuthTag()` and defaults to 16 bytes. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms` will + * display the available cipher algorithms. + * + * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded + * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be + * a `KeyObject` of type `secret`. If the cipher does not need + * an initialization vector, `iv` may be `null`. + * + * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * Initialization vectors should be unpredictable and unique; ideally, they will be + * cryptographically random. They do not have to be secret: IVs are typically just + * added to ciphertext messages unencrypted. It may sound contradictory that + * something has to be unpredictable and unique, but does not have to be secret; + * remember that an attacker must not be able to predict ahead of time what a + * given IV will be. + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createCipheriv( + algorithm: CipherCCMTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherCCMOptions, + ): CipherCCM; + function createCipheriv( + algorithm: CipherOCBTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherOCBOptions, + ): CipherOCB; + function createCipheriv( + algorithm: CipherGCMTypes, + key: CipherKey, + iv: BinaryLike, + options?: CipherGCMOptions, + ): CipherGCM; + function createCipheriv( + algorithm: CipherChaCha20Poly1305Types, + key: CipherKey, + iv: BinaryLike, + options?: CipherChaCha20Poly1305Options, + ): CipherChaCha20Poly1305; + function createCipheriv( + algorithm: string, + key: CipherKey, + iv: BinaryLike | null, + options?: stream.TransformOptions, + ): Cipheriv; + /** + * Instances of the `Cipheriv` class are used to encrypt data. The class can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where plain unencrypted + * data is written to produce encrypted data on the readable side, or + * * Using the `cipher.update()` and `cipher.final()` methods to produce + * the encrypted data. + * + * The {@link createCipheriv} method is + * used to create `Cipheriv` instances. `Cipheriv` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Cipheriv` objects as streams: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * // Once we have the key and iv, we can create and use the cipher... + * const cipher = createCipheriv(algorithm, key, iv); + * + * let encrypted = ''; + * cipher.setEncoding('hex'); + * + * cipher.on('data', (chunk) => encrypted += chunk); + * cipher.on('end', () => console.log(encrypted)); + * + * cipher.write('some clear text data'); + * cipher.end(); + * }); + * }); + * ``` + * + * Example: Using `Cipheriv` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'node:fs'; + * + * import { + * pipeline, + * } from 'node:stream'; + * + * const { + * scrypt, + * randomFill, + * createCipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * const cipher = createCipheriv(algorithm, key, iv); + * + * const input = createReadStream('test.js'); + * const output = createWriteStream('test.enc'); + * + * pipeline(input, cipher, output, (err) => { + * if (err) throw err; + * }); + * }); + * }); + * ``` + * + * Example: Using the `cipher.update()` and `cipher.final()` methods: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * const cipher = createCipheriv(algorithm, key, iv); + * + * let encrypted = cipher.update('some clear text data', 'utf8', 'hex'); + * encrypted += cipher.final('hex'); + * console.log(encrypted); + * }); + * }); + * ``` + * @since v0.1.94 + */ + class Cipheriv extends stream.Transform { + private constructor(); + /** + * Updates the cipher with `data`. If the `inputEncoding` argument is given, + * the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`, `TypedArray`, or `DataView`. If `data` is a `Buffer`, + * `TypedArray`, or `DataView`, then `inputEncoding` is ignored. + * + * The `outputEncoding` specifies the output format of the enciphered + * data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned. + * + * The `cipher.update()` method can be called multiple times with new data until `cipher.final()` is called. Calling `cipher.update()` after `cipher.final()` will result in an error being + * thrown. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the data. + * @param outputEncoding The `encoding` of the return value. + */ + update(data: BinaryLike): NonSharedBuffer; + update(data: string, inputEncoding: Encoding): NonSharedBuffer; + update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string; + update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string; + /** + * Once the `cipher.final()` method has been called, the `Cipheriv` object can no + * longer be used to encrypt data. Attempts to call `cipher.final()` more than + * once will result in an error being thrown. + * @since v0.1.94 + * @param outputEncoding The `encoding` of the return value. + * @return Any remaining enciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. + */ + final(): NonSharedBuffer; + final(outputEncoding: BufferEncoding): string; + /** + * When using block encryption algorithms, the `Cipheriv` class will automatically + * add padding to the input data to the appropriate block size. To disable the + * default padding call `cipher.setAutoPadding(false)`. + * + * When `autoPadding` is `false`, the length of the entire input data must be a + * multiple of the cipher's block size or `cipher.final()` will throw an error. + * Disabling automatic padding is useful for non-standard padding, for instance + * using `0x0` instead of PKCS padding. + * + * The `cipher.setAutoPadding()` method must be called before `cipher.final()`. + * @since v0.7.1 + * @param [autoPadding=true] + * @return for method chaining. + */ + setAutoPadding(autoPadding?: boolean): this; + } + interface CipherCCM extends Cipheriv { + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + getAuthTag(): NonSharedBuffer; + } + interface CipherGCM extends Cipheriv { + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + getAuthTag(): NonSharedBuffer; + } + interface CipherOCB extends Cipheriv { + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + getAuthTag(): NonSharedBuffer; + } + interface CipherChaCha20Poly1305 extends Cipheriv { + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + getAuthTag(): NonSharedBuffer; + } + /** + * Creates and returns a `Decipheriv` object that uses the given `algorithm`, `key` and initialization vector (`iv`). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the `authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength` option is not required but can be used to restrict accepted authentication tags + * to those with the specified length. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms` will + * display the available cipher algorithms. + * + * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded + * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be + * a `KeyObject` of type `secret`. If the cipher does not need + * an initialization vector, `iv` may be `null`. + * + * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * Initialization vectors should be unpredictable and unique; ideally, they will be + * cryptographically random. They do not have to be secret: IVs are typically just + * added to ciphertext messages unencrypted. It may sound contradictory that + * something has to be unpredictable and unique, but does not have to be secret; + * remember that an attacker must not be able to predict ahead of time what a given + * IV will be. + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createDecipheriv( + algorithm: CipherCCMTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherCCMOptions, + ): DecipherCCM; + function createDecipheriv( + algorithm: CipherOCBTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherOCBOptions, + ): DecipherOCB; + function createDecipheriv( + algorithm: CipherGCMTypes, + key: CipherKey, + iv: BinaryLike, + options?: CipherGCMOptions, + ): DecipherGCM; + function createDecipheriv( + algorithm: CipherChaCha20Poly1305Types, + key: CipherKey, + iv: BinaryLike, + options?: CipherChaCha20Poly1305Options, + ): DecipherChaCha20Poly1305; + function createDecipheriv( + algorithm: string, + key: CipherKey, + iv: BinaryLike | null, + options?: stream.TransformOptions, + ): Decipheriv; + /** + * Instances of the `Decipheriv` class are used to decrypt data. The class can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where plain encrypted + * data is written to produce unencrypted data on the readable side, or + * * Using the `decipher.update()` and `decipher.final()` methods to + * produce the unencrypted data. + * + * The {@link createDecipheriv} method is + * used to create `Decipheriv` instances. `Decipheriv` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Decipheriv` objects as streams: + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * scryptSync, + * createDecipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Key length is dependent on the algorithm. In this case for aes192, it is + * // 24 bytes (192 bits). + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * let decrypted = ''; + * decipher.on('readable', () => { + * let chunk; + * while (null !== (chunk = decipher.read())) { + * decrypted += chunk.toString('utf8'); + * } + * }); + * decipher.on('end', () => { + * console.log(decrypted); + * // Prints: some clear text data + * }); + * + * // Encrypted with same algorithm, key and iv. + * const encrypted = + * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; + * decipher.write(encrypted, 'hex'); + * decipher.end(); + * ``` + * + * Example: Using `Decipheriv` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'node:fs'; + * import { Buffer } from 'node:buffer'; + * const { + * scryptSync, + * createDecipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * const input = createReadStream('test.enc'); + * const output = createWriteStream('test.js'); + * + * input.pipe(decipher).pipe(output); + * ``` + * + * Example: Using the `decipher.update()` and `decipher.final()` methods: + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * scryptSync, + * createDecipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * // Encrypted using same algorithm, key and iv. + * const encrypted = + * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; + * let decrypted = decipher.update(encrypted, 'hex', 'utf8'); + * decrypted += decipher.final('utf8'); + * console.log(decrypted); + * // Prints: some clear text data + * ``` + * @since v0.1.94 + */ + class Decipheriv extends stream.Transform { + private constructor(); + /** + * Updates the decipher with `data`. If the `inputEncoding` argument is given, + * the `data` argument is a string using the specified encoding. If the `inputEncoding` argument is not given, `data` must be a `Buffer`. If `data` is a `Buffer` then `inputEncoding` is + * ignored. + * + * The `outputEncoding` specifies the output format of the enciphered + * data. If the `outputEncoding` is specified, a string using the specified encoding is returned. If no `outputEncoding` is provided, a `Buffer` is returned. + * + * The `decipher.update()` method can be called multiple times with new data until `decipher.final()` is called. Calling `decipher.update()` after `decipher.final()` will result in an error + * being thrown. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the `data` string. + * @param outputEncoding The `encoding` of the return value. + */ + update(data: NodeJS.ArrayBufferView): NonSharedBuffer; + update(data: string, inputEncoding: Encoding): NonSharedBuffer; + update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string; + update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string; + /** + * Once the `decipher.final()` method has been called, the `Decipheriv` object can + * no longer be used to decrypt data. Attempts to call `decipher.final()` more + * than once will result in an error being thrown. + * @since v0.1.94 + * @param outputEncoding The `encoding` of the return value. + * @return Any remaining deciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. + */ + final(): NonSharedBuffer; + final(outputEncoding: BufferEncoding): string; + /** + * When data has been encrypted without standard block padding, calling `decipher.setAutoPadding(false)` will disable automatic padding to prevent `decipher.final()` from checking for and + * removing padding. + * + * Turning auto padding off will only work if the input data's length is a + * multiple of the ciphers block size. + * + * The `decipher.setAutoPadding()` method must be called before `decipher.final()`. + * @since v0.7.1 + * @param [autoPadding=true] + * @return for method chaining. + */ + setAutoPadding(auto_padding?: boolean): this; + } + interface DecipherCCM extends Decipheriv { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + } + interface DecipherGCM extends Decipheriv { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + } + interface DecipherOCB extends Decipheriv { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + } + interface DecipherChaCha20Poly1305 extends Decipheriv { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + } + interface PrivateKeyInput { + key: string | Buffer; + format?: KeyFormat | undefined; + type?: PrivateKeyExportType | undefined; + passphrase?: string | Buffer | undefined; + encoding?: string | undefined; + } + interface PublicKeyInput { + key: string | Buffer; + format?: KeyFormat | undefined; + type?: PublicKeyExportType | undefined; + encoding?: string | undefined; + } + /** + * Asynchronously generates a new random secret key of the given `length`. The `type` will determine which validations will be performed on the `length`. + * + * ```js + * const { + * generateKey, + * } = await import('node:crypto'); + * + * generateKey('hmac', { length: 512 }, (err, key) => { + * if (err) throw err; + * console.log(key.export().toString('hex')); // 46e..........620 + * }); + * ``` + * + * The size of a generated HMAC key should not exceed the block size of the + * underlying hash function. See {@link createHmac} for more information. + * @since v15.0.0 + * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. + */ + function generateKey( + type: "hmac" | "aes", + options: { + length: number; + }, + callback: (err: Error | null, key: KeyObject) => void, + ): void; + /** + * Synchronously generates a new random secret key of the given `length`. The `type` will determine which validations will be performed on the `length`. + * + * ```js + * const { + * generateKeySync, + * } = await import('node:crypto'); + * + * const key = generateKeySync('hmac', { length: 512 }); + * console.log(key.export().toString('hex')); // e89..........41e + * ``` + * + * The size of a generated HMAC key should not exceed the block size of the + * underlying hash function. See {@link createHmac} for more information. + * @since v15.0.0 + * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. + */ + function generateKeySync( + type: "hmac" | "aes", + options: { + length: number; + }, + ): KeyObject; + interface JsonWebKeyInput { + key: webcrypto.JsonWebKey; + format: "jwk"; + } + /** + * Creates and returns a new key object containing a private key. If `key` is a + * string or `Buffer`, `format` is assumed to be `'pem'`; otherwise, `key` must be an object with the properties described above. + * + * If the private key is encrypted, a `passphrase` must be specified. The length + * of the passphrase is limited to 1024 bytes. + * @since v11.6.0 + */ + function createPrivateKey(key: PrivateKeyInput | string | Buffer | JsonWebKeyInput): KeyObject; + /** + * Creates and returns a new key object containing a public key. If `key` is a + * string or `Buffer`, `format` is assumed to be `'pem'`; if `key` is a `KeyObject` with type `'private'`, the public key is derived from the given private key; + * otherwise, `key` must be an object with the properties described above. + * + * If the format is `'pem'`, the `'key'` may also be an X.509 certificate. + * + * Because public keys can be derived from private keys, a private key may be + * passed instead of a public key. In that case, this function behaves as if {@link createPrivateKey} had been called, except that the type of the + * returned `KeyObject` will be `'public'` and that the private key cannot be + * extracted from the returned `KeyObject`. Similarly, if a `KeyObject` with type `'private'` is given, a new `KeyObject` with type `'public'` will be returned + * and it will be impossible to extract the private key from the returned object. + * @since v11.6.0 + */ + function createPublicKey(key: PublicKeyInput | string | Buffer | KeyObject | JsonWebKeyInput): KeyObject; + /** + * Creates and returns a new key object containing a secret key for symmetric + * encryption or `Hmac`. + * @since v11.6.0 + * @param encoding The string encoding when `key` is a string. + */ + function createSecretKey(key: NodeJS.ArrayBufferView): KeyObject; + function createSecretKey(key: string, encoding: BufferEncoding): KeyObject; + /** + * Creates and returns a `Sign` object that uses the given `algorithm`. Use {@link getHashes} to obtain the names of the available digest algorithms. + * Optional `options` argument controls the `stream.Writable` behavior. + * + * In some cases, a `Sign` instance can be created using the name of a signature + * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use + * the corresponding digest algorithm. This does not work for all signature + * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest + * algorithm names. + * @since v0.1.92 + * @param options `stream.Writable` options + */ + // TODO: signing algorithm type + function createSign(algorithm: string, options?: stream.WritableOptions): Sign; + type DSAEncoding = "der" | "ieee-p1363"; + interface SigningOptions { + /** + * @see crypto.constants.RSA_PKCS1_PADDING + */ + padding?: number | undefined; + saltLength?: number | undefined; + dsaEncoding?: DSAEncoding | undefined; + context?: ArrayBuffer | NodeJS.ArrayBufferView | undefined; + } + interface SignPrivateKeyInput extends PrivateKeyInput, SigningOptions {} + interface SignKeyObjectInput extends SigningOptions { + key: KeyObject; + } + interface SignJsonWebKeyInput extends JsonWebKeyInput, SigningOptions {} + interface VerifyPublicKeyInput extends PublicKeyInput, SigningOptions {} + interface VerifyKeyObjectInput extends SigningOptions { + key: KeyObject; + } + interface VerifyJsonWebKeyInput extends JsonWebKeyInput, SigningOptions {} + type KeyLike = string | Buffer | KeyObject; + /** + * The `Sign` class is a utility for generating signatures. It can be used in one + * of two ways: + * + * * As a writable `stream`, where data to be signed is written and the `sign.sign()` method is used to generate and return the signature, or + * * Using the `sign.update()` and `sign.sign()` methods to produce the + * signature. + * + * The {@link createSign} method is used to create `Sign` instances. The + * argument is the string name of the hash function to use. `Sign` objects are not + * to be created directly using the `new` keyword. + * + * Example: Using `Sign` and `Verify` objects as streams: + * + * ```js + * const { + * generateKeyPairSync, + * createSign, + * createVerify, + * } = await import('node:crypto'); + * + * const { privateKey, publicKey } = generateKeyPairSync('ec', { + * namedCurve: 'sect239k1', + * }); + * + * const sign = createSign('SHA256'); + * sign.write('some data to sign'); + * sign.end(); + * const signature = sign.sign(privateKey, 'hex'); + * + * const verify = createVerify('SHA256'); + * verify.write('some data to sign'); + * verify.end(); + * console.log(verify.verify(publicKey, signature, 'hex')); + * // Prints: true + * ``` + * + * Example: Using the `sign.update()` and `verify.update()` methods: + * + * ```js + * const { + * generateKeyPairSync, + * createSign, + * createVerify, + * } = await import('node:crypto'); + * + * const { privateKey, publicKey } = generateKeyPairSync('rsa', { + * modulusLength: 2048, + * }); + * + * const sign = createSign('SHA256'); + * sign.update('some data to sign'); + * sign.end(); + * const signature = sign.sign(privateKey); + * + * const verify = createVerify('SHA256'); + * verify.update('some data to sign'); + * verify.end(); + * console.log(verify.verify(publicKey, signature)); + * // Prints: true + * ``` + * @since v0.1.92 + */ + class Sign extends stream.Writable { + private constructor(); + /** + * Updates the `Sign` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): this; + update(data: string, inputEncoding: Encoding): this; + /** + * Calculates the signature on all the data passed through using either `sign.update()` or `sign.write()`. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if `privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the following additional properties can be passed: + * + * If `outputEncoding` is provided a string is returned; otherwise a `Buffer` is returned. + * + * The `Sign` object can not be again used after `sign.sign()` method has been + * called. Multiple calls to `sign.sign()` will result in an error being thrown. + * @since v0.1.92 + */ + sign(privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput): NonSharedBuffer; + sign( + privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput, + outputFormat: BinaryToTextEncoding, + ): string; + } + /** + * Creates and returns a `Verify` object that uses the given algorithm. + * Use {@link getHashes} to obtain an array of names of the available + * signing algorithms. Optional `options` argument controls the `stream.Writable` behavior. + * + * In some cases, a `Verify` instance can be created using the name of a signature + * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use + * the corresponding digest algorithm. This does not work for all signature + * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest + * algorithm names. + * @since v0.1.92 + * @param options `stream.Writable` options + */ + function createVerify(algorithm: string, options?: stream.WritableOptions): Verify; + /** + * The `Verify` class is a utility for verifying signatures. It can be used in one + * of two ways: + * + * * As a writable `stream` where written data is used to validate against the + * supplied signature, or + * * Using the `verify.update()` and `verify.verify()` methods to verify + * the signature. + * + * The {@link createVerify} method is used to create `Verify` instances. `Verify` objects are not to be created directly using the `new` keyword. + * + * See `Sign` for examples. + * @since v0.1.92 + */ + class Verify extends stream.Writable { + private constructor(); + /** + * Updates the `Verify` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `inputEncoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or `DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Verify; + update(data: string, inputEncoding: Encoding): Verify; + /** + * Verifies the provided data using the given `object` and `signature`. + * + * If `object` is not a `KeyObject`, this function behaves as if `object` had been passed to {@link createPublicKey}. If it is an + * object, the following additional properties can be passed: + * + * The `signature` argument is the previously calculated signature for the data, in + * the `signatureEncoding`. + * If a `signatureEncoding` is specified, the `signature` is expected to be a + * string; otherwise `signature` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * The `verify` object can not be used again after `verify.verify()` has been + * called. Multiple calls to `verify.verify()` will result in an error being + * thrown. + * + * Because public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v0.1.92 + */ + verify( + object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: NodeJS.ArrayBufferView, + ): boolean; + verify( + object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: string, + signature_format?: BinaryToTextEncoding, + ): boolean; + } + /** + * Creates a `DiffieHellman` key exchange object using the supplied `prime` and an + * optional specific `generator`. + * + * The `generator` argument can be a number, string, or `Buffer`. If `generator` is not specified, the value `2` is used. + * + * If `primeEncoding` is specified, `prime` is expected to be a string; otherwise + * a `Buffer`, `TypedArray`, or `DataView` is expected. + * + * If `generatorEncoding` is specified, `generator` is expected to be a string; + * otherwise a number, `Buffer`, `TypedArray`, or `DataView` is expected. + * @since v0.11.12 + * @param primeEncoding The `encoding` of the `prime` string. + * @param [generator=2] + * @param generatorEncoding The `encoding` of the `generator` string. + */ + function createDiffieHellman(primeLength: number, generator?: number): DiffieHellman; + function createDiffieHellman( + prime: ArrayBuffer | NodeJS.ArrayBufferView, + generator?: number | ArrayBuffer | NodeJS.ArrayBufferView, + ): DiffieHellman; + function createDiffieHellman( + prime: ArrayBuffer | NodeJS.ArrayBufferView, + generator: string, + generatorEncoding: BinaryToTextEncoding, + ): DiffieHellman; + function createDiffieHellman( + prime: string, + primeEncoding: BinaryToTextEncoding, + generator?: number | ArrayBuffer | NodeJS.ArrayBufferView, + ): DiffieHellman; + function createDiffieHellman( + prime: string, + primeEncoding: BinaryToTextEncoding, + generator: string, + generatorEncoding: BinaryToTextEncoding, + ): DiffieHellman; + /** + * The `DiffieHellman` class is a utility for creating Diffie-Hellman key + * exchanges. + * + * Instances of the `DiffieHellman` class can be created using the {@link createDiffieHellman} function. + * + * ```js + * import assert from 'node:assert'; + * + * const { + * createDiffieHellman, + * } = await import('node:crypto'); + * + * // Generate Alice's keys... + * const alice = createDiffieHellman(2048); + * const aliceKey = alice.generateKeys(); + * + * // Generate Bob's keys... + * const bob = createDiffieHellman(alice.getPrime(), alice.getGenerator()); + * const bobKey = bob.generateKeys(); + * + * // Exchange and generate the secret... + * const aliceSecret = alice.computeSecret(bobKey); + * const bobSecret = bob.computeSecret(aliceKey); + * + * // OK + * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); + * ``` + * @since v0.5.0 + */ + class DiffieHellman { + private constructor(); + /** + * Generates private and public Diffie-Hellman key values unless they have been + * generated or computed already, and returns + * the public key in the specified `encoding`. This key should be + * transferred to the other party. + * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. + * + * This function is a thin wrapper around [`DH_generate_key()`](https://www.openssl.org/docs/man3.0/man3/DH_generate_key.html). In particular, + * once a private key has been generated or set, calling this function only updates + * the public key but does not generate a new private key. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + generateKeys(): NonSharedBuffer; + generateKeys(encoding: BinaryToTextEncoding): string; + /** + * Computes the shared secret using `otherPublicKey` as the other + * party's public key and returns the computed shared secret. The supplied + * key is interpreted using the specified `inputEncoding`, and secret is + * encoded using specified `outputEncoding`. + * If the `inputEncoding` is not + * provided, `otherPublicKey` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * If `outputEncoding` is given a string is returned; otherwise, a `Buffer` is returned. + * @since v0.5.0 + * @param inputEncoding The `encoding` of an `otherPublicKey` string. + * @param outputEncoding The `encoding` of the return value. + */ + computeSecret( + otherPublicKey: NodeJS.ArrayBufferView, + inputEncoding?: null, + outputEncoding?: null, + ): NonSharedBuffer; + computeSecret( + otherPublicKey: string, + inputEncoding: BinaryToTextEncoding, + outputEncoding?: null, + ): NonSharedBuffer; + computeSecret( + otherPublicKey: NodeJS.ArrayBufferView, + inputEncoding: null, + outputEncoding: BinaryToTextEncoding, + ): string; + computeSecret( + otherPublicKey: string, + inputEncoding: BinaryToTextEncoding, + outputEncoding: BinaryToTextEncoding, + ): string; + /** + * Returns the Diffie-Hellman prime in the specified `encoding`. + * If `encoding` is provided a string is + * returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPrime(): NonSharedBuffer; + getPrime(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman generator in the specified `encoding`. + * If `encoding` is provided a string is + * returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getGenerator(): NonSharedBuffer; + getGenerator(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman public key in the specified `encoding`. + * If `encoding` is provided a + * string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPublicKey(): NonSharedBuffer; + getPublicKey(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman private key in the specified `encoding`. + * If `encoding` is provided a + * string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPrivateKey(): NonSharedBuffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + /** + * Sets the Diffie-Hellman public key. If the `encoding` argument is provided, `publicKey` is expected + * to be a string. If no `encoding` is provided, `publicKey` is expected + * to be a `Buffer`, `TypedArray`, or `DataView`. + * @since v0.5.0 + * @param encoding The `encoding` of the `publicKey` string. + */ + setPublicKey(publicKey: NodeJS.ArrayBufferView): void; + setPublicKey(publicKey: string, encoding: BufferEncoding): void; + /** + * Sets the Diffie-Hellman private key. If the `encoding` argument is provided,`privateKey` is expected + * to be a string. If no `encoding` is provided, `privateKey` is expected + * to be a `Buffer`, `TypedArray`, or `DataView`. + * + * This function does not automatically compute the associated public key. Either `diffieHellman.setPublicKey()` or `diffieHellman.generateKeys()` can be + * used to manually provide the public key or to automatically derive it. + * @since v0.5.0 + * @param encoding The `encoding` of the `privateKey` string. + */ + setPrivateKey(privateKey: NodeJS.ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BufferEncoding): void; + /** + * A bit field containing any warnings and/or errors resulting from a check + * performed during initialization of the `DiffieHellman` object. + * + * The following values are valid for this property (as defined in `node:constants` module): + * + * * `DH_CHECK_P_NOT_SAFE_PRIME` + * * `DH_CHECK_P_NOT_PRIME` + * * `DH_UNABLE_TO_CHECK_GENERATOR` + * * `DH_NOT_SUITABLE_GENERATOR` + * @since v0.11.12 + */ + verifyError: number; + } + /** + * The `DiffieHellmanGroup` class takes a well-known modp group as its argument. + * It works the same as `DiffieHellman`, except that it does not allow changing its keys after creation. + * In other words, it does not implement `setPublicKey()` or `setPrivateKey()` methods. + * + * ```js + * const { createDiffieHellmanGroup } = await import('node:crypto'); + * const dh = createDiffieHellmanGroup('modp1'); + * ``` + * The name (e.g. `'modp1'`) is taken from [RFC 2412](https://www.rfc-editor.org/rfc/rfc2412.txt) (modp1 and 2) and [RFC 3526](https://www.rfc-editor.org/rfc/rfc3526.txt): + * ```bash + * $ perl -ne 'print "$1\n" if /"(modp\d+)"/' src/node_crypto_groups.h + * modp1 # 768 bits + * modp2 # 1024 bits + * modp5 # 1536 bits + * modp14 # 2048 bits + * modp15 # etc. + * modp16 + * modp17 + * modp18 + * ``` + * @since v0.7.5 + */ + const DiffieHellmanGroup: DiffieHellmanGroupConstructor; + interface DiffieHellmanGroupConstructor { + new(name: string): DiffieHellmanGroup; + (name: string): DiffieHellmanGroup; + readonly prototype: DiffieHellmanGroup; + } + type DiffieHellmanGroup = Omit; + /** + * Creates a predefined `DiffieHellmanGroup` key exchange object. The + * supported groups are listed in the documentation for `DiffieHellmanGroup`. + * + * The returned object mimics the interface of objects created by {@link createDiffieHellman}, but will not allow changing + * the keys (with `diffieHellman.setPublicKey()`, for example). The + * advantage of using this method is that the parties do not have to + * generate nor exchange a group modulus beforehand, saving both processor + * and communication time. + * + * Example (obtaining a shared secret): + * + * ```js + * const { + * getDiffieHellman, + * } = await import('node:crypto'); + * const alice = getDiffieHellman('modp14'); + * const bob = getDiffieHellman('modp14'); + * + * alice.generateKeys(); + * bob.generateKeys(); + * + * const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); + * const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); + * + * // aliceSecret and bobSecret should be the same + * console.log(aliceSecret === bobSecret); + * ``` + * @since v0.7.5 + */ + function getDiffieHellman(groupName: string): DiffieHellmanGroup; + /** + * An alias for {@link getDiffieHellman} + * @since v0.9.3 + */ + function createDiffieHellmanGroup(name: string): DiffieHellmanGroup; + /** + * Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2) + * implementation. A selected HMAC digest algorithm specified by `digest` is + * applied to derive a key of the requested byte length (`keylen`) from the `password`, `salt` and `iterations`. + * + * The supplied `callback` function is called with two arguments: `err` and `derivedKey`. If an error occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. By default, the successfully generated `derivedKey` will be passed to the callback as a `Buffer`. An error will be + * thrown if any of the input arguments specify invalid values or types. + * + * The `iterations` argument must be a number set as high as possible. The + * higher the number of iterations, the more secure the derived key will be, + * but will take a longer amount of time to complete. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * ```js + * const { + * pbkdf2, + * } = await import('node:crypto'); + * + * pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * ``` + * + * An array of supported digest functions can be retrieved using {@link getHashes}. + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * @since v0.5.5 + */ + function pbkdf2( + password: BinaryLike, + salt: BinaryLike, + iterations: number, + keylen: number, + digest: string, + callback: (err: Error | null, derivedKey: NonSharedBuffer) => void, + ): void; + /** + * Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2) + * implementation. A selected HMAC digest algorithm specified by `digest` is + * applied to derive a key of the requested byte length (`keylen`) from the `password`, `salt` and `iterations`. + * + * If an error occurs an `Error` will be thrown, otherwise the derived key will be + * returned as a `Buffer`. + * + * The `iterations` argument must be a number set as high as possible. The + * higher the number of iterations, the more secure the derived key will be, + * but will take a longer amount of time to complete. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * ```js + * const { + * pbkdf2Sync, + * } = await import('node:crypto'); + * + * const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512'); + * console.log(key.toString('hex')); // '3745e48...08d59ae' + * ``` + * + * An array of supported digest functions can be retrieved using {@link getHashes}. + * @since v0.9.3 + */ + function pbkdf2Sync( + password: BinaryLike, + salt: BinaryLike, + iterations: number, + keylen: number, + digest: string, + ): NonSharedBuffer; + /** + * Generates cryptographically strong pseudorandom data. The `size` argument + * is a number indicating the number of bytes to generate. + * + * If a `callback` function is provided, the bytes are generated asynchronously + * and the `callback` function is invoked with two arguments: `err` and `buf`. + * If an error occurs, `err` will be an `Error` object; otherwise it is `null`. The `buf` argument is a `Buffer` containing the generated bytes. + * + * ```js + * // Asynchronous + * const { + * randomBytes, + * } = await import('node:crypto'); + * + * randomBytes(256, (err, buf) => { + * if (err) throw err; + * console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`); + * }); + * ``` + * + * If the `callback` function is not provided, the random bytes are generated + * synchronously and returned as a `Buffer`. An error will be thrown if + * there is a problem generating the bytes. + * + * ```js + * // Synchronous + * const { + * randomBytes, + * } = await import('node:crypto'); + * + * const buf = randomBytes(256); + * console.log( + * `${buf.length} bytes of random data: ${buf.toString('hex')}`); + * ``` + * + * The `crypto.randomBytes()` method will not complete until there is + * sufficient entropy available. + * This should normally never take longer than a few milliseconds. The only time + * when generating the random bytes may conceivably block for a longer period of + * time is right after boot, when the whole system is still low on entropy. + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * + * The asynchronous version of `crypto.randomBytes()` is carried out in a single + * threadpool request. To minimize threadpool task length variation, partition + * large `randomBytes` requests when doing so as part of fulfilling a client + * request. + * @since v0.5.8 + * @param size The number of bytes to generate. The `size` must not be larger than `2**31 - 1`. + * @return if the `callback` function is not provided. + */ + function randomBytes(size: number): NonSharedBuffer; + function randomBytes(size: number, callback: (err: Error | null, buf: NonSharedBuffer) => void): void; + function pseudoRandomBytes(size: number): NonSharedBuffer; + function pseudoRandomBytes(size: number, callback: (err: Error | null, buf: NonSharedBuffer) => void): void; + /** + * Return a random integer `n` such that `min <= n < max`. This + * implementation avoids [modulo bias](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Modulo_bias). + * + * The range (`max - min`) must be less than 2**48. `min` and `max` must + * be [safe integers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger). + * + * If the `callback` function is not provided, the random integer is + * generated synchronously. + * + * ```js + * // Asynchronous + * const { + * randomInt, + * } = await import('node:crypto'); + * + * randomInt(3, (err, n) => { + * if (err) throw err; + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * }); + * ``` + * + * ```js + * // Synchronous + * const { + * randomInt, + * } = await import('node:crypto'); + * + * const n = randomInt(3); + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * ``` + * + * ```js + * // With `min` argument + * const { + * randomInt, + * } = await import('node:crypto'); + * + * const n = randomInt(1, 7); + * console.log(`The dice rolled: ${n}`); + * ``` + * @since v14.10.0, v12.19.0 + * @param [min=0] Start of random range (inclusive). + * @param max End of random range (exclusive). + * @param callback `function(err, n) {}`. + */ + function randomInt(max: number): number; + function randomInt(min: number, max: number): number; + function randomInt(max: number, callback: (err: Error | null, value: number) => void): void; + function randomInt(min: number, max: number, callback: (err: Error | null, value: number) => void): void; + /** + * Synchronous version of {@link randomFill}. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFillSync } = await import('node:crypto'); + * + * const buf = Buffer.alloc(10); + * console.log(randomFillSync(buf).toString('hex')); + * + * randomFillSync(buf, 5); + * console.log(buf.toString('hex')); + * + * // The above is equivalent to the following: + * randomFillSync(buf, 5, 5); + * console.log(buf.toString('hex')); + * ``` + * + * Any `ArrayBuffer`, `TypedArray` or `DataView` instance may be passed as`buffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFillSync } = await import('node:crypto'); + * + * const a = new Uint32Array(10); + * console.log(Buffer.from(randomFillSync(a).buffer, + * a.byteOffset, a.byteLength).toString('hex')); + * + * const b = new DataView(new ArrayBuffer(10)); + * console.log(Buffer.from(randomFillSync(b).buffer, + * b.byteOffset, b.byteLength).toString('hex')); + * + * const c = new ArrayBuffer(10); + * console.log(Buffer.from(randomFillSync(c)).toString('hex')); + * ``` + * @since v7.10.0, v6.13.0 + * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. + * @param [offset=0] + * @param [size=buffer.length - offset] + * @return The object passed as `buffer` argument. + */ + function randomFillSync(buffer: T, offset?: number, size?: number): T; + /** + * This function is similar to {@link randomBytes} but requires the first + * argument to be a `Buffer` that will be filled. It also + * requires that a callback is passed in. + * + * If the `callback` function is not provided, an error will be thrown. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFill } = await import('node:crypto'); + * + * const buf = Buffer.alloc(10); + * randomFill(buf, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * + * randomFill(buf, 5, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * + * // The above is equivalent to the following: + * randomFill(buf, 5, 5, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * ``` + * + * Any `ArrayBuffer`, `TypedArray`, or `DataView` instance may be passed as `buffer`. + * + * While this includes instances of `Float32Array` and `Float64Array`, this + * function should not be used to generate random floating-point numbers. The + * result may contain `+Infinity`, `-Infinity`, and `NaN`, and even if the array + * contains finite numbers only, they are not drawn from a uniform random + * distribution and have no meaningful lower or upper bounds. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFill } = await import('node:crypto'); + * + * const a = new Uint32Array(10); + * randomFill(a, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) + * .toString('hex')); + * }); + * + * const b = new DataView(new ArrayBuffer(10)); + * randomFill(b, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) + * .toString('hex')); + * }); + * + * const c = new ArrayBuffer(10); + * randomFill(c, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf).toString('hex')); + * }); + * ``` + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * + * The asynchronous version of `crypto.randomFill()` is carried out in a single + * threadpool request. To minimize threadpool task length variation, partition + * large `randomFill` requests when doing so as part of fulfilling a client + * request. + * @since v7.10.0, v6.13.0 + * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. + * @param [offset=0] + * @param [size=buffer.length - offset] + * @param callback `function(err, buf) {}`. + */ + function randomFill( + buffer: T, + callback: (err: Error | null, buf: T) => void, + ): void; + function randomFill( + buffer: T, + offset: number, + callback: (err: Error | null, buf: T) => void, + ): void; + function randomFill( + buffer: T, + offset: number, + size: number, + callback: (err: Error | null, buf: T) => void, + ): void; + interface ScryptOptions { + cost?: number | undefined; + blockSize?: number | undefined; + parallelization?: number | undefined; + N?: number | undefined; + r?: number | undefined; + p?: number | undefined; + maxmem?: number | undefined; + } + /** + * Provides an asynchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * The `callback` function is called with two arguments: `err` and `derivedKey`. `err` is an exception object when key derivation fails, otherwise `err` is `null`. `derivedKey` is passed to the + * callback as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { + * scrypt, + * } = await import('node:crypto'); + * + * // Using the factory defaults. + * scrypt('password', 'salt', 64, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * // Using a custom N parameter. Must be a power of two. + * scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...aa39b34' + * }); + * ``` + * @since v10.5.0 + */ + function scrypt( + password: BinaryLike, + salt: BinaryLike, + keylen: number, + callback: (err: Error | null, derivedKey: NonSharedBuffer) => void, + ): void; + function scrypt( + password: BinaryLike, + salt: BinaryLike, + keylen: number, + options: ScryptOptions, + callback: (err: Error | null, derivedKey: NonSharedBuffer) => void, + ): void; + /** + * Provides a synchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * An exception is thrown when key derivation fails, otherwise the derived key is + * returned as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { + * scryptSync, + * } = await import('node:crypto'); + * // Using the factory defaults. + * + * const key1 = scryptSync('password', 'salt', 64); + * console.log(key1.toString('hex')); // '3745e48...08d59ae' + * // Using a custom N parameter. Must be a power of two. + * const key2 = scryptSync('password', 'salt', 64, { N: 1024 }); + * console.log(key2.toString('hex')); // '3745e48...aa39b34' + * ``` + * @since v10.5.0 + */ + function scryptSync( + password: BinaryLike, + salt: BinaryLike, + keylen: number, + options?: ScryptOptions, + ): NonSharedBuffer; + interface RsaPublicKey { + key: KeyLike; + padding?: number | undefined; + } + interface RsaPrivateKey { + key: KeyLike; + passphrase?: string | undefined; + /** + * @default 'sha1' + */ + oaepHash?: string | undefined; + oaepLabel?: NodeJS.TypedArray | undefined; + padding?: number | undefined; + } + /** + * Encrypts the content of `buffer` with `key` and returns a new `Buffer` with encrypted content. The returned data can be decrypted using + * the corresponding private key, for example using {@link privateDecrypt}. + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_OAEP_PADDING`. + * + * Because RSA public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v0.11.14 + */ + function publicEncrypt( + key: RsaPublicKey | RsaPrivateKey | KeyLike, + buffer: NodeJS.ArrayBufferView | string, + ): NonSharedBuffer; + /** + * Decrypts `buffer` with `key`.`buffer` was previously encrypted using + * the corresponding private key, for example using {@link privateEncrypt}. + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_PADDING`. + * + * Because RSA public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v1.1.0 + */ + function publicDecrypt( + key: RsaPublicKey | RsaPrivateKey | KeyLike, + buffer: NodeJS.ArrayBufferView | string, + ): NonSharedBuffer; + /** + * Decrypts `buffer` with `privateKey`. `buffer` was previously encrypted using + * the corresponding public key, for example using {@link publicEncrypt}. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if `privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_OAEP_PADDING`. + * @since v0.11.14 + */ + function privateDecrypt( + privateKey: RsaPrivateKey | KeyLike, + buffer: NodeJS.ArrayBufferView | string, + ): NonSharedBuffer; + /** + * Encrypts `buffer` with `privateKey`. The returned data can be decrypted using + * the corresponding public key, for example using {@link publicDecrypt}. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if `privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_PADDING`. + * @since v1.1.0 + */ + function privateEncrypt( + privateKey: RsaPrivateKey | KeyLike, + buffer: NodeJS.ArrayBufferView | string, + ): NonSharedBuffer; + /** + * ```js + * const { + * getCiphers, + * } = await import('node:crypto'); + * + * console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...] + * ``` + * @since v0.9.3 + * @return An array with the names of the supported cipher algorithms. + */ + function getCiphers(): string[]; + /** + * ```js + * const { + * getCurves, + * } = await import('node:crypto'); + * + * console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...] + * ``` + * @since v2.3.0 + * @return An array with the names of the supported elliptic curves. + */ + function getCurves(): string[]; + /** + * @since v10.0.0 + * @return `1` if and only if a FIPS compliant crypto provider is currently in use, `0` otherwise. A future semver-major release may change the return type of this API to a {boolean}. + */ + function getFips(): 1 | 0; + /** + * Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build. + * Throws an error if FIPS mode is not available. + * @since v10.0.0 + * @param bool `true` to enable FIPS mode. + */ + function setFips(bool: boolean): void; + /** + * ```js + * const { + * getHashes, + * } = await import('node:crypto'); + * + * console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] + * ``` + * @since v0.9.3 + * @return An array of the names of the supported hash algorithms, such as `'RSA-SHA256'`. Hash algorithms are also called "digest" algorithms. + */ + function getHashes(): string[]; + /** + * The `ECDH` class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH) + * key exchanges. + * + * Instances of the `ECDH` class can be created using the {@link createECDH} function. + * + * ```js + * import assert from 'node:assert'; + * + * const { + * createECDH, + * } = await import('node:crypto'); + * + * // Generate Alice's keys... + * const alice = createECDH('secp521r1'); + * const aliceKey = alice.generateKeys(); + * + * // Generate Bob's keys... + * const bob = createECDH('secp521r1'); + * const bobKey = bob.generateKeys(); + * + * // Exchange and generate the secret... + * const aliceSecret = alice.computeSecret(bobKey); + * const bobSecret = bob.computeSecret(aliceKey); + * + * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); + * // OK + * ``` + * @since v0.11.14 + */ + class ECDH { + private constructor(); + /** + * Converts the EC Diffie-Hellman public key specified by `key` and `curve` to the + * format specified by `format`. The `format` argument specifies point encoding + * and can be `'compressed'`, `'uncompressed'` or `'hybrid'`. The supplied key is + * interpreted using the specified `inputEncoding`, and the returned key is encoded + * using the specified `outputEncoding`. + * + * Use {@link getCurves} to obtain a list of available curve names. + * On recent OpenSSL releases, `openssl ecparam -list_curves` will also display + * the name and description of each available elliptic curve. + * + * If `format` is not specified the point will be returned in `'uncompressed'` format. + * + * If the `inputEncoding` is not provided, `key` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * Example (uncompressing a key): + * + * ```js + * const { + * createECDH, + * ECDH, + * } = await import('node:crypto'); + * + * const ecdh = createECDH('secp256k1'); + * ecdh.generateKeys(); + * + * const compressedKey = ecdh.getPublicKey('hex', 'compressed'); + * + * const uncompressedKey = ECDH.convertKey(compressedKey, + * 'secp256k1', + * 'hex', + * 'hex', + * 'uncompressed'); + * + * // The converted key and the uncompressed public key should be the same + * console.log(uncompressedKey === ecdh.getPublicKey('hex')); + * ``` + * @since v10.0.0 + * @param inputEncoding The `encoding` of the `key` string. + * @param outputEncoding The `encoding` of the return value. + * @param [format='uncompressed'] + */ + static convertKey( + key: BinaryLike, + curve: string, + inputEncoding?: BinaryToTextEncoding, + outputEncoding?: "latin1" | "hex" | "base64" | "base64url", + format?: "uncompressed" | "compressed" | "hybrid", + ): NonSharedBuffer | string; + /** + * Generates private and public EC Diffie-Hellman key values, and returns + * the public key in the specified `format` and `encoding`. This key should be + * transferred to the other party. + * + * The `format` argument specifies point encoding and can be `'compressed'` or `'uncompressed'`. If `format` is not specified, the point will be returned in`'uncompressed'` format. + * + * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @param [format='uncompressed'] + */ + generateKeys(): NonSharedBuffer; + generateKeys(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; + /** + * Computes the shared secret using `otherPublicKey` as the other + * party's public key and returns the computed shared secret. The supplied + * key is interpreted using specified `inputEncoding`, and the returned secret + * is encoded using the specified `outputEncoding`. + * If the `inputEncoding` is not + * provided, `otherPublicKey` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * If `outputEncoding` is given a string will be returned; otherwise a `Buffer` is returned. + * + * `ecdh.computeSecret` will throw an`ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY` error when `otherPublicKey` lies outside of the elliptic curve. Since `otherPublicKey` is + * usually supplied from a remote user over an insecure network, + * be sure to handle this exception accordingly. + * @since v0.11.14 + * @param inputEncoding The `encoding` of the `otherPublicKey` string. + * @param outputEncoding The `encoding` of the return value. + */ + computeSecret(otherPublicKey: NodeJS.ArrayBufferView): NonSharedBuffer; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding): NonSharedBuffer; + computeSecret(otherPublicKey: NodeJS.ArrayBufferView, outputEncoding: BinaryToTextEncoding): string; + computeSecret( + otherPublicKey: string, + inputEncoding: BinaryToTextEncoding, + outputEncoding: BinaryToTextEncoding, + ): string; + /** + * If `encoding` is specified, a string is returned; otherwise a `Buffer` is + * returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @return The EC Diffie-Hellman in the specified `encoding`. + */ + getPrivateKey(): NonSharedBuffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + /** + * The `format` argument specifies point encoding and can be `'compressed'` or `'uncompressed'`. If `format` is not specified the point will be returned in`'uncompressed'` format. + * + * If `encoding` is specified, a string is returned; otherwise a `Buffer` is + * returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @param [format='uncompressed'] + * @return The EC Diffie-Hellman public key in the specified `encoding` and `format`. + */ + getPublicKey(encoding?: null, format?: ECDHKeyFormat): NonSharedBuffer; + getPublicKey(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; + /** + * Sets the EC Diffie-Hellman private key. + * If `encoding` is provided, `privateKey` is expected + * to be a string; otherwise `privateKey` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * If `privateKey` is not valid for the curve specified when the `ECDH` object was + * created, an error is thrown. Upon setting the private key, the associated + * public point (key) is also generated and set in the `ECDH` object. + * @since v0.11.14 + * @param encoding The `encoding` of the `privateKey` string. + */ + setPrivateKey(privateKey: NodeJS.ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BinaryToTextEncoding): void; + } + /** + * Creates an Elliptic Curve Diffie-Hellman (`ECDH`) key exchange object using a + * predefined curve specified by the `curveName` string. Use {@link getCurves} to obtain a list of available curve names. On recent + * OpenSSL releases, `openssl ecparam -list_curves` will also display the name + * and description of each available elliptic curve. + * @since v0.11.14 + */ + function createECDH(curveName: string): ECDH; + /** + * This function compares the underlying bytes that represent the given `ArrayBuffer`, `TypedArray`, or `DataView` instances using a constant-time + * algorithm. + * + * This function does not leak timing information that + * would allow an attacker to guess one of the values. This is suitable for + * comparing HMAC digests or secret values like authentication cookies or [capability urls](https://www.w3.org/TR/capability-urls/). + * + * `a` and `b` must both be `Buffer`s, `TypedArray`s, or `DataView`s, and they + * must have the same byte length. An error is thrown if `a` and `b` have + * different byte lengths. + * + * If at least one of `a` and `b` is a `TypedArray` with more than one byte per + * entry, such as `Uint16Array`, the result will be computed using the platform + * byte order. + * + * **When both of the inputs are `Float32Array`s or `Float64Array`s, this function might return unexpected results due to IEEE 754** + * **encoding of floating-point numbers. In particular, neither `x === y` nor `Object.is(x, y)` implies that the byte representations of two floating-point** + * **numbers `x` and `y` are equal.** + * + * Use of `crypto.timingSafeEqual` does not guarantee that the _surrounding_ code + * is timing-safe. Care should be taken to ensure that the surrounding code does + * not introduce timing vulnerabilities. + * @since v6.6.0 + */ + function timingSafeEqual(a: NodeJS.ArrayBufferView, b: NodeJS.ArrayBufferView): boolean; + interface DHKeyPairOptions extends KeyPairExportOptions<"spki", "pkcs8"> { + /** + * The prime parameter + */ + prime?: Buffer | undefined; + /** + * Prime length in bits + */ + primeLength?: number | undefined; + /** + * Custom generator + * @default 2 + */ + generator?: number | undefined; + /** + * Diffie-Hellman group name + * @see {@link getDiffieHellman} + */ + groupName?: string | undefined; + } + interface DSAKeyPairOptions extends KeyPairExportOptions<"spki", "pkcs8"> { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + } + interface ECKeyPairOptions extends KeyPairExportOptions<"spki", "pkcs8" | "sec1"> { + /** + * Name of the curve to use + */ + namedCurve: string; + /** + * Must be `'named'` or `'explicit'` + * @default 'named' + */ + paramEncoding?: "explicit" | "named" | undefined; + } + interface ED25519KeyPairOptions extends KeyPairExportOptions<"spki", "pkcs8"> {} + interface ED448KeyPairOptions extends KeyPairExportOptions<"spki", "pkcs8"> {} + interface MLDSAKeyPairOptions extends KeyPairExportOptions<"spki", "pkcs8"> {} + interface MLKEMKeyPairOptions extends KeyPairExportOptions<"spki", "pkcs8"> {} + interface RSAPSSKeyPairOptions extends KeyPairExportOptions<"spki", "pkcs8"> { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + /** + * Name of the message digest + */ + hashAlgorithm?: string | undefined; + /** + * Name of the message digest used by MGF1 + */ + mgf1HashAlgorithm?: string | undefined; + /** + * Minimal salt length in bytes + */ + saltLength?: string | undefined; + } + interface RSAKeyPairOptions extends KeyPairExportOptions<"pkcs1" | "spki", "pkcs1" | "pkcs8"> { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + } + interface SLHDSAKeyPairOptions extends KeyPairExportOptions<"spki", "pkcs8"> {} + interface X25519KeyPairOptions extends KeyPairExportOptions<"spki", "pkcs8"> {} + interface X448KeyPairOptions extends KeyPairExportOptions<"spki", "pkcs8"> {} + /** + * Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC, + * Ed25519, Ed448, X25519, X448, DH, and ML-DSA are currently supported. + * + * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function + * behaves as if `keyObject.export()` had been called on its result. Otherwise, + * the respective part of the key is returned as a `KeyObject`. + * + * When encoding public keys, it is recommended to use `'spki'`. When encoding + * private keys, it is recommended to use `'pkcs8'` with a strong passphrase, + * and to keep the passphrase confidential. + * + * ```js + * const { + * generateKeyPairSync, + * } = await import('node:crypto'); + * + * const { + * publicKey, + * privateKey, + * } = generateKeyPairSync('rsa', { + * modulusLength: 4096, + * publicKeyEncoding: { + * type: 'spki', + * format: 'pem', + * }, + * privateKeyEncoding: { + * type: 'pkcs8', + * format: 'pem', + * cipher: 'aes-256-cbc', + * passphrase: 'top secret', + * }, + * }); + * ``` + * + * The return value `{ publicKey, privateKey }` represents the generated key pair. + * When PEM encoding was selected, the respective key will be a string, otherwise + * it will be a buffer containing the data encoded as DER. + * @since v10.12.0 + * @param type The asymmetric key type to generate. See the + * supported [asymmetric key types](https://nodejs.org/docs/latest-v25.x/api/crypto.html#asymmetric-key-types). + */ + function generateKeyPairSync( + type: "dh", + options: T, + ): KeyPairExportResult; + function generateKeyPairSync( + type: "dsa", + options: T, + ): KeyPairExportResult; + function generateKeyPairSync( + type: "ec", + options: T, + ): KeyPairExportResult; + function generateKeyPairSync( + type: "ed25519", + options?: T, + ): KeyPairExportResult; + function generateKeyPairSync( + type: "ed448", + options?: T, + ): KeyPairExportResult; + function generateKeyPairSync( + type: MLDSAKeyType, + options?: T, + ): KeyPairExportResult; + function generateKeyPairSync( + type: MLKEMKeyType, + options?: T, + ): KeyPairExportResult; + function generateKeyPairSync( + type: "rsa-pss", + options: T, + ): KeyPairExportResult; + function generateKeyPairSync( + type: "rsa", + options: T, + ): KeyPairExportResult; + function generateKeyPairSync( + type: SLHDSAKeyType, + options?: T, + ): KeyPairExportResult; + function generateKeyPairSync( + type: "x25519", + options?: T, + ): KeyPairExportResult; + function generateKeyPairSync( + type: "x448", + options?: T, + ): KeyPairExportResult; + /** + * Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC, + * Ed25519, Ed448, X25519, X448, and DH are currently supported. + * + * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function + * behaves as if `keyObject.export()` had been called on its result. Otherwise, + * the respective part of the key is returned as a `KeyObject`. + * + * It is recommended to encode public keys as `'spki'` and private keys as `'pkcs8'` with encryption for long-term storage: + * + * ```js + * const { + * generateKeyPair, + * } = await import('node:crypto'); + * + * generateKeyPair('rsa', { + * modulusLength: 4096, + * publicKeyEncoding: { + * type: 'spki', + * format: 'pem', + * }, + * privateKeyEncoding: { + * type: 'pkcs8', + * format: 'pem', + * cipher: 'aes-256-cbc', + * passphrase: 'top secret', + * }, + * }, (err, publicKey, privateKey) => { + * // Handle errors and use the generated key pair. + * }); + * ``` + * + * On completion, `callback` will be called with `err` set to `undefined` and `publicKey` / `privateKey` representing the generated key pair. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `publicKey` and `privateKey` properties. + * @since v10.12.0 + * @param type The asymmetric key type to generate. See the + * supported [asymmetric key types](https://nodejs.org/docs/latest-v25.x/api/crypto.html#asymmetric-key-types). + */ + function generateKeyPair( + type: "dh", + options: T, + callback: KeyPairExportCallback, + ): void; + function generateKeyPair( + type: "dsa", + options: T, + callback: KeyPairExportCallback, + ): void; + function generateKeyPair( + type: "ec", + options: T, + callback: KeyPairExportCallback, + ): void; + function generateKeyPair( + type: "ed25519", + options: T | undefined, + callback: KeyPairExportCallback, + ): void; + function generateKeyPair( + type: "ed448", + options: T | undefined, + callback: KeyPairExportCallback, + ): void; + function generateKeyPair( + type: MLDSAKeyType, + options: T | undefined, + callback: KeyPairExportCallback, + ): void; + function generateKeyPair( + type: MLKEMKeyType, + options: T | undefined, + callback: KeyPairExportCallback, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: T, + callback: KeyPairExportCallback, + ): void; + function generateKeyPair( + type: "rsa", + options: T, + callback: KeyPairExportCallback, + ): void; + function generateKeyPair( + type: SLHDSAKeyType, + options: T | undefined, + callback: KeyPairExportCallback, + ): void; + function generateKeyPair( + type: "x25519", + options: T | undefined, + callback: KeyPairExportCallback, + ): void; + function generateKeyPair( + type: "x448", + options: T | undefined, + callback: KeyPairExportCallback, + ): void; + namespace generateKeyPair { + function __promisify__( + type: "dh", + options: T, + ): Promise>; + function __promisify__( + type: "dsa", + options: T, + ): Promise>; + function __promisify__( + type: "ec", + options: T, + ): Promise>; + function __promisify__( + type: "ed25519", + options?: T, + ): Promise>; + function __promisify__( + type: "ed448", + options?: T, + ): Promise>; + function __promisify__( + type: MLDSAKeyType, + options?: T, + ): Promise>; + function __promisify__( + type: MLKEMKeyType, + options?: T, + ): Promise>; + function __promisify__( + type: "rsa-pss", + options: T, + ): Promise>; + function __promisify__( + type: "rsa", + options: T, + ): Promise>; + function __promisify__( + type: SLHDSAKeyType, + options?: T, + ): Promise>; + function __promisify__( + type: "x25519", + options?: T, + ): Promise>; + function __promisify__( + type: "x448", + options?: T, + ): Promise>; + } + /** + * Calculates and returns the signature for `data` using the given private key and + * algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is + * dependent upon the key type. + * + * `algorithm` is required to be `null` or `undefined` for Ed25519, Ed448, and + * ML-DSA. + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to {@link createPrivateKey}. If it is an object, the following + * additional properties can be passed: + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v12.0.0 + */ + function sign( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput, + ): NonSharedBuffer; + function sign( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput, + callback: (error: Error | null, data: NonSharedBuffer) => void, + ): void; + /** + * Verifies the given signature for `data` using the given key and algorithm. If + * `algorithm` is `null` or `undefined`, then the algorithm is dependent upon the + * key type. + * + * `algorithm` is required to be `null` or `undefined` for Ed25519, Ed448, and + * ML-DSA. + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to {@link createPublicKey}. If it is an object, the following + * additional properties can be passed: + * + * The `signature` argument is the previously calculated signature for the `data`. + * + * Because public keys can be derived from private keys, a private key or a public + * key may be passed for `key`. + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v12.0.0 + */ + function verify( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: NodeJS.ArrayBufferView, + ): boolean; + function verify( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: NodeJS.ArrayBufferView, + callback: (error: Error | null, result: boolean) => void, + ): void; + /** + * Key decapsulation using a KEM algorithm with a private key. + * + * Supported key types and their KEM algorithms are: + * + * * `'rsa'` RSA Secret Value Encapsulation + * * `'ec'` DHKEM(P-256, HKDF-SHA256), DHKEM(P-384, HKDF-SHA256), DHKEM(P-521, HKDF-SHA256) + * * `'x25519'` DHKEM(X25519, HKDF-SHA256) + * * `'x448'` DHKEM(X448, HKDF-SHA512) + * * `'ml-kem-512'` ML-KEM + * * `'ml-kem-768'` ML-KEM + * * `'ml-kem-1024'` ML-KEM + * + * If `key` is not a {@link KeyObject}, this function behaves as if `key` had been + * passed to `crypto.createPrivateKey()`. + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v24.7.0 + */ + function decapsulate( + key: KeyLike | PrivateKeyInput | JsonWebKeyInput, + ciphertext: ArrayBuffer | NodeJS.ArrayBufferView, + ): NonSharedBuffer; + function decapsulate( + key: KeyLike | PrivateKeyInput | JsonWebKeyInput, + ciphertext: ArrayBuffer | NodeJS.ArrayBufferView, + callback: (err: Error, sharedKey: NonSharedBuffer) => void, + ): void; + /** + * Computes the Diffie-Hellman shared secret based on a `privateKey` and a `publicKey`. + * Both keys must have the same `asymmetricKeyType` and must support either the DH or + * ECDH operation. + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v13.9.0, v12.17.0 + */ + function diffieHellman(options: { privateKey: KeyObject; publicKey: KeyObject }): NonSharedBuffer; + function diffieHellman( + options: { privateKey: KeyObject; publicKey: KeyObject }, + callback: (err: Error | null, secret: NonSharedBuffer) => void, + ): void; + /** + * Key encapsulation using a KEM algorithm with a public key. + * + * Supported key types and their KEM algorithms are: + * + * * `'rsa'` RSA Secret Value Encapsulation + * * `'ec'` DHKEM(P-256, HKDF-SHA256), DHKEM(P-384, HKDF-SHA256), DHKEM(P-521, HKDF-SHA256) + * * `'x25519'` DHKEM(X25519, HKDF-SHA256) + * * `'x448'` DHKEM(X448, HKDF-SHA512) + * * `'ml-kem-512'` ML-KEM + * * `'ml-kem-768'` ML-KEM + * * `'ml-kem-1024'` ML-KEM + * + * If `key` is not a {@link KeyObject}, this function behaves as if `key` had been + * passed to `crypto.createPublicKey()`. + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v24.7.0 + */ + function encapsulate( + key: KeyLike | PublicKeyInput | JsonWebKeyInput, + ): { sharedKey: NonSharedBuffer; ciphertext: NonSharedBuffer }; + function encapsulate( + key: KeyLike | PublicKeyInput | JsonWebKeyInput, + callback: (err: Error, result: { sharedKey: NonSharedBuffer; ciphertext: NonSharedBuffer }) => void, + ): void; + interface OneShotDigestOptions { + /** + * Encoding used to encode the returned digest. + * @default 'hex' + */ + outputEncoding?: BinaryToTextEncoding | "buffer" | undefined; + /** + * For XOF hash functions such as 'shake256', the outputLength option + * can be used to specify the desired output length in bytes. + */ + outputLength?: number | undefined; + } + interface OneShotDigestOptionsWithStringEncoding extends OneShotDigestOptions { + outputEncoding?: BinaryToTextEncoding | undefined; + } + interface OneShotDigestOptionsWithBufferEncoding extends OneShotDigestOptions { + outputEncoding: "buffer"; + } + /** + * A utility for creating one-shot hash digests of data. It can be faster than + * the object-based `crypto.createHash()` when hashing a smaller amount of data + * (<= 5MB) that's readily available. If the data can be big or if it is streamed, + * it's still recommended to use `crypto.createHash()` instead. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms` will + * display the available digest algorithms. + * + * If `options` is a string, then it specifies the `outputEncoding`. + * + * Example: + * + * ```js + * import crypto from 'node:crypto'; + * import { Buffer } from 'node:buffer'; + * + * // Hashing a string and return the result as a hex-encoded string. + * const string = 'Node.js'; + * // 10b3493287f831e81a438811a1ffba01f8cec4b7 + * console.log(crypto.hash('sha1', string)); + * + * // Encode a base64-encoded string into a Buffer, hash it and return + * // the result as a buffer. + * const base64 = 'Tm9kZS5qcw=='; + * // + * console.log(crypto.hash('sha1', Buffer.from(base64, 'base64'), 'buffer')); + * ``` + * @since v21.7.0, v20.12.0 + * @param data When `data` is a string, it will be encoded as UTF-8 before being hashed. If a different + * input encoding is desired for a string input, user could encode the string + * into a `TypedArray` using either `TextEncoder` or `Buffer.from()` and passing + * the encoded `TypedArray` into this API instead. + */ + function hash( + algorithm: string, + data: BinaryLike, + options?: OneShotDigestOptionsWithStringEncoding | BinaryToTextEncoding, + ): string; + function hash( + algorithm: string, + data: BinaryLike, + options: OneShotDigestOptionsWithBufferEncoding | "buffer", + ): NonSharedBuffer; + function hash( + algorithm: string, + data: BinaryLike, + options: OneShotDigestOptions | BinaryToTextEncoding | "buffer", + ): string | NonSharedBuffer; + type CipherMode = "cbc" | "ccm" | "cfb" | "ctr" | "ecb" | "gcm" | "ocb" | "ofb" | "stream" | "wrap" | "xts"; + interface CipherInfoOptions { + /** + * A test key length. + */ + keyLength?: number | undefined; + /** + * A test IV length. + */ + ivLength?: number | undefined; + } + interface CipherInfo { + /** + * The name of the cipher. + */ + name: string; + /** + * The nid of the cipher. + */ + nid: number; + /** + * The block size of the cipher in bytes. + * This property is omitted when mode is 'stream'. + */ + blockSize?: number | undefined; + /** + * The expected or default initialization vector length in bytes. + * This property is omitted if the cipher does not use an initialization vector. + */ + ivLength?: number | undefined; + /** + * The expected or default key length in bytes. + */ + keyLength: number; + /** + * The cipher mode. + */ + mode: CipherMode; + } + /** + * Returns information about a given cipher. + * + * Some ciphers accept variable length keys and initialization vectors. By default, + * the `crypto.getCipherInfo()` method will return the default values for these + * ciphers. To test if a given key length or iv length is acceptable for given + * cipher, use the `keyLength` and `ivLength` options. If the given values are + * unacceptable, `undefined` will be returned. + * @since v15.0.0 + * @param nameOrNid The name or nid of the cipher to query. + */ + function getCipherInfo(nameOrNid: string | number, options?: CipherInfoOptions): CipherInfo | undefined; + /** + * HKDF is a simple key derivation function defined in RFC 5869\. The given `ikm`, `salt` and `info` are used with the `digest` to derive a key of `keylen` bytes. + * + * The supplied `callback` function is called with two arguments: `err` and `derivedKey`. If an errors occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. The successfully generated `derivedKey` will + * be passed to the callback as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). An error will be thrown if any + * of the input arguments specify invalid values or types. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * hkdf, + * } = await import('node:crypto'); + * + * hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => { + * if (err) throw err; + * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' + * }); + * ``` + * @since v15.0.0 + * @param digest The digest algorithm to use. + * @param ikm The input keying material. Must be provided but can be zero-length. + * @param salt The salt value. Must be provided but can be zero-length. + * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. + * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` + * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). + */ + function hkdf( + digest: string, + irm: BinaryLike | KeyObject, + salt: BinaryLike, + info: BinaryLike, + keylen: number, + callback: (err: Error | null, derivedKey: ArrayBuffer) => void, + ): void; + /** + * Provides a synchronous HKDF key derivation function as defined in RFC 5869\. The + * given `ikm`, `salt` and `info` are used with the `digest` to derive a key of `keylen` bytes. + * + * The successfully generated `derivedKey` will be returned as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). + * + * An error will be thrown if any of the input arguments specify invalid values or + * types, or if the derived key cannot be generated. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * hkdfSync, + * } = await import('node:crypto'); + * + * const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64); + * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' + * ``` + * @since v15.0.0 + * @param digest The digest algorithm to use. + * @param ikm The input keying material. Must be provided but can be zero-length. + * @param salt The salt value. Must be provided but can be zero-length. + * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. + * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` + * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). + */ + function hkdfSync( + digest: string, + ikm: BinaryLike | KeyObject, + salt: BinaryLike, + info: BinaryLike, + keylen: number, + ): ArrayBuffer; + interface SecureHeapUsage { + /** + * The total allocated secure heap size as specified using the `--secure-heap=n` command-line flag. + */ + total: number; + /** + * The minimum allocation from the secure heap as specified using the `--secure-heap-min` command-line flag. + */ + min: number; + /** + * The total number of bytes currently allocated from the secure heap. + */ + used: number; + /** + * The calculated ratio of `used` to `total` allocated bytes. + */ + utilization: number; + } + /** + * @since v15.6.0 + */ + function secureHeapUsed(): SecureHeapUsage; + interface RandomUUIDOptions { + /** + * By default, to improve performance, + * Node.js will pre-emptively generate and persistently cache enough + * random data to generate up to 128 random UUIDs. To generate a UUID + * without using the cache, set `disableEntropyCache` to `true`. + * + * @default `false` + */ + disableEntropyCache?: boolean | undefined; + } + type UUID = `${string}-${string}-${string}-${string}-${string}`; + /** + * Generates a random [RFC 4122](https://www.rfc-editor.org/rfc/rfc4122.txt) version 4 UUID. The UUID is generated using a + * cryptographic pseudorandom number generator. + * @since v15.6.0, v14.17.0 + */ + function randomUUID(options?: RandomUUIDOptions): UUID; + interface X509CheckOptions { + /** + * @default 'always' + */ + subject?: "always" | "default" | "never" | undefined; + /** + * @default true + */ + wildcards?: boolean | undefined; + /** + * @default true + */ + partialWildcards?: boolean | undefined; + /** + * @default false + */ + multiLabelWildcards?: boolean | undefined; + /** + * @default false + */ + singleLabelSubdomains?: boolean | undefined; + } + /** + * Encapsulates an X509 certificate and provides read-only access to + * its information. + * + * ```js + * const { X509Certificate } = await import('node:crypto'); + * + * const x509 = new X509Certificate('{... pem encoded cert ...}'); + * + * console.log(x509.subject); + * ``` + * @since v15.6.0 + */ + class X509Certificate { + /** + * Will be \`true\` if this is a Certificate Authority (CA) certificate. + * @since v15.6.0 + */ + readonly ca: boolean; + /** + * The SHA-1 fingerprint of this certificate. + * + * Because SHA-1 is cryptographically broken and because the security of SHA-1 is + * significantly worse than that of algorithms that are commonly used to sign + * certificates, consider using `x509.fingerprint256` instead. + * @since v15.6.0 + */ + readonly fingerprint: string; + /** + * The SHA-256 fingerprint of this certificate. + * @since v15.6.0 + */ + readonly fingerprint256: string; + /** + * The SHA-512 fingerprint of this certificate. + * + * Because computing the SHA-256 fingerprint is usually faster and because it is + * only half the size of the SHA-512 fingerprint, `x509.fingerprint256` may be + * a better choice. While SHA-512 presumably provides a higher level of security in + * general, the security of SHA-256 matches that of most algorithms that are + * commonly used to sign certificates. + * @since v17.2.0, v16.14.0 + */ + readonly fingerprint512: string; + /** + * The complete subject of this certificate. + * @since v15.6.0 + */ + readonly subject: string; + /** + * The subject alternative name specified for this certificate. + * + * This is a comma-separated list of subject alternative names. Each entry begins + * with a string identifying the kind of the subject alternative name followed by + * a colon and the value associated with the entry. + * + * Earlier versions of Node.js incorrectly assumed that it is safe to split this + * property at the two-character sequence `', '` (see [CVE-2021-44532](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44532)). However, + * both malicious and legitimate certificates can contain subject alternative names + * that include this sequence when represented as a string. + * + * After the prefix denoting the type of the entry, the remainder of each entry + * might be enclosed in quotes to indicate that the value is a JSON string literal. + * For backward compatibility, Node.js only uses JSON string literals within this + * property when necessary to avoid ambiguity. Third-party code should be prepared + * to handle both possible entry formats. + * @since v15.6.0 + */ + readonly subjectAltName: string | undefined; + /** + * A textual representation of the certificate's authority information access + * extension. + * + * This is a line feed separated list of access descriptions. Each line begins with + * the access method and the kind of the access location, followed by a colon and + * the value associated with the access location. + * + * After the prefix denoting the access method and the kind of the access location, + * the remainder of each line might be enclosed in quotes to indicate that the + * value is a JSON string literal. For backward compatibility, Node.js only uses + * JSON string literals within this property when necessary to avoid ambiguity. + * Third-party code should be prepared to handle both possible entry formats. + * @since v15.6.0 + */ + readonly infoAccess: string | undefined; + /** + * An array detailing the key usages for this certificate. + * @since v15.6.0 + */ + readonly keyUsage: string[]; + /** + * The issuer identification included in this certificate. + * @since v15.6.0 + */ + readonly issuer: string; + /** + * The issuer certificate or `undefined` if the issuer certificate is not + * available. + * @since v15.9.0 + */ + readonly issuerCertificate: X509Certificate | undefined; + /** + * The public key `KeyObject` for this certificate. + * @since v15.6.0 + */ + readonly publicKey: KeyObject; + /** + * A `Buffer` containing the DER encoding of this certificate. + * @since v15.6.0 + */ + readonly raw: NonSharedBuffer; + /** + * The serial number of this certificate. + * + * Serial numbers are assigned by certificate authorities and do not uniquely + * identify certificates. Consider using `x509.fingerprint256` as a unique + * identifier instead. + * @since v15.6.0 + */ + readonly serialNumber: string; + /** + * The algorithm used to sign the certificate or `undefined` if the signature algorithm is unknown by OpenSSL. + * @since v24.9.0 + */ + readonly signatureAlgorithm: string | undefined; + /** + * The OID of the algorithm used to sign the certificate. + * @since v24.9.0 + */ + readonly signatureAlgorithmOid: string; + /** + * The date/time from which this certificate is considered valid. + * @since v15.6.0 + */ + readonly validFrom: string; + /** + * The date/time from which this certificate is valid, encapsulated in a `Date` object. + * @since v22.10.0 + */ + readonly validFromDate: Date; + /** + * The date/time until which this certificate is considered valid. + * @since v15.6.0 + */ + readonly validTo: string; + /** + * The date/time until which this certificate is valid, encapsulated in a `Date` object. + * @since v22.10.0 + */ + readonly validToDate: Date; + constructor(buffer: BinaryLike); + /** + * Checks whether the certificate matches the given email address. + * + * If the `'subject'` option is undefined or set to `'default'`, the certificate + * subject is only considered if the subject alternative name extension either does + * not exist or does not contain any email addresses. + * + * If the `'subject'` option is set to `'always'` and if the subject alternative + * name extension either does not exist or does not contain a matching email + * address, the certificate subject is considered. + * + * If the `'subject'` option is set to `'never'`, the certificate subject is never + * considered, even if the certificate contains no subject alternative names. + * @since v15.6.0 + * @return Returns `email` if the certificate matches, `undefined` if it does not. + */ + checkEmail(email: string, options?: Pick): string | undefined; + /** + * Checks whether the certificate matches the given host name. + * + * If the certificate matches the given host name, the matching subject name is + * returned. The returned name might be an exact match (e.g., `foo.example.com`) + * or it might contain wildcards (e.g., `*.example.com`). Because host name + * comparisons are case-insensitive, the returned subject name might also differ + * from the given `name` in capitalization. + * + * If the `'subject'` option is undefined or set to `'default'`, the certificate + * subject is only considered if the subject alternative name extension either does + * not exist or does not contain any DNS names. This behavior is consistent with [RFC 2818](https://www.rfc-editor.org/rfc/rfc2818.txt) ("HTTP Over TLS"). + * + * If the `'subject'` option is set to `'always'` and if the subject alternative + * name extension either does not exist or does not contain a matching DNS name, + * the certificate subject is considered. + * + * If the `'subject'` option is set to `'never'`, the certificate subject is never + * considered, even if the certificate contains no subject alternative names. + * @since v15.6.0 + * @return Returns a subject name that matches `name`, or `undefined` if no subject name matches `name`. + */ + checkHost(name: string, options?: X509CheckOptions): string | undefined; + /** + * Checks whether the certificate matches the given IP address (IPv4 or IPv6). + * + * Only [RFC 5280](https://www.rfc-editor.org/rfc/rfc5280.txt) `iPAddress` subject alternative names are considered, and they + * must match the given `ip` address exactly. Other subject alternative names as + * well as the subject field of the certificate are ignored. + * @since v15.6.0 + * @return Returns `ip` if the certificate matches, `undefined` if it does not. + */ + checkIP(ip: string): string | undefined; + /** + * Checks whether this certificate was potentially issued by the given `otherCert` + * by comparing the certificate metadata. + * + * This is useful for pruning a list of possible issuer certificates which have been + * selected using a more rudimentary filtering routine, i.e. just based on subject + * and issuer names. + * + * Finally, to verify that this certificate's signature was produced by a private key + * corresponding to `otherCert`'s public key use `x509.verify(publicKey)` + * with `otherCert`'s public key represented as a `KeyObject` + * like so + * + * ```js + * if (!x509.verify(otherCert.publicKey)) { + * throw new Error('otherCert did not issue x509'); + * } + * ``` + * @since v15.6.0 + */ + checkIssued(otherCert: X509Certificate): boolean; + /** + * Checks whether the public key for this certificate is consistent with + * the given private key. + * @since v15.6.0 + * @param privateKey A private key. + */ + checkPrivateKey(privateKey: KeyObject): boolean; + /** + * There is no standard JSON encoding for X509 certificates. The`toJSON()` method returns a string containing the PEM encoded + * certificate. + * @since v15.6.0 + */ + toJSON(): string; + /** + * Returns information about this certificate using the legacy `certificate object` encoding. + * @since v15.6.0 + */ + toLegacyObject(): PeerCertificate; + /** + * Returns the PEM-encoded certificate. + * @since v15.6.0 + */ + toString(): string; + /** + * Verifies that this certificate was signed by the given public key. + * Does not perform any other validation checks on the certificate. + * @since v15.6.0 + * @param publicKey A public key. + */ + verify(publicKey: KeyObject): boolean; + } + type LargeNumberLike = NodeJS.ArrayBufferView | SharedArrayBuffer | ArrayBuffer | bigint; + interface GeneratePrimeOptions { + add?: LargeNumberLike | undefined; + rem?: LargeNumberLike | undefined; + /** + * @default false + */ + safe?: boolean | undefined; + bigint?: boolean | undefined; + } + interface GeneratePrimeOptionsBigInt extends GeneratePrimeOptions { + bigint: true; + } + interface GeneratePrimeOptionsArrayBuffer extends GeneratePrimeOptions { + bigint?: false | undefined; + } + /** + * Generates a pseudorandom prime of `size` bits. + * + * If `options.safe` is `true`, the prime will be a safe prime -- that is, `(prime - 1) / 2` will also be a prime. + * + * The `options.add` and `options.rem` parameters can be used to enforce additional + * requirements, e.g., for Diffie-Hellman: + * + * * If `options.add` and `options.rem` are both set, the prime will satisfy the + * condition that `prime % add = rem`. + * * If only `options.add` is set and `options.safe` is not `true`, the prime will + * satisfy the condition that `prime % add = 1`. + * * If only `options.add` is set and `options.safe` is set to `true`, the prime + * will instead satisfy the condition that `prime % add = 3`. This is necessary + * because `prime % add = 1` for `options.add > 2` would contradict the condition + * enforced by `options.safe`. + * * `options.rem` is ignored if `options.add` is not given. + * + * Both `options.add` and `options.rem` must be encoded as big-endian sequences + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or `DataView`. + * + * By default, the prime is encoded as a big-endian sequence of octets + * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided. + * @since v15.8.0 + * @param size The size (in bits) of the prime to generate. + */ + function generatePrime(size: number, callback: (err: Error | null, prime: ArrayBuffer) => void): void; + function generatePrime( + size: number, + options: GeneratePrimeOptionsBigInt, + callback: (err: Error | null, prime: bigint) => void, + ): void; + function generatePrime( + size: number, + options: GeneratePrimeOptionsArrayBuffer, + callback: (err: Error | null, prime: ArrayBuffer) => void, + ): void; + function generatePrime( + size: number, + options: GeneratePrimeOptions, + callback: (err: Error | null, prime: ArrayBuffer | bigint) => void, + ): void; + /** + * Generates a pseudorandom prime of `size` bits. + * + * If `options.safe` is `true`, the prime will be a safe prime -- that is, `(prime - 1) / 2` will also be a prime. + * + * The `options.add` and `options.rem` parameters can be used to enforce additional + * requirements, e.g., for Diffie-Hellman: + * + * * If `options.add` and `options.rem` are both set, the prime will satisfy the + * condition that `prime % add = rem`. + * * If only `options.add` is set and `options.safe` is not `true`, the prime will + * satisfy the condition that `prime % add = 1`. + * * If only `options.add` is set and `options.safe` is set to `true`, the prime + * will instead satisfy the condition that `prime % add = 3`. This is necessary + * because `prime % add = 1` for `options.add > 2` would contradict the condition + * enforced by `options.safe`. + * * `options.rem` is ignored if `options.add` is not given. + * + * Both `options.add` and `options.rem` must be encoded as big-endian sequences + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or `DataView`. + * + * By default, the prime is encoded as a big-endian sequence of octets + * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided. + * @since v15.8.0 + * @param size The size (in bits) of the prime to generate. + */ + function generatePrimeSync(size: number): ArrayBuffer; + function generatePrimeSync(size: number, options: GeneratePrimeOptionsBigInt): bigint; + function generatePrimeSync(size: number, options: GeneratePrimeOptionsArrayBuffer): ArrayBuffer; + function generatePrimeSync(size: number, options: GeneratePrimeOptions): ArrayBuffer | bigint; + interface CheckPrimeOptions { + /** + * The number of Miller-Rabin probabilistic primality iterations to perform. + * When the value is 0 (zero), a number of checks is used that yields a false positive rate of at most `2**-64` for random input. + * Care must be used when selecting a number of checks. + * Refer to the OpenSSL documentation for the BN_is_prime_ex function nchecks options for more details. + * + * @default 0 + */ + checks?: number | undefined; + } + /** + * Checks the primality of the `candidate`. + * @since v15.8.0 + * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. + */ + function checkPrime(value: LargeNumberLike, callback: (err: Error | null, result: boolean) => void): void; + function checkPrime( + value: LargeNumberLike, + options: CheckPrimeOptions, + callback: (err: Error | null, result: boolean) => void, + ): void; + /** + * Checks the primality of the `candidate`. + * @since v15.8.0 + * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. + * @return `true` if the candidate is a prime with an error probability less than `0.25 ** options.checks`. + */ + function checkPrimeSync(candidate: LargeNumberLike, options?: CheckPrimeOptions): boolean; + /** + * Load and set the `engine` for some or all OpenSSL functions (selected by flags). + * + * `engine` could be either an id or a path to the engine's shared library. + * + * The optional `flags` argument uses `ENGINE_METHOD_ALL` by default. The `flags` is a bit field taking one of or a mix of the following flags (defined in `crypto.constants`): + * + * * `crypto.constants.ENGINE_METHOD_RSA` + * * `crypto.constants.ENGINE_METHOD_DSA` + * * `crypto.constants.ENGINE_METHOD_DH` + * * `crypto.constants.ENGINE_METHOD_RAND` + * * `crypto.constants.ENGINE_METHOD_EC` + * * `crypto.constants.ENGINE_METHOD_CIPHERS` + * * `crypto.constants.ENGINE_METHOD_DIGESTS` + * * `crypto.constants.ENGINE_METHOD_PKEY_METHS` + * * `crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS` + * * `crypto.constants.ENGINE_METHOD_ALL` + * * `crypto.constants.ENGINE_METHOD_NONE` + * @since v0.11.11 + * @param flags + */ + function setEngine(engine: string, flags?: number): void; + /** + * A convenient alias for {@link webcrypto.getRandomValues}. This + * implementation is not compliant with the Web Crypto spec, to write + * web-compatible code use {@link webcrypto.getRandomValues} instead. + * @since v17.4.0 + * @return Returns `typedArray`. + */ + function getRandomValues< + T extends Exclude< + NodeJS.NonSharedTypedArray, + NodeJS.NonSharedFloat16Array | NodeJS.NonSharedFloat32Array | NodeJS.NonSharedFloat64Array + >, + >(typedArray: T): T; + type Argon2Algorithm = "argon2d" | "argon2i" | "argon2id"; + interface Argon2Parameters { + /** + * REQUIRED, this is the password for password hashing applications of Argon2. + */ + message: string | ArrayBuffer | NodeJS.ArrayBufferView; + /** + * REQUIRED, must be at least 8 bytes long. This is the salt for password hashing applications of Argon2. + */ + nonce: string | ArrayBuffer | NodeJS.ArrayBufferView; + /** + * REQUIRED, degree of parallelism determines how many computational chains (lanes) + * can be run. Must be greater than 1 and less than `2**24-1`. + */ + parallelism: number; + /** + * REQUIRED, the length of the key to generate. Must be greater than 4 and + * less than `2**32-1`. + */ + tagLength: number; + /** + * REQUIRED, memory cost in 1KiB blocks. Must be greater than + * `8 * parallelism` and less than `2**32-1`. The actual number of blocks is rounded + * down to the nearest multiple of `4 * parallelism`. + */ + memory: number; + /** + * REQUIRED, number of passes (iterations). Must be greater than 1 and less + * than `2**32-1`. + */ + passes: number; + /** + * OPTIONAL, Random additional input, + * similar to the salt, that should **NOT** be stored with the derived key. This is known as pepper in + * password hashing applications. If used, must have a length not greater than `2**32-1` bytes. + */ + secret?: string | ArrayBuffer | NodeJS.ArrayBufferView | undefined; + /** + * OPTIONAL, Additional data to + * be added to the hash, functionally equivalent to salt or secret, but meant for + * non-random data. If used, must have a length not greater than `2**32-1` bytes. + */ + associatedData?: string | ArrayBuffer | NodeJS.ArrayBufferView | undefined; + } + /** + * Provides an asynchronous [Argon2](https://www.rfc-editor.org/rfc/rfc9106.html) implementation. Argon2 is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `nonce` should be as unique as possible. It is recommended that a nonce is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `message`, `nonce`, `secret` or `associatedData`, please + * consider [caveats when using strings as inputs to cryptographic APIs](https://nodejs.org/docs/latest-v25.x/api/crypto.html#using-strings-as-inputs-to-cryptographic-apis). + * + * The `callback` function is called with two arguments: `err` and `derivedKey`. + * `err` is an exception object when key derivation fails, otherwise `err` is + * `null`. `derivedKey` is passed to the callback as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { argon2, randomBytes } = await import('node:crypto'); + * + * const parameters = { + * message: 'password', + * nonce: randomBytes(16), + * parallelism: 4, + * tagLength: 64, + * memory: 65536, + * passes: 3, + * }; + * + * argon2('argon2id', parameters, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // 'af91dad...9520f15' + * }); + * ``` + * @since v24.7.0 + * @param algorithm Variant of Argon2, one of `"argon2d"`, `"argon2i"` or `"argon2id"`. + * @experimental + */ + function argon2( + algorithm: Argon2Algorithm, + parameters: Argon2Parameters, + callback: (err: Error | null, derivedKey: NonSharedBuffer) => void, + ): void; + /** + * Provides a synchronous [Argon2][] implementation. Argon2 is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `nonce` should be as unique as possible. It is recommended that a nonce is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `message`, `nonce`, `secret` or `associatedData`, please + * consider [caveats when using strings as inputs to cryptographic APIs](https://nodejs.org/docs/latest-v25.x/api/crypto.html#using-strings-as-inputs-to-cryptographic-apis). + * + * An exception is thrown when key derivation fails, otherwise the derived key is + * returned as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { argon2Sync, randomBytes } = await import('node:crypto'); + * + * const parameters = { + * message: 'password', + * nonce: randomBytes(16), + * parallelism: 4, + * tagLength: 64, + * memory: 65536, + * passes: 3, + * }; + * + * const derivedKey = argon2Sync('argon2id', parameters); + * console.log(derivedKey.toString('hex')); // 'af91dad...9520f15' + * ``` + * @since v24.7.0 + * @experimental + */ + function argon2Sync(algorithm: Argon2Algorithm, parameters: Argon2Parameters): NonSharedBuffer; + /** + * A convenient alias for `crypto.webcrypto.subtle`. + * @since v17.4.0 + */ + const subtle: webcrypto.SubtleCrypto; + /** + * An implementation of the Web Crypto API standard. + * + * See the {@link https://nodejs.org/docs/latest/api/webcrypto.html Web Crypto API documentation} for details. + * @since v15.0.0 + */ + const webcrypto: webcrypto.Crypto; + namespace webcrypto { + type AlgorithmIdentifier = Algorithm | string; + type BigInteger = NodeJS.NonSharedUint8Array; + type KeyFormat = "jwk" | "pkcs8" | "raw" | "raw-public" | "raw-secret" | "raw-seed" | "spki"; + type KeyType = "private" | "public" | "secret"; + type KeyUsage = + | "decapsulateBits" + | "decapsulateKey" + | "decrypt" + | "deriveBits" + | "deriveKey" + | "encapsulateBits" + | "encapsulateKey" + | "encrypt" + | "sign" + | "unwrapKey" + | "verify" + | "wrapKey"; + type HashAlgorithmIdentifier = AlgorithmIdentifier; + type NamedCurve = string; + interface AeadParams extends Algorithm { + additionalData?: NodeJS.BufferSource; + iv: NodeJS.BufferSource; + tagLength: number; + } + interface AesCbcParams extends Algorithm { + iv: NodeJS.BufferSource; + } + interface AesCtrParams extends Algorithm { + counter: NodeJS.BufferSource; + length: number; + } + interface AesDerivedKeyParams extends Algorithm { + length: number; + } + interface AesKeyAlgorithm extends KeyAlgorithm { + length: number; + } + interface AesKeyGenParams extends Algorithm { + length: number; + } + interface Algorithm { + name: string; + } + interface Argon2Params extends Algorithm { + associatedData?: NodeJS.BufferSource; + memory: number; + nonce: NodeJS.BufferSource; + parallelism: number; + passes: number; + secretValue?: NodeJS.BufferSource; + version?: number; + } + interface CShakeParams extends Algorithm { + customization?: NodeJS.BufferSource; + functionName?: NodeJS.BufferSource; + length: number; + } + interface ContextParams extends Algorithm { + context?: NodeJS.BufferSource; + } + interface EcKeyAlgorithm extends KeyAlgorithm { + namedCurve: NamedCurve; + } + interface EcKeyGenParams extends Algorithm { + namedCurve: NamedCurve; + } + interface EcKeyImportParams extends Algorithm { + namedCurve: NamedCurve; + } + interface EcdhKeyDeriveParams extends Algorithm { + public: CryptoKey; + } + interface EcdsaParams extends Algorithm { + hash: HashAlgorithmIdentifier; + } + interface HkdfParams extends Algorithm { + hash: HashAlgorithmIdentifier; + info: NodeJS.BufferSource; + salt: NodeJS.BufferSource; + } + interface HmacImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; + } + interface HmacKeyAlgorithm extends KeyAlgorithm { + hash: KeyAlgorithm; + length: number; + } + interface HmacKeyGenParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; + } + interface JsonWebKey { + alg?: string; + crv?: string; + d?: string; + dp?: string; + dq?: string; + e?: string; + ext?: boolean; + k?: string; + key_ops?: string[]; + kty?: string; + n?: string; + oth?: RsaOtherPrimesInfo[]; + p?: string; + q?: string; + qi?: string; + use?: string; + x?: string; + y?: string; + } + interface KeyAlgorithm { + name: string; + } + interface KmacImportParams extends Algorithm { + length?: number; + } + interface KmacKeyAlgorithm extends KeyAlgorithm { + length: number; + } + interface KmacKeyGenParams extends Algorithm { + length?: number; + } + interface KmacParams extends Algorithm { + customization?: NodeJS.BufferSource; + length: number; + } + interface Pbkdf2Params extends Algorithm { + hash: HashAlgorithmIdentifier; + iterations: number; + salt: NodeJS.BufferSource; + } + interface RsaHashedImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; + } + interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm { + hash: KeyAlgorithm; + } + interface RsaHashedKeyGenParams extends RsaKeyGenParams { + hash: HashAlgorithmIdentifier; + } + interface RsaKeyAlgorithm extends KeyAlgorithm { + modulusLength: number; + publicExponent: BigInteger; + } + interface RsaKeyGenParams extends Algorithm { + modulusLength: number; + publicExponent: BigInteger; + } + interface RsaOaepParams extends Algorithm { + label?: NodeJS.BufferSource; + } + interface RsaOtherPrimesInfo { + d?: string; + r?: string; + t?: string; + } + interface RsaPssParams extends Algorithm { + saltLength: number; + } + interface Crypto { + readonly subtle: SubtleCrypto; + getRandomValues< + T extends Exclude< + NodeJS.NonSharedTypedArray, + NodeJS.NonSharedFloat16Array | NodeJS.NonSharedFloat32Array | NodeJS.NonSharedFloat64Array + >, + >( + typedArray: T, + ): T; + randomUUID(): UUID; + } + interface CryptoKey { + readonly algorithm: KeyAlgorithm; + readonly extractable: boolean; + readonly type: KeyType; + readonly usages: KeyUsage[]; + } + interface CryptoKeyPair { + privateKey: CryptoKey; + publicKey: CryptoKey; + } + interface EncapsulatedBits { + sharedKey: ArrayBuffer; + ciphertext: ArrayBuffer; + } + interface EncapsulatedKey { + sharedKey: CryptoKey; + ciphertext: ArrayBuffer; + } + interface SubtleCrypto { + decapsulateBits( + decapsulationAlgorithm: AlgorithmIdentifier, + decapsulationKey: CryptoKey, + ciphertext: NodeJS.BufferSource, + ): Promise; + decapsulateKey( + decapsulationAlgorithm: AlgorithmIdentifier, + decapsulationKey: CryptoKey, + ciphertext: NodeJS.BufferSource, + sharedKeyAlgorithm: AlgorithmIdentifier | HmacImportParams | AesDerivedKeyParams | KmacImportParams, + extractable: boolean, + usages: KeyUsage[], + ): Promise; + decrypt( + algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AeadParams, + key: CryptoKey, + data: NodeJS.BufferSource, + ): Promise; + deriveBits( + algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params | Argon2Params, + baseKey: CryptoKey, + length?: number | null, + ): Promise; + deriveKey( + algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params | Argon2Params, + baseKey: CryptoKey, + derivedKeyType: AlgorithmIdentifier | AesDerivedKeyParams | HmacImportParams | KmacImportParams, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + digest(algorithm: AlgorithmIdentifier | CShakeParams, data: NodeJS.BufferSource): Promise; + encapsulateBits( + encapsulationAlgorithm: AlgorithmIdentifier, + encapsulationKey: CryptoKey, + ): Promise; + encapsulateKey( + encapsulationAlgorithm: AlgorithmIdentifier, + encapsulationKey: CryptoKey, + sharedKeyAlgorithm: AlgorithmIdentifier | AesDerivedKeyParams | HmacImportParams | KmacImportParams, + extractable: boolean, + usages: KeyUsage[], + ): Promise; + encrypt( + algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AeadParams, + key: CryptoKey, + data: NodeJS.BufferSource, + ): Promise; + exportKey(format: "jwk", key: CryptoKey): Promise; + exportKey(format: Exclude, key: CryptoKey): Promise; + exportKey(format: KeyFormat, key: CryptoKey): Promise; + generateKey( + algorithm: RsaHashedKeyGenParams | EcKeyGenParams, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + generateKey( + algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params | KmacKeyGenParams, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + generateKey( + algorithm: AlgorithmIdentifier, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + getPublicKey(key: CryptoKey, keyUsages: KeyUsage[]): Promise; + importKey( + format: "jwk", + keyData: JsonWebKey, + algorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm + | KmacImportParams, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + importKey( + format: Exclude, + keyData: NodeJS.BufferSource, + algorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm + | KmacImportParams, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + sign( + algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | ContextParams | KmacParams, + key: CryptoKey, + data: NodeJS.BufferSource, + ): Promise; + unwrapKey( + format: KeyFormat, + wrappedKey: NodeJS.BufferSource, + unwrappingKey: CryptoKey, + unwrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AeadParams, + unwrappedKeyAlgorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm + | KmacImportParams, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + verify( + algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | ContextParams | KmacParams, + key: CryptoKey, + signature: NodeJS.BufferSource, + data: NodeJS.BufferSource, + ): Promise; + wrapKey( + format: KeyFormat, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AeadParams, + ): Promise; + } + } +} +declare module "crypto" { + export * from "node:crypto"; +} diff --git a/backend/node_modules/@types/node/dgram.d.ts b/backend/node_modules/@types/node/dgram.d.ts new file mode 100644 index 0000000..3672e08 --- /dev/null +++ b/backend/node_modules/@types/node/dgram.d.ts @@ -0,0 +1,564 @@ +/** + * The `node:dgram` module provides an implementation of UDP datagram sockets. + * + * ```js + * import dgram from 'node:dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.error(`server error:\n${err.stack}`); + * server.close(); + * }); + * + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * + * server.on('listening', () => { + * const address = server.address(); + * console.log(`server listening ${address.address}:${address.port}`); + * }); + * + * server.bind(41234); + * // Prints: server listening 0.0.0.0:41234 + * ``` + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/dgram.js) + */ +declare module "node:dgram" { + import { NonSharedBuffer } from "node:buffer"; + import * as dns from "node:dns"; + import { Abortable, EventEmitter, InternalEventEmitter } from "node:events"; + import { AddressInfo, BlockList } from "node:net"; + interface RemoteInfo { + address: string; + family: "IPv4" | "IPv6"; + port: number; + size: number; + } + interface BindOptions { + port?: number | undefined; + address?: string | undefined; + exclusive?: boolean | undefined; + fd?: number | undefined; + } + type SocketType = "udp4" | "udp6"; + interface SocketOptions extends Abortable { + type: SocketType; + reuseAddr?: boolean | undefined; + reusePort?: boolean | undefined; + /** + * @default false + */ + ipv6Only?: boolean | undefined; + recvBufferSize?: number | undefined; + sendBufferSize?: number | undefined; + lookup?: + | (( + hostname: string, + options: dns.LookupOneOptions, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ) => void) + | undefined; + receiveBlockList?: BlockList | undefined; + sendBlockList?: BlockList | undefined; + } + /** + * Creates a `dgram.Socket` object. Once the socket is created, calling `socket.bind()` will instruct the socket to begin listening for datagram + * messages. When `address` and `port` are not passed to `socket.bind()` the + * method will bind the socket to the "all interfaces" address on a random port + * (it does the right thing for both `udp4` and `udp6` sockets). The bound address + * and port can be retrieved using `socket.address().address` and `socket.address().port`. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.close()` on the socket: + * + * ```js + * const controller = new AbortController(); + * const { signal } = controller; + * const server = dgram.createSocket({ type: 'udp4', signal }); + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * // Later, when you want to close the server. + * controller.abort(); + * ``` + * @since v0.11.13 + * @param options Available options are: + * @param callback Attached as a listener for `'message'` events. Optional. + */ + function createSocket(type: SocketType, callback?: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): Socket; + function createSocket(options: SocketOptions, callback?: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): Socket; + interface SocketEventMap { + "close": []; + "connect": []; + "error": [err: Error]; + "listening": []; + "message": [msg: NonSharedBuffer, rinfo: RemoteInfo]; + } + /** + * Encapsulates the datagram functionality. + * + * New instances of `dgram.Socket` are created using {@link createSocket}. + * The `new` keyword is not to be used to create `dgram.Socket` instances. + * @since v0.1.99 + */ + class Socket implements EventEmitter { + /** + * Tells the kernel to join a multicast group at the given `multicastAddress` and `multicastInterface` using the `IP_ADD_MEMBERSHIP` socket option. If the `multicastInterface` argument is not + * specified, the operating system will choose + * one interface and will add membership to it. To add membership to every + * available interface, call `addMembership` multiple times, once per interface. + * + * When called on an unbound socket, this method will implicitly bind to a random + * port, listening on all interfaces. + * + * When sharing a UDP socket across multiple `cluster` workers, the`socket.addMembership()` function must be called only once or an`EADDRINUSE` error will occur: + * + * ```js + * import cluster from 'node:cluster'; + * import dgram from 'node:dgram'; + * + * if (cluster.isPrimary) { + * cluster.fork(); // Works ok. + * cluster.fork(); // Fails with EADDRINUSE. + * } else { + * const s = dgram.createSocket('udp4'); + * s.bind(1234, () => { + * s.addMembership('224.0.0.114'); + * }); + * } + * ``` + * @since v0.6.9 + */ + addMembership(multicastAddress: string, multicastInterface?: string): void; + /** + * Returns an object containing the address information for a socket. + * For UDP sockets, this object will contain `address`, `family`, and `port` properties. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.1.99 + */ + address(): AddressInfo; + /** + * For UDP sockets, causes the `dgram.Socket` to listen for datagram + * messages on a named `port` and optional `address`. If `port` is not + * specified or is `0`, the operating system will attempt to bind to a + * random port. If `address` is not specified, the operating system will + * attempt to listen on all addresses. Once binding is complete, a `'listening'` event is emitted and the optional `callback` function is + * called. + * + * Specifying both a `'listening'` event listener and passing a `callback` to the `socket.bind()` method is not harmful but not very + * useful. + * + * A bound datagram socket keeps the Node.js process running to receive + * datagram messages. + * + * If binding fails, an `'error'` event is generated. In rare case (e.g. + * attempting to bind with a closed socket), an `Error` may be thrown. + * + * Example of a UDP server listening on port 41234: + * + * ```js + * import dgram from 'node:dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.error(`server error:\n${err.stack}`); + * server.close(); + * }); + * + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * + * server.on('listening', () => { + * const address = server.address(); + * console.log(`server listening ${address.address}:${address.port}`); + * }); + * + * server.bind(41234); + * // Prints: server listening 0.0.0.0:41234 + * ``` + * @since v0.1.99 + * @param callback with no parameters. Called when binding is complete. + */ + bind(port?: number, address?: string, callback?: () => void): this; + bind(port?: number, callback?: () => void): this; + bind(callback?: () => void): this; + bind(options: BindOptions, callback?: () => void): this; + /** + * Close the underlying socket and stop listening for data on it. If a callback is + * provided, it is added as a listener for the `'close'` event. + * @since v0.1.99 + * @param callback Called when the socket has been closed. + */ + close(callback?: () => void): this; + /** + * Associates the `dgram.Socket` to a remote address and port. Every + * message sent by this handle is automatically sent to that destination. Also, + * the socket will only receive messages from that remote peer. + * Trying to call `connect()` on an already connected socket will result + * in an `ERR_SOCKET_DGRAM_IS_CONNECTED` exception. If `address` is not + * provided, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for `udp6` sockets) + * will be used by default. Once the connection is complete, a `'connect'` event + * is emitted and the optional `callback` function is called. In case of failure, + * the `callback` is called or, failing this, an `'error'` event is emitted. + * @since v12.0.0 + * @param callback Called when the connection is completed or on error. + */ + connect(port: number, address?: string, callback?: () => void): void; + connect(port: number, callback: () => void): void; + /** + * A synchronous function that disassociates a connected `dgram.Socket` from + * its remote address. Trying to call `disconnect()` on an unbound or already + * disconnected socket will result in an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception. + * @since v12.0.0 + */ + disconnect(): void; + /** + * Instructs the kernel to leave a multicast group at `multicastAddress` using the `IP_DROP_MEMBERSHIP` socket option. This method is automatically called by the + * kernel when the socket is closed or the process terminates, so most apps will + * never have reason to call this. + * + * If `multicastInterface` is not specified, the operating system will attempt to + * drop membership on all valid interfaces. + * @since v0.6.9 + */ + dropMembership(multicastAddress: string, multicastInterface?: string): void; + /** + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + * @return the `SO_RCVBUF` socket receive buffer size in bytes. + */ + getRecvBufferSize(): number; + /** + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + * @return the `SO_SNDBUF` socket send buffer size in bytes. + */ + getSendBufferSize(): number; + /** + * @since v18.8.0, v16.19.0 + * @return Number of bytes queued for sending. + */ + getSendQueueSize(): number; + /** + * @since v18.8.0, v16.19.0 + * @return Number of send requests currently in the queue awaiting to be processed. + */ + getSendQueueCount(): number; + /** + * By default, binding a socket will cause it to block the Node.js process from + * exiting as long as the socket is open. The `socket.unref()` method can be used + * to exclude the socket from the reference counting that keeps the Node.js + * process active. The `socket.ref()` method adds the socket back to the reference + * counting and restores the default behavior. + * + * Calling `socket.ref()` multiples times will have no additional effect. + * + * The `socket.ref()` method returns a reference to the socket so calls can be + * chained. + * @since v0.9.1 + */ + ref(): this; + /** + * Returns an object containing the `address`, `family`, and `port` of the remote + * endpoint. This method throws an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception + * if the socket is not connected. + * @since v12.0.0 + */ + remoteAddress(): AddressInfo; + /** + * Broadcasts a datagram on the socket. + * For connectionless sockets, the destination `port` and `address` must be + * specified. Connected sockets, on the other hand, will use their associated + * remote endpoint, so the `port` and `address` arguments must not be set. + * + * The `msg` argument contains the message to be sent. + * Depending on its type, different behavior can apply. If `msg` is a `Buffer`, + * any `TypedArray` or a `DataView`, + * the `offset` and `length` specify the offset within the `Buffer` where the + * message begins and the number of bytes in the message, respectively. + * If `msg` is a `String`, then it is automatically converted to a `Buffer` with `'utf8'` encoding. With messages that + * contain multi-byte characters, `offset` and `length` will be calculated with + * respect to `byte length` and not the character position. + * If `msg` is an array, `offset` and `length` must not be specified. + * + * The `address` argument is a string. If the value of `address` is a host name, + * DNS will be used to resolve the address of the host. If `address` is not + * provided or otherwise nullish, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for `udp6` sockets) will be used by default. + * + * If the socket has not been previously bound with a call to `bind`, the socket + * is assigned a random port number and is bound to the "all interfaces" address + * (`'0.0.0.0'` for `udp4` sockets, `'::0'` for `udp6` sockets.) + * + * An optional `callback` function may be specified to as a way of reporting + * DNS errors or for determining when it is safe to reuse the `buf` object. + * DNS lookups delay the time to send for at least one tick of the + * Node.js event loop. + * + * The only way to know for sure that the datagram has been sent is by using a `callback`. If an error occurs and a `callback` is given, the error will be + * passed as the first argument to the `callback`. If a `callback` is not given, + * the error is emitted as an `'error'` event on the `socket` object. + * + * Offset and length are optional but both _must_ be set if either are used. + * They are supported only when the first argument is a `Buffer`, a `TypedArray`, + * or a `DataView`. + * + * This method throws `ERR_SOCKET_BAD_PORT` if called on an unbound socket. + * + * Example of sending a UDP packet to a port on `localhost`; + * + * ```js + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; + * + * const message = Buffer.from('Some bytes'); + * const client = dgram.createSocket('udp4'); + * client.send(message, 41234, 'localhost', (err) => { + * client.close(); + * }); + * ``` + * + * Example of sending a UDP packet composed of multiple buffers to a port on`127.0.0.1`; + * + * ```js + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('Some '); + * const buf2 = Buffer.from('bytes'); + * const client = dgram.createSocket('udp4'); + * client.send([buf1, buf2], 41234, (err) => { + * client.close(); + * }); + * ``` + * + * Sending multiple buffers might be faster or slower depending on the + * application and operating system. Run benchmarks to + * determine the optimal strategy on a case-by-case basis. Generally speaking, + * however, sending multiple buffers is faster. + * + * Example of sending a UDP packet using a socket connected to a port on `localhost`: + * + * ```js + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; + * + * const message = Buffer.from('Some bytes'); + * const client = dgram.createSocket('udp4'); + * client.connect(41234, 'localhost', (err) => { + * client.send(message, (err) => { + * client.close(); + * }); + * }); + * ``` + * @since v0.1.99 + * @param msg Message to be sent. + * @param offset Offset in the buffer where the message starts. + * @param length Number of bytes in the message. + * @param port Destination port. + * @param address Destination host name or IP address. + * @param callback Called when the message has been sent. + */ + send( + msg: string | NodeJS.ArrayBufferView | readonly any[], + port?: number, + address?: string, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView | readonly any[], + port?: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView | readonly any[], + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView, + offset: number, + length: number, + port?: number, + address?: string, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView, + offset: number, + length: number, + port?: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView, + offset: number, + length: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + /** + * Sets or clears the `SO_BROADCAST` socket option. When set to `true`, UDP + * packets may be sent to a local interface's broadcast address. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.6.9 + */ + setBroadcast(flag: boolean): void; + /** + * _All references to scope in this section are referring to [IPv6 Zone Indices](https://en.wikipedia.org/wiki/IPv6_address#Scoped_literal_IPv6_addresses), which are defined by [RFC + * 4007](https://tools.ietf.org/html/rfc4007). In string form, an IP_ + * _with a scope index is written as `'IP%scope'` where scope is an interface name_ + * _or interface number._ + * + * Sets the default outgoing multicast interface of the socket to a chosen + * interface or back to system interface selection. The `multicastInterface` must + * be a valid string representation of an IP from the socket's family. + * + * For IPv4 sockets, this should be the IP configured for the desired physical + * interface. All packets sent to multicast on the socket will be sent on the + * interface determined by the most recent successful use of this call. + * + * For IPv6 sockets, `multicastInterface` should include a scope to indicate the + * interface as in the examples that follow. In IPv6, individual `send` calls can + * also use explicit scope in addresses, so only packets sent to a multicast + * address without specifying an explicit scope are affected by the most recent + * successful use of this call. + * + * This method throws `EBADF` if called on an unbound socket. + * + * #### Example: IPv6 outgoing multicast interface + * + * On most systems, where scope format uses the interface name: + * + * ```js + * const socket = dgram.createSocket('udp6'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('::%eth1'); + * }); + * ``` + * + * On Windows, where scope format uses an interface number: + * + * ```js + * const socket = dgram.createSocket('udp6'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('::%2'); + * }); + * ``` + * + * #### Example: IPv4 outgoing multicast interface + * + * All systems use an IP of the host on the desired physical interface: + * + * ```js + * const socket = dgram.createSocket('udp4'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('10.0.0.2'); + * }); + * ``` + * @since v8.6.0 + */ + setMulticastInterface(multicastInterface: string): void; + /** + * Sets or clears the `IP_MULTICAST_LOOP` socket option. When set to `true`, + * multicast packets will also be received on the local interface. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.3.8 + */ + setMulticastLoopback(flag: boolean): boolean; + /** + * Sets the `IP_MULTICAST_TTL` socket option. While TTL generally stands for + * "Time to Live", in this context it specifies the number of IP hops that a + * packet is allowed to travel through, specifically for multicast traffic. Each + * router or gateway that forwards a packet decrements the TTL. If the TTL is + * decremented to 0 by a router, it will not be forwarded. + * + * The `ttl` argument may be between 0 and 255\. The default on most systems is `1`. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.3.8 + */ + setMulticastTTL(ttl: number): number; + /** + * Sets the `SO_RCVBUF` socket option. Sets the maximum socket receive buffer + * in bytes. + * + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + */ + setRecvBufferSize(size: number): void; + /** + * Sets the `SO_SNDBUF` socket option. Sets the maximum socket send buffer + * in bytes. + * + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + */ + setSendBufferSize(size: number): void; + /** + * Sets the `IP_TTL` socket option. While TTL generally stands for "Time to Live", + * in this context it specifies the number of IP hops that a packet is allowed to + * travel through. Each router or gateway that forwards a packet decrements the + * TTL. If the TTL is decremented to 0 by a router, it will not be forwarded. + * Changing TTL values is typically done for network probes or when multicasting. + * + * The `ttl` argument may be between 1 and 255\. The default on most systems + * is 64. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.1.101 + */ + setTTL(ttl: number): number; + /** + * By default, binding a socket will cause it to block the Node.js process from + * exiting as long as the socket is open. The `socket.unref()` method can be used + * to exclude the socket from the reference counting that keeps the Node.js + * process active, allowing the process to exit even if the socket is still + * listening. + * + * Calling `socket.unref()` multiple times will have no additional effect. + * + * The `socket.unref()` method returns a reference to the socket so calls can be + * chained. + * @since v0.9.1 + */ + unref(): this; + /** + * Tells the kernel to join a source-specific multicast channel at the given `sourceAddress` and `groupAddress`, using the `multicastInterface` with the `IP_ADD_SOURCE_MEMBERSHIP` socket + * option. If the `multicastInterface` argument + * is not specified, the operating system will choose one interface and will add + * membership to it. To add membership to every available interface, call `socket.addSourceSpecificMembership()` multiple times, once per interface. + * + * When called on an unbound socket, this method will implicitly bind to a random + * port, listening on all interfaces. + * @since v13.1.0, v12.16.0 + */ + addSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; + /** + * Instructs the kernel to leave a source-specific multicast channel at the given `sourceAddress` and `groupAddress` using the `IP_DROP_SOURCE_MEMBERSHIP` socket option. This method is + * automatically called by the kernel when the + * socket is closed or the process terminates, so most apps will never have + * reason to call this. + * + * If `multicastInterface` is not specified, the operating system will attempt to + * drop membership on all valid interfaces. + * @since v13.1.0, v12.16.0 + */ + dropSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; + /** + * Calls `socket.close()` and returns a promise that fulfills when the socket has closed. + * @since v20.5.0 + */ + [Symbol.asyncDispose](): Promise; + } + interface Socket extends InternalEventEmitter {} +} +declare module "dgram" { + export * from "node:dgram"; +} diff --git a/backend/node_modules/@types/node/diagnostics_channel.d.ts b/backend/node_modules/@types/node/diagnostics_channel.d.ts new file mode 100644 index 0000000..206592b --- /dev/null +++ b/backend/node_modules/@types/node/diagnostics_channel.d.ts @@ -0,0 +1,576 @@ +/** + * The `node:diagnostics_channel` module provides an API to create named channels + * to report arbitrary message data for diagnostics purposes. + * + * It can be accessed using: + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * ``` + * + * It is intended that a module writer wanting to report diagnostics messages + * will create one or many top-level channels to report messages through. + * Channels may also be acquired at runtime but it is not encouraged + * due to the additional overhead of doing so. Channels may be exported for + * convenience, but as long as the name is known it can be acquired anywhere. + * + * If you intend for your module to produce diagnostics data for others to + * consume it is recommended that you include documentation of what named + * channels are used along with the shape of the message data. Channel names + * should generally include the module name to avoid collisions with data from + * other modules. + * @since v15.1.0, v14.17.0 + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/diagnostics_channel.js) + */ +declare module "node:diagnostics_channel" { + import { AsyncLocalStorage } from "node:async_hooks"; + /** + * Check if there are active subscribers to the named channel. This is helpful if + * the message you want to send might be expensive to prepare. + * + * This API is optional but helpful when trying to publish messages from very + * performance-sensitive code. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * if (diagnostics_channel.hasSubscribers('my-channel')) { + * // There are subscribers, prepare and publish message + * } + * ``` + * @since v15.1.0, v14.17.0 + * @param name The channel name + * @return If there are active subscribers + */ + function hasSubscribers(name: string | symbol): boolean; + /** + * This is the primary entry-point for anyone wanting to publish to a named + * channel. It produces a channel object which is optimized to reduce overhead at + * publish time as much as possible. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * ``` + * @since v15.1.0, v14.17.0 + * @param name The channel name + * @return The named channel object + */ + function channel(name: string | symbol): Channel; + type ChannelListener = (message: unknown, name: string | symbol) => void; + /** + * Register a message handler to subscribe to this channel. This message handler + * will be run synchronously whenever a message is published to the channel. Any + * errors thrown in the message handler will trigger an `'uncaughtException'`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * diagnostics_channel.subscribe('my-channel', (message, name) => { + * // Received data + * }); + * ``` + * @since v18.7.0, v16.17.0 + * @param name The channel name + * @param onMessage The handler to receive channel messages + */ + function subscribe(name: string | symbol, onMessage: ChannelListener): void; + /** + * Remove a message handler previously registered to this channel with {@link subscribe}. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * function onMessage(message, name) { + * // Received data + * } + * + * diagnostics_channel.subscribe('my-channel', onMessage); + * + * diagnostics_channel.unsubscribe('my-channel', onMessage); + * ``` + * @since v18.7.0, v16.17.0 + * @param name The channel name + * @param onMessage The previous subscribed handler to remove + * @return `true` if the handler was found, `false` otherwise. + */ + function unsubscribe(name: string | symbol, onMessage: ChannelListener): boolean; + /** + * Creates a `TracingChannel` wrapper for the given `TracingChannel Channels`. If a name is given, the corresponding tracing + * channels will be created in the form of `tracing:${name}:${eventType}` where `eventType` corresponds to the types of `TracingChannel Channels`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channelsByName = diagnostics_channel.tracingChannel('my-channel'); + * + * // or... + * + * const channelsByCollection = diagnostics_channel.tracingChannel({ + * start: diagnostics_channel.channel('tracing:my-channel:start'), + * end: diagnostics_channel.channel('tracing:my-channel:end'), + * asyncStart: diagnostics_channel.channel('tracing:my-channel:asyncStart'), + * asyncEnd: diagnostics_channel.channel('tracing:my-channel:asyncEnd'), + * error: diagnostics_channel.channel('tracing:my-channel:error'), + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param nameOrChannels Channel name or object containing all the `TracingChannel Channels` + * @return Collection of channels to trace with + */ + function tracingChannel< + StoreType = unknown, + ContextType extends object = StoreType extends object ? StoreType : object, + >( + nameOrChannels: string | TracingChannelCollection, + ): TracingChannel; + /** + * The class `Channel` represents an individual named channel within the data + * pipeline. It is used to track subscribers and to publish messages when there + * are subscribers present. It exists as a separate object to avoid channel + * lookups at publish time, enabling very fast publish speeds and allowing + * for heavy use while incurring very minimal cost. Channels are created with {@link channel}, constructing a channel directly + * with `new Channel(name)` is not supported. + * @since v15.1.0, v14.17.0 + */ + class Channel { + readonly name: string | symbol; + /** + * Check if there are active subscribers to this channel. This is helpful if + * the message you want to send might be expensive to prepare. + * + * This API is optional but helpful when trying to publish messages from very + * performance-sensitive code. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * if (channel.hasSubscribers) { + * // There are subscribers, prepare and publish message + * } + * ``` + * @since v15.1.0, v14.17.0 + */ + readonly hasSubscribers: boolean; + private constructor(name: string | symbol); + /** + * Publish a message to any subscribers to the channel. This will trigger + * message handlers synchronously so they will execute within the same context. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.publish({ + * some: 'message', + * }); + * ``` + * @since v15.1.0, v14.17.0 + * @param message The message to send to the channel subscribers + */ + publish(message: unknown): void; + /** + * Register a message handler to subscribe to this channel. This message handler + * will be run synchronously whenever a message is published to the channel. Any + * errors thrown in the message handler will trigger an `'uncaughtException'`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.subscribe((message, name) => { + * // Received data + * }); + * ``` + * @since v15.1.0, v14.17.0 + * @param onMessage The handler to receive channel messages + */ + subscribe(onMessage: ChannelListener): void; + /** + * Remove a message handler previously registered to this channel with `channel.subscribe(onMessage)`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * function onMessage(message, name) { + * // Received data + * } + * + * channel.subscribe(onMessage); + * + * channel.unsubscribe(onMessage); + * ``` + * @since v15.1.0, v14.17.0 + * @param onMessage The previous subscribed handler to remove + * @return `true` if the handler was found, `false` otherwise. + */ + unsubscribe(onMessage: ChannelListener): void; + /** + * When `channel.runStores(context, ...)` is called, the given context data + * will be applied to any store bound to the channel. If the store has already been + * bound the previous `transform` function will be replaced with the new one. + * The `transform` function may be omitted to set the given context data as the + * context directly. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const store = new AsyncLocalStorage(); + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.bindStore(store, (data) => { + * return { data }; + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param store The store to which to bind the context data + * @param transform Transform context data before setting the store context + */ + bindStore(store: AsyncLocalStorage, transform?: (context: ContextType) => StoreType): void; + /** + * Remove a message handler previously registered to this channel with `channel.bindStore(store)`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const store = new AsyncLocalStorage(); + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.bindStore(store); + * channel.unbindStore(store); + * ``` + * @since v19.9.0 + * @experimental + * @param store The store to unbind from the channel. + * @return `true` if the store was found, `false` otherwise. + */ + unbindStore(store: AsyncLocalStorage): boolean; + /** + * Applies the given data to any AsyncLocalStorage instances bound to the channel + * for the duration of the given function, then publishes to the channel within + * the scope of that data is applied to the stores. + * + * If a transform function was given to `channel.bindStore(store)` it will be + * applied to transform the message data before it becomes the context value for + * the store. The prior storage context is accessible from within the transform + * function in cases where context linking is required. + * + * The context applied to the store should be accessible in any async code which + * continues from execution which began during the given function, however + * there are some situations in which `context loss` may occur. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const store = new AsyncLocalStorage(); + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.bindStore(store, (message) => { + * const parent = store.getStore(); + * return new Span(message, parent); + * }); + * channel.runStores({ some: 'message' }, () => { + * store.getStore(); // Span({ some: 'message' }) + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param context Message to send to subscribers and bind to stores + * @param fn Handler to run within the entered storage context + * @param thisArg The receiver to be used for the function call. + * @param args Optional arguments to pass to the function. + */ + runStores( + context: ContextType, + fn: (this: ThisArg, ...args: Args) => Result, + thisArg?: ThisArg, + ...args: Args + ): Result; + } + interface TracingChannelSubscribers { + start: (message: ContextType) => void; + end: ( + message: ContextType & { + error?: unknown; + result?: unknown; + }, + ) => void; + asyncStart: ( + message: ContextType & { + error?: unknown; + result?: unknown; + }, + ) => void; + asyncEnd: ( + message: ContextType & { + error?: unknown; + result?: unknown; + }, + ) => void; + error: ( + message: ContextType & { + error: unknown; + }, + ) => void; + } + interface TracingChannelCollection { + start: Channel; + end: Channel; + asyncStart: Channel; + asyncEnd: Channel; + error: Channel; + } + /** + * The class `TracingChannel` is a collection of `TracingChannel Channels` which + * together express a single traceable action. It is used to formalize and + * simplify the process of producing events for tracing application flow. {@link tracingChannel} is used to construct a `TracingChannel`. As with `Channel` it is recommended to create and reuse a + * single `TracingChannel` at the top-level of the file rather than creating them + * dynamically. + * @since v19.9.0 + * @experimental + */ + class TracingChannel implements TracingChannelCollection { + start: Channel; + end: Channel; + asyncStart: Channel; + asyncEnd: Channel; + error: Channel; + /** + * Helper to subscribe a collection of functions to the corresponding channels. + * This is the same as calling `channel.subscribe(onMessage)` on each channel + * individually. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.subscribe({ + * start(message) { + * // Handle start message + * }, + * end(message) { + * // Handle end message + * }, + * asyncStart(message) { + * // Handle asyncStart message + * }, + * asyncEnd(message) { + * // Handle asyncEnd message + * }, + * error(message) { + * // Handle error message + * }, + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param subscribers Set of `TracingChannel Channels` subscribers + */ + subscribe(subscribers: TracingChannelSubscribers): void; + /** + * Helper to unsubscribe a collection of functions from the corresponding channels. + * This is the same as calling `channel.unsubscribe(onMessage)` on each channel + * individually. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.unsubscribe({ + * start(message) { + * // Handle start message + * }, + * end(message) { + * // Handle end message + * }, + * asyncStart(message) { + * // Handle asyncStart message + * }, + * asyncEnd(message) { + * // Handle asyncEnd message + * }, + * error(message) { + * // Handle error message + * }, + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param subscribers Set of `TracingChannel Channels` subscribers + * @return `true` if all handlers were successfully unsubscribed, and `false` otherwise. + */ + unsubscribe(subscribers: TracingChannelSubscribers): void; + /** + * Trace a synchronous function call. This will always produce a `start event` and `end event` around the execution and may produce an `error event` if the given function throws an error. + * This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all + * events should have any bound stores set to match this trace context. + * + * To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions + * which are added after the trace begins will not receive future events from that trace, only future traces will be seen. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.traceSync(() => { + * // Do something + * }, { + * some: 'thing', + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param fn Function to wrap a trace around + * @param context Shared object to correlate events through + * @param thisArg The receiver to be used for the function call + * @param args Optional arguments to pass to the function + * @return The return value of the given function + */ + traceSync( + fn: (this: ThisArg, ...args: Args) => Result, + context?: ContextType, + thisArg?: ThisArg, + ...args: Args + ): Result; + /** + * Trace a promise-returning function call. This will always produce a `start event` and `end event` around the synchronous portion of the + * function execution, and will produce an `asyncStart event` and `asyncEnd event` when a promise continuation is reached. It may also + * produce an `error event` if the given function throws an error or the + * returned promise rejects. This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all + * events should have any bound stores set to match this trace context. + * + * To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions + * which are added after the trace begins will not receive future events from that trace, only future traces will be seen. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.tracePromise(async () => { + * // Do something + * }, { + * some: 'thing', + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param fn Promise-returning function to wrap a trace around + * @param context Shared object to correlate trace events through + * @param thisArg The receiver to be used for the function call + * @param args Optional arguments to pass to the function + * @return Chained from promise returned by the given function + */ + tracePromise( + fn: (this: ThisArg, ...args: Args) => Promise, + context?: ContextType, + thisArg?: ThisArg, + ...args: Args + ): Promise; + /** + * Trace a callback-receiving function call. This will always produce a `start event` and `end event` around the synchronous portion of the + * function execution, and will produce a `asyncStart event` and `asyncEnd event` around the callback execution. It may also produce an `error event` if the given function throws an error or + * the returned + * promise rejects. This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all + * events should have any bound stores set to match this trace context. + * + * The `position` will be -1 by default to indicate the final argument should + * be used as the callback. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.traceCallback((arg1, callback) => { + * // Do something + * callback(null, 'result'); + * }, 1, { + * some: 'thing', + * }, thisArg, arg1, callback); + * ``` + * + * The callback will also be run with `channel.runStores(context, ...)` which + * enables context loss recovery in some cases. + * + * To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions + * which are added after the trace begins will not receive future events from that trace, only future traces will be seen. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * const myStore = new AsyncLocalStorage(); + * + * // The start channel sets the initial store data to something + * // and stores that store data value on the trace context object + * channels.start.bindStore(myStore, (data) => { + * const span = new Span(data); + * data.span = span; + * return span; + * }); + * + * // Then asyncStart can restore from that data it stored previously + * channels.asyncStart.bindStore(myStore, (data) => { + * return data.span; + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param fn callback using function to wrap a trace around + * @param position Zero-indexed argument position of expected callback + * @param context Shared object to correlate trace events through + * @param thisArg The receiver to be used for the function call + * @param args Optional arguments to pass to the function + * @return The return value of the given function + */ + traceCallback( + fn: (this: ThisArg, ...args: Args) => Result, + position?: number, + context?: ContextType, + thisArg?: ThisArg, + ...args: Args + ): Result; + /** + * `true` if any of the individual channels has a subscriber, `false` if not. + * + * This is a helper method available on a {@link TracingChannel} instance to check + * if any of the [TracingChannel Channels](https://nodejs.org/api/diagnostics_channel.html#tracingchannel-channels) have subscribers. + * A `true` is returned if any of them have at least one subscriber, a `false` is returned otherwise. + * + * ```js + * const diagnostics_channel = require('node:diagnostics_channel'); + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * if (channels.hasSubscribers) { + * // Do something + * } + * ``` + * @since v22.0.0, v20.13.0 + */ + readonly hasSubscribers: boolean; + } +} +declare module "diagnostics_channel" { + export * from "node:diagnostics_channel"; +} diff --git a/backend/node_modules/@types/node/dns.d.ts b/backend/node_modules/@types/node/dns.d.ts new file mode 100644 index 0000000..80a2272 --- /dev/null +++ b/backend/node_modules/@types/node/dns.d.ts @@ -0,0 +1,922 @@ +/** + * The `node:dns` module enables name resolution. For example, use it to look up IP + * addresses of host names. + * + * Although named for the [Domain Name System (DNS)](https://en.wikipedia.org/wiki/Domain_Name_System), it does not always use the + * DNS protocol for lookups. {@link lookup} uses the operating system + * facilities to perform name resolution. It may not need to perform any network + * communication. To perform name resolution the way other applications on the same + * system do, use {@link lookup}. + * + * ```js + * import dns from 'node:dns'; + * + * dns.lookup('example.org', (err, address, family) => { + * console.log('address: %j family: IPv%s', address, family); + * }); + * // address: "93.184.216.34" family: IPv4 + * ``` + * + * All other functions in the `node:dns` module connect to an actual DNS server to + * perform name resolution. They will always use the network to perform DNS + * queries. These functions do not use the same set of configuration files used by {@link lookup} (e.g. `/etc/hosts`). Use these functions to always perform + * DNS queries, bypassing other name-resolution facilities. + * + * ```js + * import dns from 'node:dns'; + * + * dns.resolve4('archive.org', (err, addresses) => { + * if (err) throw err; + * + * console.log(`addresses: ${JSON.stringify(addresses)}`); + * + * addresses.forEach((a) => { + * dns.reverse(a, (err, hostnames) => { + * if (err) { + * throw err; + * } + * console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`); + * }); + * }); + * }); + * ``` + * + * See the [Implementation considerations section](https://nodejs.org/docs/latest-v25.x/api/dns.html#implementation-considerations) for more information. + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/dns.js) + */ +declare module "node:dns" { + // Supported getaddrinfo flags. + /** + * Limits returned address types to the types of non-loopback addresses configured on the system. For example, IPv4 addresses are + * only returned if the current system has at least one IPv4 address configured. + */ + const ADDRCONFIG: number; + /** + * If the IPv6 family was specified, but no IPv6 addresses were found, then return IPv4 mapped IPv6 addresses. It is not supported + * on some operating systems (e.g. FreeBSD 10.1). + */ + const V4MAPPED: number; + /** + * If `dns.V4MAPPED` is specified, return resolved IPv6 addresses as + * well as IPv4 mapped IPv6 addresses. + */ + const ALL: number; + interface LookupOptions { + /** + * The record family. Must be `4`, `6`, or `0`. For backward compatibility reasons, `'IPv4'` and `'IPv6'` are interpreted + * as `4` and `6` respectively. The value 0 indicates that either an IPv4 or IPv6 address is returned. If the value `0` is used + * with `{ all: true } (see below)`, both IPv4 and IPv6 addresses are returned. + * @default 0 + */ + family?: number | "IPv4" | "IPv6" | undefined; + /** + * One or more [supported `getaddrinfo`](https://nodejs.org/docs/latest-v25.x/api/dns.html#supported-getaddrinfo-flags) flags. Multiple flags may be + * passed by bitwise `OR`ing their values. + */ + hints?: number | undefined; + /** + * When `true`, the callback returns all resolved addresses in an array. Otherwise, returns a single address. + * @default false + */ + all?: boolean | undefined; + /** + * When `verbatim`, the resolved addresses are return unsorted. When `ipv4first`, the resolved addresses are sorted + * by placing IPv4 addresses before IPv6 addresses. When `ipv6first`, the resolved addresses are sorted by placing IPv6 + * addresses before IPv4 addresses. Default value is configurable using + * {@link setDefaultResultOrder} or [`--dns-result-order`](https://nodejs.org/docs/latest-v25.x/api/cli.html#--dns-result-orderorder). + * @default `verbatim` (addresses are not reordered) + * @since v22.1.0 + */ + order?: "ipv4first" | "ipv6first" | "verbatim" | undefined; + /** + * When `true`, the callback receives IPv4 and IPv6 addresses in the order the DNS resolver returned them. When `false`, IPv4 + * addresses are placed before IPv6 addresses. This option will be deprecated in favor of `order`. When both are specified, + * `order` has higher precedence. New code should only use `order`. Default value is configurable using {@link setDefaultResultOrder} + * @default true (addresses are not reordered) + * @deprecated Please use `order` option + */ + verbatim?: boolean | undefined; + } + interface LookupOneOptions extends LookupOptions { + all?: false | undefined; + } + interface LookupAllOptions extends LookupOptions { + all: true; + } + interface LookupAddress { + /** + * A string representation of an IPv4 or IPv6 address. + */ + address: string; + /** + * `4` or `6`, denoting the family of `address`, or `0` if the address is not an IPv4 or IPv6 address. `0` is a likely indicator of a + * bug in the name resolution service used by the operating system. + */ + family: number; + } + /** + * Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or + * AAAA (IPv6) record. All `option` properties are optional. If `options` is an + * integer, then it must be `4` or `6` – if `options` is `0` or not provided, then + * IPv4 and IPv6 addresses are both returned if found. + * + * With the `all` option set to `true`, the arguments for `callback` change to `(err, addresses)`, with `addresses` being an array of objects with the + * properties `address` and `family`. + * + * On error, `err` is an `Error` object, where `err.code` is the error code. + * Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when + * the host name does not exist but also when the lookup fails in other ways + * such as no available file descriptors. + * + * `dns.lookup()` does not necessarily have anything to do with the DNS protocol. + * The implementation uses an operating system facility that can associate names + * with addresses and vice versa. This implementation can have subtle but + * important consequences on the behavior of any Node.js program. Please take some + * time to consult the [Implementation considerations section](https://nodejs.org/docs/latest-v25.x/api/dns.html#implementation-considerations) + * before using `dns.lookup()`. + * + * Example usage: + * + * ```js + * import dns from 'node:dns'; + * const options = { + * family: 6, + * hints: dns.ADDRCONFIG | dns.V4MAPPED, + * }; + * dns.lookup('example.com', options, (err, address, family) => + * console.log('address: %j family: IPv%s', address, family)); + * // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6 + * + * // When options.all is true, the result will be an Array. + * options.all = true; + * dns.lookup('example.com', options, (err, addresses) => + * console.log('addresses: %j', addresses)); + * // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] + * ``` + * + * If this method is invoked as its [util.promisify()](https://nodejs.org/docs/latest-v25.x/api/util.html#utilpromisifyoriginal) ed + * version, and `all` is not set to `true`, it returns a `Promise` for an `Object` with `address` and `family` properties. + * @since v0.1.90 + */ + function lookup( + hostname: string, + family: number, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ): void; + function lookup( + hostname: string, + options: LookupOneOptions, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ): void; + function lookup( + hostname: string, + options: LookupAllOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => void, + ): void; + function lookup( + hostname: string, + options: LookupOptions, + callback: (err: NodeJS.ErrnoException | null, address: string | LookupAddress[], family: number) => void, + ): void; + function lookup( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ): void; + namespace lookup { + function __promisify__(hostname: string, options: LookupAllOptions): Promise; + function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise; + function __promisify__(hostname: string, options: LookupOptions): Promise; + } + /** + * Resolves the given `address` and `port` into a host name and service using + * the operating system's underlying `getnameinfo` implementation. + * + * If `address` is not a valid IP address, a `TypeError` will be thrown. + * The `port` will be coerced to a number. If it is not a legal port, a `TypeError` will be thrown. + * + * On an error, `err` is an [`Error`](https://nodejs.org/docs/latest-v25.x/api/errors.html#class-error) object, + * where `err.code` is the error code. + * + * ```js + * import dns from 'node:dns'; + * dns.lookupService('127.0.0.1', 22, (err, hostname, service) => { + * console.log(hostname, service); + * // Prints: localhost ssh + * }); + * ``` + * + * If this method is invoked as its [util.promisify()](https://nodejs.org/docs/latest-v25.x/api/util.html#utilpromisifyoriginal) ed + * version, it returns a `Promise` for an `Object` with `hostname` and `service` properties. + * @since v0.11.14 + */ + function lookupService( + address: string, + port: number, + callback: (err: NodeJS.ErrnoException | null, hostname: string, service: string) => void, + ): void; + namespace lookupService { + function __promisify__( + address: string, + port: number, + ): Promise<{ + hostname: string; + service: string; + }>; + } + interface ResolveOptions { + ttl: boolean; + } + interface ResolveWithTtlOptions extends ResolveOptions { + ttl: true; + } + interface RecordWithTtl { + address: string; + ttl: number; + } + interface AnyARecord extends RecordWithTtl { + type: "A"; + } + interface AnyAaaaRecord extends RecordWithTtl { + type: "AAAA"; + } + interface CaaRecord { + critical: number; + issue?: string | undefined; + issuewild?: string | undefined; + iodef?: string | undefined; + contactemail?: string | undefined; + contactphone?: string | undefined; + } + interface AnyCaaRecord extends CaaRecord { + type: "CAA"; + } + interface MxRecord { + priority: number; + exchange: string; + } + interface AnyMxRecord extends MxRecord { + type: "MX"; + } + interface NaptrRecord { + flags: string; + service: string; + regexp: string; + replacement: string; + order: number; + preference: number; + } + interface AnyNaptrRecord extends NaptrRecord { + type: "NAPTR"; + } + interface SoaRecord { + nsname: string; + hostmaster: string; + serial: number; + refresh: number; + retry: number; + expire: number; + minttl: number; + } + interface AnySoaRecord extends SoaRecord { + type: "SOA"; + } + interface SrvRecord { + priority: number; + weight: number; + port: number; + name: string; + } + interface AnySrvRecord extends SrvRecord { + type: "SRV"; + } + interface TlsaRecord { + certUsage: number; + selector: number; + match: number; + data: ArrayBuffer; + } + interface AnyTlsaRecord extends TlsaRecord { + type: "TLSA"; + } + interface AnyTxtRecord { + type: "TXT"; + entries: string[]; + } + interface AnyNsRecord { + type: "NS"; + value: string; + } + interface AnyPtrRecord { + type: "PTR"; + value: string; + } + interface AnyCnameRecord { + type: "CNAME"; + value: string; + } + type AnyRecord = + | AnyARecord + | AnyAaaaRecord + | AnyCaaRecord + | AnyCnameRecord + | AnyMxRecord + | AnyNaptrRecord + | AnyNsRecord + | AnyPtrRecord + | AnySoaRecord + | AnySrvRecord + | AnyTlsaRecord + | AnyTxtRecord; + /** + * Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array + * of the resource records. The `callback` function has arguments `(err, records)`. When successful, `records` will be an array of resource + * records. The type and structure of individual results varies based on `rrtype`: + * + * + * + * On error, `err` is an [`Error`](https://nodejs.org/docs/latest-v25.x/api/errors.html#class-error) object, + * where `err.code` is one of the `DNS error codes`. + * @since v0.1.27 + * @param hostname Host name to resolve. + * @param [rrtype='A'] Resource record type. + */ + function resolve( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + function resolve( + hostname: string, + rrtype: "A" | "AAAA" | "CNAME" | "NS" | "PTR", + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + function resolve( + hostname: string, + rrtype: "ANY", + callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void, + ): void; + function resolve( + hostname: string, + rrtype: "CAA", + callback: (err: NodeJS.ErrnoException | null, address: CaaRecord[]) => void, + ): void; + function resolve( + hostname: string, + rrtype: "MX", + callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void, + ): void; + function resolve( + hostname: string, + rrtype: "NAPTR", + callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void, + ): void; + function resolve( + hostname: string, + rrtype: "SOA", + callback: (err: NodeJS.ErrnoException | null, addresses: SoaRecord) => void, + ): void; + function resolve( + hostname: string, + rrtype: "SRV", + callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void, + ): void; + function resolve( + hostname: string, + rrtype: "TLSA", + callback: (err: NodeJS.ErrnoException | null, addresses: TlsaRecord[]) => void, + ): void; + function resolve( + hostname: string, + rrtype: "TXT", + callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void, + ): void; + function resolve( + hostname: string, + rrtype: string, + callback: ( + err: NodeJS.ErrnoException | null, + addresses: + | string[] + | CaaRecord[] + | MxRecord[] + | NaptrRecord[] + | SoaRecord + | SrvRecord[] + | TlsaRecord[] + | string[][] + | AnyRecord[], + ) => void, + ): void; + namespace resolve { + function __promisify__(hostname: string, rrtype?: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise; + function __promisify__(hostname: string, rrtype: "ANY"): Promise; + function __promisify__(hostname: string, rrtype: "CAA"): Promise; + function __promisify__(hostname: string, rrtype: "MX"): Promise; + function __promisify__(hostname: string, rrtype: "NAPTR"): Promise; + function __promisify__(hostname: string, rrtype: "SOA"): Promise; + function __promisify__(hostname: string, rrtype: "SRV"): Promise; + function __promisify__(hostname: string, rrtype: "TLSA"): Promise; + function __promisify__(hostname: string, rrtype: "TXT"): Promise; + function __promisify__( + hostname: string, + rrtype: string, + ): Promise< + | string[] + | CaaRecord[] + | MxRecord[] + | NaptrRecord[] + | SoaRecord + | SrvRecord[] + | TlsaRecord[] + | string[][] + | AnyRecord[] + >; + } + /** + * Uses the DNS protocol to resolve a IPv4 addresses (`A` records) for the `hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of IPv4 addresses (e.g.`['74.125.79.104', '74.125.79.105', '74.125.79.106']`). + * @since v0.1.16 + * @param hostname Host name to resolve. + */ + function resolve4( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + function resolve4( + hostname: string, + options: ResolveWithTtlOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void, + ): void; + function resolve4( + hostname: string, + options: ResolveOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void, + ): void; + namespace resolve4 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + /** + * Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the `hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of IPv6 addresses. + * @since v0.1.16 + * @param hostname Host name to resolve. + */ + function resolve6( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + function resolve6( + hostname: string, + options: ResolveWithTtlOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void, + ): void; + function resolve6( + hostname: string, + options: ResolveOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void, + ): void; + namespace resolve6 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + /** + * Uses the DNS protocol to resolve `CNAME` records for the `hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of canonical name records available for the `hostname` (e.g. `['bar.example.com']`). + * @since v0.3.2 + */ + function resolveCname( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + namespace resolveCname { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve `CAA` records for the `hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of certification authority authorization records + * available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'}, {critical: 128, issue: 'pki.example.com'}]`). + * @since v15.0.0, v14.17.0 + */ + function resolveCaa( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, records: CaaRecord[]) => void, + ): void; + namespace resolveCaa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the `hostname`. The `addresses` argument passed to the `callback` function will + * contain an array of objects containing both a `priority` and `exchange` property (e.g. `[{priority: 10, exchange: 'mx.example.com'}, ...]`). + * @since v0.1.27 + */ + function resolveMx( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void, + ): void; + namespace resolveMx { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve regular expression-based records (`NAPTR` records) for the `hostname`. The `addresses` argument passed to the `callback` function will contain an array of + * objects with the following properties: + * + * * `flags` + * * `service` + * * `regexp` + * * `replacement` + * * `order` + * * `preference` + * + * ```js + * { + * flags: 's', + * service: 'SIP+D2U', + * regexp: '', + * replacement: '_sip._udp.example.com', + * order: 30, + * preference: 100 + * } + * ``` + * @since v0.9.12 + */ + function resolveNaptr( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void, + ): void; + namespace resolveNaptr { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve name server records (`NS` records) for the `hostname`. The `addresses` argument passed to the `callback` function will + * contain an array of name server records available for `hostname` (e.g. `['ns1.example.com', 'ns2.example.com']`). + * @since v0.1.90 + */ + function resolveNs( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + namespace resolveNs { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve pointer records (`PTR` records) for the `hostname`. The `addresses` argument passed to the `callback` function will + * be an array of strings containing the reply records. + * @since v6.0.0 + */ + function resolvePtr( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + namespace resolvePtr { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve a start of authority record (`SOA` record) for + * the `hostname`. The `address` argument passed to the `callback` function will + * be an object with the following properties: + * + * * `nsname` + * * `hostmaster` + * * `serial` + * * `refresh` + * * `retry` + * * `expire` + * * `minttl` + * + * ```js + * { + * nsname: 'ns.example.com', + * hostmaster: 'root.example.com', + * serial: 2013101809, + * refresh: 10000, + * retry: 2400, + * expire: 604800, + * minttl: 3600 + * } + * ``` + * @since v0.11.10 + */ + function resolveSoa( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, address: SoaRecord) => void, + ): void; + namespace resolveSoa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve service records (`SRV` records) for the `hostname`. The `addresses` argument passed to the `callback` function will + * be an array of objects with the following properties: + * + * * `priority` + * * `weight` + * * `port` + * * `name` + * + * ```js + * { + * priority: 10, + * weight: 5, + * port: 21223, + * name: 'service.example.com' + * } + * ``` + * @since v0.1.27 + */ + function resolveSrv( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void, + ): void; + namespace resolveSrv { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve certificate associations (`TLSA` records) for + * the `hostname`. The `records` argument passed to the `callback` function is an + * array of objects with these properties: + * + * * `certUsage` + * * `selector` + * * `match` + * * `data` + * + * ```js + * { + * certUsage: 3, + * selector: 1, + * match: 1, + * data: [ArrayBuffer] + * } + * ``` + * @since v23.9.0, v22.15.0 + */ + function resolveTlsa( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: TlsaRecord[]) => void, + ): void; + namespace resolveTlsa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve text queries (`TXT` records) for the `hostname`. The `records` argument passed to the `callback` function is a + * two-dimensional array of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of + * one record. Depending on the use case, these could be either joined together or + * treated separately. + * @since v0.1.27 + */ + function resolveTxt( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void, + ): void; + namespace resolveTxt { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query). + * The `ret` argument passed to the `callback` function will be an array containing + * various types of records. Each object has a property `type` that indicates the + * type of the current record. And depending on the `type`, additional properties + * will be present on the object: + * + * + * + * Here is an example of the `ret` object passed to the callback: + * + * ```js + * [ { type: 'A', address: '127.0.0.1', ttl: 299 }, + * { type: 'CNAME', value: 'example.com' }, + * { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 }, + * { type: 'NS', value: 'ns1.example.com' }, + * { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] }, + * { type: 'SOA', + * nsname: 'ns1.example.com', + * hostmaster: 'admin.example.com', + * serial: 156696742, + * refresh: 900, + * retry: 900, + * expire: 1800, + * minttl: 60 } ] + * ``` + * + * DNS server operators may choose not to respond to `ANY` queries. It may be better to call individual methods like {@link resolve4}, {@link resolveMx}, and so on. For more details, see + * [RFC 8482](https://tools.ietf.org/html/rfc8482). + */ + function resolveAny( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void, + ): void; + namespace resolveAny { + function __promisify__(hostname: string): Promise; + } + /** + * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an + * array of host names. + * + * On error, `err` is an [`Error`](https://nodejs.org/docs/latest-v25.x/api/errors.html#class-error) object, where `err.code` is + * one of the [DNS error codes](https://nodejs.org/docs/latest-v25.x/api/dns.html#error-codes). + * @since v0.1.16 + */ + function reverse( + ip: string, + callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void, + ): void; + /** + * Get the default value for `order` in {@link lookup} and [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v25.x/api/dns.html#dnspromiseslookuphostname-options). + * The value could be: + * + * * `ipv4first`: for `order` defaulting to `ipv4first`. + * * `ipv6first`: for `order` defaulting to `ipv6first`. + * * `verbatim`: for `order` defaulting to `verbatim`. + * @since v18.17.0 + */ + function getDefaultResultOrder(): "ipv4first" | "ipv6first" | "verbatim"; + /** + * Sets the IP address and port of servers to be used when performing DNS + * resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted + * addresses. If the port is the IANA default DNS port (53) it can be omitted. + * + * ```js + * dns.setServers([ + * '4.4.4.4', + * '[2001:4860:4860::8888]', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ]); + * ``` + * + * An error will be thrown if an invalid address is provided. + * + * The `dns.setServers()` method must not be called while a DNS query is in + * progress. + * + * The {@link setServers} method affects only {@link resolve}, `dns.resolve*()` and {@link reverse} (and specifically _not_ {@link lookup}). + * + * This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). + * That is, if attempting to resolve with the first server provided results in a `NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with + * subsequent servers provided. Fallback DNS servers will only be used if the + * earlier ones time out or result in some other error. + * @since v0.11.3 + * @param servers array of [RFC 5952](https://datatracker.ietf.org/doc/html/rfc5952#section-6) formatted addresses + */ + function setServers(servers: readonly string[]): void; + /** + * Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6), + * that are currently configured for DNS resolution. A string will include a port + * section if a custom port is used. + * + * ```js + * [ + * '4.4.4.4', + * '2001:4860:4860::8888', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ] + * ``` + * @since v0.11.3 + */ + function getServers(): string[]; + /** + * Set the default value of `order` in {@link lookup} and [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v25.x/api/dns.html#dnspromiseslookuphostname-options). + * The value could be: + * + * * `ipv4first`: sets default `order` to `ipv4first`. + * * `ipv6first`: sets default `order` to `ipv6first`. + * * `verbatim`: sets default `order` to `verbatim`. + * + * The default is `verbatim` and {@link setDefaultResultOrder} have higher + * priority than [`--dns-result-order`](https://nodejs.org/docs/latest-v25.x/api/cli.html#--dns-result-orderorder). When using + * [worker threads](https://nodejs.org/docs/latest-v25.x/api/worker_threads.html), {@link setDefaultResultOrder} from the main + * thread won't affect the default dns orders in workers. + * @since v16.4.0, v14.18.0 + * @param order must be `'ipv4first'`, `'ipv6first'` or `'verbatim'`. + */ + function setDefaultResultOrder(order: "ipv4first" | "ipv6first" | "verbatim"): void; + // Error codes + const NODATA: "ENODATA"; + const FORMERR: "EFORMERR"; + const SERVFAIL: "ESERVFAIL"; + const NOTFOUND: "ENOTFOUND"; + const NOTIMP: "ENOTIMP"; + const REFUSED: "EREFUSED"; + const BADQUERY: "EBADQUERY"; + const BADNAME: "EBADNAME"; + const BADFAMILY: "EBADFAMILY"; + const BADRESP: "EBADRESP"; + const CONNREFUSED: "ECONNREFUSED"; + const TIMEOUT: "ETIMEOUT"; + const EOF: "EOF"; + const FILE: "EFILE"; + const NOMEM: "ENOMEM"; + const DESTRUCTION: "EDESTRUCTION"; + const BADSTR: "EBADSTR"; + const BADFLAGS: "EBADFLAGS"; + const NONAME: "ENONAME"; + const BADHINTS: "EBADHINTS"; + const NOTINITIALIZED: "ENOTINITIALIZED"; + const LOADIPHLPAPI: "ELOADIPHLPAPI"; + const ADDRGETNETWORKPARAMS: "EADDRGETNETWORKPARAMS"; + const CANCELLED: "ECANCELLED"; + interface ResolverOptions { + /** + * Query timeout in milliseconds, or `-1` to use the default timeout. + */ + timeout?: number | undefined; + /** + * The number of tries the resolver will try contacting each name server before giving up. + * @default 4 + */ + tries?: number | undefined; + /** + * The max retry timeout, in milliseconds. + * @default 0 + */ + maxTimeout?: number | undefined; + } + /** + * An independent resolver for DNS requests. + * + * Creating a new resolver uses the default server settings. Setting + * the servers used for a resolver using [`resolver.setServers()`](https://nodejs.org/docs/latest-v25.x/api/dns.html#dnssetserversservers) does not affect + * other resolvers: + * + * ```js + * import { Resolver } from 'node:dns'; + * const resolver = new Resolver(); + * resolver.setServers(['4.4.4.4']); + * + * // This request will use the server at 4.4.4.4, independent of global settings. + * resolver.resolve4('example.org', (err, addresses) => { + * // ... + * }); + * ``` + * + * The following methods from the `node:dns` module are available: + * + * * `resolver.getServers()` + * * `resolver.resolve()` + * * `resolver.resolve4()` + * * `resolver.resolve6()` + * * `resolver.resolveAny()` + * * `resolver.resolveCaa()` + * * `resolver.resolveCname()` + * * `resolver.resolveMx()` + * * `resolver.resolveNaptr()` + * * `resolver.resolveNs()` + * * `resolver.resolvePtr()` + * * `resolver.resolveSoa()` + * * `resolver.resolveSrv()` + * * `resolver.resolveTxt()` + * * `resolver.reverse()` + * * `resolver.setServers()` + * @since v8.3.0 + */ + class Resolver { + constructor(options?: ResolverOptions); + /** + * Cancel all outstanding DNS queries made by this resolver. The corresponding + * callbacks will be called with an error with code `ECANCELLED`. + * @since v8.3.0 + */ + cancel(): void; + getServers: typeof getServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCaa: typeof resolveCaa; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTlsa: typeof resolveTlsa; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + /** + * The resolver instance will send its requests from the specified IP address. + * This allows programs to specify outbound interfaces when used on multi-homed + * systems. + * + * If a v4 or v6 address is not specified, it is set to the default and the + * operating system will choose a local address automatically. + * + * The resolver will use the v4 local address when making requests to IPv4 DNS + * servers, and the v6 local address when making requests to IPv6 DNS servers. + * The `rrtype` of resolution requests has no impact on the local address used. + * @since v15.1.0, v14.17.0 + * @param [ipv4='0.0.0.0'] A string representation of an IPv4 address. + * @param [ipv6='::0'] A string representation of an IPv6 address. + */ + setLocalAddress(ipv4?: string, ipv6?: string): void; + setServers: typeof setServers; + } +} +declare module "node:dns" { + export * as promises from "node:dns/promises"; +} +declare module "dns" { + export * from "node:dns"; +} diff --git a/backend/node_modules/@types/node/dns/promises.d.ts b/backend/node_modules/@types/node/dns/promises.d.ts new file mode 100644 index 0000000..8d5f989 --- /dev/null +++ b/backend/node_modules/@types/node/dns/promises.d.ts @@ -0,0 +1,503 @@ +/** + * The `dns.promises` API provides an alternative set of asynchronous DNS methods + * that return `Promise` objects rather than using callbacks. The API is accessible + * via `import { promises as dnsPromises } from 'node:dns'` or `import dnsPromises from 'node:dns/promises'`. + * @since v10.6.0 + */ +declare module "node:dns/promises" { + import { + AnyRecord, + CaaRecord, + LookupAddress, + LookupAllOptions, + LookupOneOptions, + LookupOptions, + MxRecord, + NaptrRecord, + RecordWithTtl, + ResolveOptions, + ResolverOptions, + ResolveWithTtlOptions, + SoaRecord, + SrvRecord, + TlsaRecord, + } from "node:dns"; + /** + * Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6), + * that are currently configured for DNS resolution. A string will include a port + * section if a custom port is used. + * + * ```js + * [ + * '4.4.4.4', + * '2001:4860:4860::8888', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ] + * ``` + * @since v10.6.0 + */ + function getServers(): string[]; + /** + * Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or + * AAAA (IPv6) record. All `option` properties are optional. If `options` is an + * integer, then it must be `4` or `6` – if `options` is not provided, then IPv4 + * and IPv6 addresses are both returned if found. + * + * With the `all` option set to `true`, the `Promise` is resolved with `addresses` being an array of objects with the properties `address` and `family`. + * + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` is the error code. + * Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when + * the host name does not exist but also when the lookup fails in other ways + * such as no available file descriptors. + * + * [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromiseslookuphostname-options) does not necessarily have anything to do with the DNS + * protocol. The implementation uses an operating system facility that can + * associate names with addresses and vice versa. This implementation can have + * subtle but important consequences on the behavior of any Node.js program. Please + * take some time to consult the [Implementation considerations section](https://nodejs.org/docs/latest-v20.x/api/dns.html#implementation-considerations) before + * using `dnsPromises.lookup()`. + * + * Example usage: + * + * ```js + * import dns from 'node:dns'; + * const dnsPromises = dns.promises; + * const options = { + * family: 6, + * hints: dns.ADDRCONFIG | dns.V4MAPPED, + * }; + * + * dnsPromises.lookup('example.com', options).then((result) => { + * console.log('address: %j family: IPv%s', result.address, result.family); + * // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6 + * }); + * + * // When options.all is true, the result will be an Array. + * options.all = true; + * dnsPromises.lookup('example.com', options).then((result) => { + * console.log('addresses: %j', result); + * // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] + * }); + * ``` + * @since v10.6.0 + */ + function lookup(hostname: string, family: number): Promise; + function lookup(hostname: string, options: LookupOneOptions): Promise; + function lookup(hostname: string, options: LookupAllOptions): Promise; + function lookup(hostname: string, options: LookupOptions): Promise; + function lookup(hostname: string): Promise; + /** + * Resolves the given `address` and `port` into a host name and service using + * the operating system's underlying `getnameinfo` implementation. + * + * If `address` is not a valid IP address, a `TypeError` will be thrown. + * The `port` will be coerced to a number. If it is not a legal port, a `TypeError` will be thrown. + * + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` is the error code. + * + * ```js + * import dnsPromises from 'node:dns'; + * dnsPromises.lookupService('127.0.0.1', 22).then((result) => { + * console.log(result.hostname, result.service); + * // Prints: localhost ssh + * }); + * ``` + * @since v10.6.0 + */ + function lookupService( + address: string, + port: number, + ): Promise<{ + hostname: string; + service: string; + }>; + /** + * Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array + * of the resource records. When successful, the `Promise` is resolved with an + * array of resource records. The type and structure of individual results vary + * based on `rrtype`: + * + * + * + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` + * is one of the [DNS error codes](https://nodejs.org/docs/latest-v20.x/api/dns.html#error-codes). + * @since v10.6.0 + * @param hostname Host name to resolve. + * @param [rrtype='A'] Resource record type. + */ + function resolve(hostname: string): Promise; + function resolve(hostname: string, rrtype: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise; + function resolve(hostname: string, rrtype: "ANY"): Promise; + function resolve(hostname: string, rrtype: "CAA"): Promise; + function resolve(hostname: string, rrtype: "MX"): Promise; + function resolve(hostname: string, rrtype: "NAPTR"): Promise; + function resolve(hostname: string, rrtype: "SOA"): Promise; + function resolve(hostname: string, rrtype: "SRV"): Promise; + function resolve(hostname: string, rrtype: "TLSA"): Promise; + function resolve(hostname: string, rrtype: "TXT"): Promise; + function resolve(hostname: string, rrtype: string): Promise< + | string[] + | CaaRecord[] + | MxRecord[] + | NaptrRecord[] + | SoaRecord + | SrvRecord[] + | TlsaRecord[] + | string[][] + | AnyRecord[] + >; + /** + * Uses the DNS protocol to resolve IPv4 addresses (`A` records) for the `hostname`. On success, the `Promise` is resolved with an array of IPv4 + * addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`). + * @since v10.6.0 + * @param hostname Host name to resolve. + */ + function resolve4(hostname: string): Promise; + function resolve4(hostname: string, options: ResolveWithTtlOptions): Promise; + function resolve4(hostname: string, options: ResolveOptions): Promise; + /** + * Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the `hostname`. On success, the `Promise` is resolved with an array of IPv6 + * addresses. + * @since v10.6.0 + * @param hostname Host name to resolve. + */ + function resolve6(hostname: string): Promise; + function resolve6(hostname: string, options: ResolveWithTtlOptions): Promise; + function resolve6(hostname: string, options: ResolveOptions): Promise; + /** + * Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query). + * On success, the `Promise` is resolved with an array containing various types of + * records. Each object has a property `type` that indicates the type of the + * current record. And depending on the `type`, additional properties will be + * present on the object: + * + * + * + * Here is an example of the result object: + * + * ```js + * [ { type: 'A', address: '127.0.0.1', ttl: 299 }, + * { type: 'CNAME', value: 'example.com' }, + * { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 }, + * { type: 'NS', value: 'ns1.example.com' }, + * { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] }, + * { type: 'SOA', + * nsname: 'ns1.example.com', + * hostmaster: 'admin.example.com', + * serial: 156696742, + * refresh: 900, + * retry: 900, + * expire: 1800, + * minttl: 60 } ] + * ``` + * @since v10.6.0 + */ + function resolveAny(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve `CAA` records for the `hostname`. On success, + * the `Promise` is resolved with an array of objects containing available + * certification authority authorization records available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'},{critical: 128, issue: 'pki.example.com'}]`). + * @since v15.0.0, v14.17.0 + */ + function resolveCaa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve `CNAME` records for the `hostname`. On success, + * the `Promise` is resolved with an array of canonical name records available for + * the `hostname` (e.g. `['bar.example.com']`). + * @since v10.6.0 + */ + function resolveCname(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the `hostname`. On success, the `Promise` is resolved with an array of objects + * containing both a `priority` and `exchange` property (e.g.`[{priority: 10, exchange: 'mx.example.com'}, ...]`). + * @since v10.6.0 + */ + function resolveMx(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve regular expression-based records (`NAPTR` records) for the `hostname`. On success, the `Promise` is resolved with an array + * of objects with the following properties: + * + * * `flags` + * * `service` + * * `regexp` + * * `replacement` + * * `order` + * * `preference` + * + * ```js + * { + * flags: 's', + * service: 'SIP+D2U', + * regexp: '', + * replacement: '_sip._udp.example.com', + * order: 30, + * preference: 100 + * } + * ``` + * @since v10.6.0 + */ + function resolveNaptr(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve name server records (`NS` records) for the `hostname`. On success, the `Promise` is resolved with an array of name server + * records available for `hostname` (e.g.`['ns1.example.com', 'ns2.example.com']`). + * @since v10.6.0 + */ + function resolveNs(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve pointer records (`PTR` records) for the `hostname`. On success, the `Promise` is resolved with an array of strings + * containing the reply records. + * @since v10.6.0 + */ + function resolvePtr(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve a start of authority record (`SOA` record) for + * the `hostname`. On success, the `Promise` is resolved with an object with the + * following properties: + * + * * `nsname` + * * `hostmaster` + * * `serial` + * * `refresh` + * * `retry` + * * `expire` + * * `minttl` + * + * ```js + * { + * nsname: 'ns.example.com', + * hostmaster: 'root.example.com', + * serial: 2013101809, + * refresh: 10000, + * retry: 2400, + * expire: 604800, + * minttl: 3600 + * } + * ``` + * @since v10.6.0 + */ + function resolveSoa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve service records (`SRV` records) for the `hostname`. On success, the `Promise` is resolved with an array of objects with + * the following properties: + * + * * `priority` + * * `weight` + * * `port` + * * `name` + * + * ```js + * { + * priority: 10, + * weight: 5, + * port: 21223, + * name: 'service.example.com' + * } + * ``` + * @since v10.6.0 + */ + function resolveSrv(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve certificate associations (`TLSA` records) for + * the `hostname`. On success, the `Promise` is resolved with an array of objectsAdd commentMore actions + * with these properties: + * + * * `certUsage` + * * `selector` + * * `match` + * * `data` + * + * ```js + * { + * certUsage: 3, + * selector: 1, + * match: 1, + * data: [ArrayBuffer] + * } + * ``` + * @since v23.9.0, v22.15.0 + */ + function resolveTlsa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve text queries (`TXT` records) for the `hostname`. On success, the `Promise` is resolved with a two-dimensional array + * of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of + * one record. Depending on the use case, these could be either joined together or + * treated separately. + * @since v10.6.0 + */ + function resolveTxt(hostname: string): Promise; + /** + * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an + * array of host names. + * + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` + * is one of the [DNS error codes](https://nodejs.org/docs/latest-v20.x/api/dns.html#error-codes). + * @since v10.6.0 + */ + function reverse(ip: string): Promise; + /** + * Get the default value for `verbatim` in {@link lookup} and [dnsPromises.lookup()](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromiseslookuphostname-options). + * The value could be: + * + * * `ipv4first`: for `verbatim` defaulting to `false`. + * * `verbatim`: for `verbatim` defaulting to `true`. + * @since v20.1.0 + */ + function getDefaultResultOrder(): "ipv4first" | "verbatim"; + /** + * Sets the IP address and port of servers to be used when performing DNS + * resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted + * addresses. If the port is the IANA default DNS port (53) it can be omitted. + * + * ```js + * dnsPromises.setServers([ + * '4.4.4.4', + * '[2001:4860:4860::8888]', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ]); + * ``` + * + * An error will be thrown if an invalid address is provided. + * + * The `dnsPromises.setServers()` method must not be called while a DNS query is in + * progress. + * + * This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). + * That is, if attempting to resolve with the first server provided results in a `NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with + * subsequent servers provided. Fallback DNS servers will only be used if the + * earlier ones time out or result in some other error. + * @since v10.6.0 + * @param servers array of `RFC 5952` formatted addresses + */ + function setServers(servers: readonly string[]): void; + /** + * Set the default value of `order` in `dns.lookup()` and `{@link lookup}`. The value could be: + * + * * `ipv4first`: sets default `order` to `ipv4first`. + * * `ipv6first`: sets default `order` to `ipv6first`. + * * `verbatim`: sets default `order` to `verbatim`. + * + * The default is `verbatim` and [dnsPromises.setDefaultResultOrder()](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetdefaultresultorderorder) + * have higher priority than [`--dns-result-order`](https://nodejs.org/docs/latest-v20.x/api/cli.html#--dns-result-orderorder). + * When using [worker threads](https://nodejs.org/docs/latest-v20.x/api/worker_threads.html), [`dnsPromises.setDefaultResultOrder()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetdefaultresultorderorder) + * from the main thread won't affect the default dns orders in workers. + * @since v16.4.0, v14.18.0 + * @param order must be `'ipv4first'`, `'ipv6first'` or `'verbatim'`. + */ + function setDefaultResultOrder(order: "ipv4first" | "ipv6first" | "verbatim"): void; + // Error codes + const NODATA: "ENODATA"; + const FORMERR: "EFORMERR"; + const SERVFAIL: "ESERVFAIL"; + const NOTFOUND: "ENOTFOUND"; + const NOTIMP: "ENOTIMP"; + const REFUSED: "EREFUSED"; + const BADQUERY: "EBADQUERY"; + const BADNAME: "EBADNAME"; + const BADFAMILY: "EBADFAMILY"; + const BADRESP: "EBADRESP"; + const CONNREFUSED: "ECONNREFUSED"; + const TIMEOUT: "ETIMEOUT"; + const EOF: "EOF"; + const FILE: "EFILE"; + const NOMEM: "ENOMEM"; + const DESTRUCTION: "EDESTRUCTION"; + const BADSTR: "EBADSTR"; + const BADFLAGS: "EBADFLAGS"; + const NONAME: "ENONAME"; + const BADHINTS: "EBADHINTS"; + const NOTINITIALIZED: "ENOTINITIALIZED"; + const LOADIPHLPAPI: "ELOADIPHLPAPI"; + const ADDRGETNETWORKPARAMS: "EADDRGETNETWORKPARAMS"; + const CANCELLED: "ECANCELLED"; + + /** + * An independent resolver for DNS requests. + * + * Creating a new resolver uses the default server settings. Setting + * the servers used for a resolver using [`resolver.setServers()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetserversservers) does not affect + * other resolvers: + * + * ```js + * import { promises } from 'node:dns'; + * const resolver = new promises.Resolver(); + * resolver.setServers(['4.4.4.4']); + * + * // This request will use the server at 4.4.4.4, independent of global settings. + * resolver.resolve4('example.org').then((addresses) => { + * // ... + * }); + * + * // Alternatively, the same code can be written using async-await style. + * (async function() { + * const addresses = await resolver.resolve4('example.org'); + * })(); + * ``` + * + * The following methods from the `dnsPromises` API are available: + * + * * `resolver.getServers()` + * * `resolver.resolve()` + * * `resolver.resolve4()` + * * `resolver.resolve6()` + * * `resolver.resolveAny()` + * * `resolver.resolveCaa()` + * * `resolver.resolveCname()` + * * `resolver.resolveMx()` + * * `resolver.resolveNaptr()` + * * `resolver.resolveNs()` + * * `resolver.resolvePtr()` + * * `resolver.resolveSoa()` + * * `resolver.resolveSrv()` + * * `resolver.resolveTxt()` + * * `resolver.reverse()` + * * `resolver.setServers()` + * @since v10.6.0 + */ + class Resolver { + constructor(options?: ResolverOptions); + /** + * Cancel all outstanding DNS queries made by this resolver. The corresponding + * callbacks will be called with an error with code `ECANCELLED`. + * @since v8.3.0 + */ + cancel(): void; + getServers: typeof getServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCaa: typeof resolveCaa; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTlsa: typeof resolveTlsa; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + /** + * The resolver instance will send its requests from the specified IP address. + * This allows programs to specify outbound interfaces when used on multi-homed + * systems. + * + * If a v4 or v6 address is not specified, it is set to the default and the + * operating system will choose a local address automatically. + * + * The resolver will use the v4 local address when making requests to IPv4 DNS + * servers, and the v6 local address when making requests to IPv6 DNS servers. + * The `rrtype` of resolution requests has no impact on the local address used. + * @since v15.1.0, v14.17.0 + * @param [ipv4='0.0.0.0'] A string representation of an IPv4 address. + * @param [ipv6='::0'] A string representation of an IPv6 address. + */ + setLocalAddress(ipv4?: string, ipv6?: string): void; + setServers: typeof setServers; + } +} +declare module "dns/promises" { + export * from "node:dns/promises"; +} diff --git a/backend/node_modules/@types/node/domain.d.ts b/backend/node_modules/@types/node/domain.d.ts new file mode 100644 index 0000000..24a0981 --- /dev/null +++ b/backend/node_modules/@types/node/domain.d.ts @@ -0,0 +1,166 @@ +/** + * **This module is pending deprecation.** Once a replacement API has been + * finalized, this module will be fully deprecated. Most developers should + * **not** have cause to use this module. Users who absolutely must have + * the functionality that domains provide may rely on it for the time being + * but should expect to have to migrate to a different solution + * in the future. + * + * Domains provide a way to handle multiple different IO operations as a + * single group. If any of the event emitters or callbacks registered to a + * domain emit an `'error'` event, or throw an error, then the domain object + * will be notified, rather than losing the context of the error in the `process.on('uncaughtException')` handler, or causing the program to + * exit immediately with an error code. + * @deprecated Since v1.4.2 - Deprecated + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/domain.js) + */ +declare module "node:domain" { + import { EventEmitter } from "node:events"; + /** + * The `Domain` class encapsulates the functionality of routing errors and + * uncaught exceptions to the active `Domain` object. + * + * To handle the errors that it catches, listen to its `'error'` event. + */ + class Domain extends EventEmitter { + /** + * An array of event emitters that have been explicitly added to the domain. + */ + members: EventEmitter[]; + /** + * The `enter()` method is plumbing used by the `run()`, `bind()`, and `intercept()` methods to set the active domain. It sets `domain.active` and `process.domain` to the domain, and implicitly + * pushes the domain onto the domain + * stack managed by the domain module (see {@link exit} for details on the + * domain stack). The call to `enter()` delimits the beginning of a chain of + * asynchronous calls and I/O operations bound to a domain. + * + * Calling `enter()` changes only the active domain, and does not alter the domain + * itself. `enter()` and `exit()` can be called an arbitrary number of times on a + * single domain. + */ + enter(): void; + /** + * The `exit()` method exits the current domain, popping it off the domain stack. + * Any time execution is going to switch to the context of a different chain of + * asynchronous calls, it's important to ensure that the current domain is exited. + * The call to `exit()` delimits either the end of or an interruption to the chain + * of asynchronous calls and I/O operations bound to a domain. + * + * If there are multiple, nested domains bound to the current execution context, `exit()` will exit any domains nested within this domain. + * + * Calling `exit()` changes only the active domain, and does not alter the domain + * itself. `enter()` and `exit()` can be called an arbitrary number of times on a + * single domain. + */ + exit(): void; + /** + * Run the supplied function in the context of the domain, implicitly + * binding all event emitters, timers, and low-level requests that are + * created in that context. Optionally, arguments can be passed to + * the function. + * + * This is the most basic way to use a domain. + * + * ```js + * import domain from 'node:domain'; + * import fs from 'node:fs'; + * const d = domain.create(); + * d.on('error', (er) => { + * console.error('Caught error!', er); + * }); + * d.run(() => { + * process.nextTick(() => { + * setTimeout(() => { // Simulating some various async stuff + * fs.open('non-existent file', 'r', (er, fd) => { + * if (er) throw er; + * // proceed... + * }); + * }, 100); + * }); + * }); + * ``` + * + * In this example, the `d.on('error')` handler will be triggered, rather + * than crashing the program. + */ + run(fn: (...args: any[]) => T, ...args: any[]): T; + /** + * Explicitly adds an emitter to the domain. If any event handlers called by + * the emitter throw an error, or if the emitter emits an `'error'` event, it + * will be routed to the domain's `'error'` event, just like with implicit + * binding. + * + * If the `EventEmitter` was already bound to a domain, it is removed from that + * one, and bound to this one instead. + * @param emitter emitter to be added to the domain + */ + add(emitter: EventEmitter): void; + /** + * The opposite of {@link add}. Removes domain handling from the + * specified emitter. + * @param emitter emitter to be removed from the domain + */ + remove(emitter: EventEmitter): void; + /** + * The returned function will be a wrapper around the supplied callback + * function. When the returned function is called, any errors that are + * thrown will be routed to the domain's `'error'` event. + * + * ```js + * const d = domain.create(); + * + * function readSomeFile(filename, cb) { + * fs.readFile(filename, 'utf8', d.bind((er, data) => { + * // If this throws, it will also be passed to the domain. + * return cb(er, data ? JSON.parse(data) : null); + * })); + * } + * + * d.on('error', (er) => { + * // An error occurred somewhere. If we throw it now, it will crash the program + * // with the normal line number and stack message. + * }); + * ``` + * @param callback The callback function + * @return The bound function + */ + bind(callback: T): T; + /** + * This method is almost identical to {@link bind}. However, in + * addition to catching thrown errors, it will also intercept `Error` objects sent as the first argument to the function. + * + * In this way, the common `if (err) return callback(err);` pattern can be replaced + * with a single error handler in a single place. + * + * ```js + * const d = domain.create(); + * + * function readSomeFile(filename, cb) { + * fs.readFile(filename, 'utf8', d.intercept((data) => { + * // Note, the first argument is never passed to the + * // callback since it is assumed to be the 'Error' argument + * // and thus intercepted by the domain. + * + * // If this throws, it will also be passed to the domain + * // so the error-handling logic can be moved to the 'error' + * // event on the domain instead of being repeated throughout + * // the program. + * return cb(null, JSON.parse(data)); + * })); + * } + * + * d.on('error', (er) => { + * // An error occurred somewhere. If we throw it now, it will crash the program + * // with the normal line number and stack message. + * }); + * ``` + * @param callback The callback function + * @return The intercepted function + */ + intercept(callback: T): T; + } + function create(): Domain; +} +declare module "domain" { + export * from "node:domain"; +} diff --git a/backend/node_modules/@types/node/events.d.ts b/backend/node_modules/@types/node/events.d.ts new file mode 100644 index 0000000..13a804f --- /dev/null +++ b/backend/node_modules/@types/node/events.d.ts @@ -0,0 +1,1046 @@ +/** + * Much of the Node.js core API is built around an idiomatic asynchronous + * event-driven architecture in which certain kinds of objects (called "emitters") + * emit named events that cause `Function` objects ("listeners") to be called. + * + * For instance: a `net.Server` object emits an event each time a peer + * connects to it; a `fs.ReadStream` emits an event when the file is opened; + * a `stream` emits an event whenever data is available to be read. + * + * All objects that emit events are instances of the `EventEmitter` class. These + * objects expose an `eventEmitter.on()` function that allows one or more + * functions to be attached to named events emitted by the object. Typically, + * event names are camel-cased strings but any valid JavaScript property key + * can be used. + * + * When the `EventEmitter` object emits an event, all of the functions attached + * to that specific event are called _synchronously_. Any values returned by the + * called listeners are _ignored_ and discarded. + * + * The following example shows a simple `EventEmitter` instance with a single + * listener. The `eventEmitter.on()` method is used to register listeners, while + * the `eventEmitter.emit()` method is used to trigger the event. + * + * ```js + * import { EventEmitter } from 'node:events'; + * + * class MyEmitter extends EventEmitter {} + * + * const myEmitter = new MyEmitter(); + * myEmitter.on('event', () => { + * console.log('an event occurred!'); + * }); + * myEmitter.emit('event'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/events.js) + */ +declare module "node:events" { + import { AsyncResource, AsyncResourceOptions } from "node:async_hooks"; + // #region Event map helpers + type EventMap = Record; + type IfEventMap, True, False> = {} extends Events ? False : True; + type Args, EventName extends string | symbol> = IfEventMap< + Events, + EventName extends keyof Events ? Events[EventName] + : EventName extends keyof EventEmitterEventMap ? EventEmitterEventMap[EventName] + : any[], + any[] + >; + type EventNames, EventName extends string | symbol> = IfEventMap< + Events, + EventName | (keyof Events & (string | symbol)) | keyof EventEmitterEventMap, + string | symbol + >; + type Listener, EventName extends string | symbol> = IfEventMap< + Events, + ( + ...args: EventName extends keyof Events ? Events[EventName] + : EventName extends keyof EventEmitterEventMap ? EventEmitterEventMap[EventName] + : any[] + ) => void, + (...args: any[]) => void + >; + interface EventEmitterEventMap { + newListener: [eventName: string | symbol, listener: (...args: any[]) => void]; + removeListener: [eventName: string | symbol, listener: (...args: any[]) => void]; + } + // #endregion + interface EventEmitterOptions { + /** + * It enables + * [automatic capturing of promise rejection](https://nodejs.org/docs/latest-v25.x/api/events.html#capture-rejections-of-promises). + * @default false + */ + captureRejections?: boolean | undefined; + } + /** + * The `EventEmitter` class is defined and exposed by the `node:events` module: + * + * ```js + * import { EventEmitter } from 'node:events'; + * ``` + * + * All `EventEmitter`s emit the event `'newListener'` when new listeners are + * added and `'removeListener'` when existing listeners are removed. + * + * It supports the following option: + * @since v0.1.26 + */ + class EventEmitter = any> { + constructor(options?: EventEmitterOptions); + /** + * The `Symbol.for('nodejs.rejection')` method is called in case a + * promise rejection happens when emitting an event and + * `captureRejections` is enabled on the emitter. + * It is possible to use `events.captureRejectionSymbol` in + * place of `Symbol.for('nodejs.rejection')`. + * + * ```js + * import { EventEmitter, captureRejectionSymbol } from 'node:events'; + * + * class MyClass extends EventEmitter { + * constructor() { + * super({ captureRejections: true }); + * } + * + * [captureRejectionSymbol](err, event, ...args) { + * console.log('rejection happened for', event, 'with', err, ...args); + * this.destroy(err); + * } + * + * destroy(err) { + * // Tear the resource down here. + * } + * } + * ``` + * @since v13.4.0, v12.16.0 + */ + [EventEmitter.captureRejectionSymbol]?(error: Error, event: string | symbol, ...args: any[]): void; + /** + * Alias for `emitter.on(eventName, listener)`. + * @since v0.1.26 + */ + addListener(eventName: EventNames, listener: Listener): this; + /** + * Synchronously calls each of the listeners registered for the event named + * `eventName`, in the order they were registered, passing the supplied arguments + * to each. + * + * Returns `true` if the event had listeners, `false` otherwise. + * + * ```js + * import { EventEmitter } from 'node:events'; + * const myEmitter = new EventEmitter(); + * + * // First listener + * myEmitter.on('event', function firstListener() { + * console.log('Helloooo! first listener'); + * }); + * // Second listener + * myEmitter.on('event', function secondListener(arg1, arg2) { + * console.log(`event with parameters ${arg1}, ${arg2} in second listener`); + * }); + * // Third listener + * myEmitter.on('event', function thirdListener(...args) { + * const parameters = args.join(', '); + * console.log(`event with parameters ${parameters} in third listener`); + * }); + * + * console.log(myEmitter.listeners('event')); + * + * myEmitter.emit('event', 1, 2, 3, 4, 5); + * + * // Prints: + * // [ + * // [Function: firstListener], + * // [Function: secondListener], + * // [Function: thirdListener] + * // ] + * // Helloooo! first listener + * // event with parameters 1, 2 in second listener + * // event with parameters 1, 2, 3, 4, 5 in third listener + * ``` + * @since v0.1.26 + */ + emit(eventName: EventNames, ...args: Args): boolean; + /** + * Returns an array listing the events for which the emitter has registered + * listeners. + * + * ```js + * import { EventEmitter } from 'node:events'; + * + * const myEE = new EventEmitter(); + * myEE.on('foo', () => {}); + * myEE.on('bar', () => {}); + * + * const sym = Symbol('symbol'); + * myEE.on(sym, () => {}); + * + * console.log(myEE.eventNames()); + * // Prints: [ 'foo', 'bar', Symbol(symbol) ] + * ``` + * @since v6.0.0 + */ + eventNames(): (string | symbol)[]; + /** + * Returns the current max listener value for the `EventEmitter` which is either + * set by `emitter.setMaxListeners(n)` or defaults to + * `events.defaultMaxListeners`. + * @since v1.0.0 + */ + getMaxListeners(): number; + /** + * Returns the number of listeners listening for the event named `eventName`. + * If `listener` is provided, it will return how many times the listener is found + * in the list of the listeners of the event. + * @since v3.2.0 + * @param eventName The name of the event being listened for + * @param listener The event handler function + */ + listenerCount(eventName: EventNames, listener?: Listener): number; + /** + * Returns a copy of the array of listeners for the event named `eventName`. + * + * ```js + * server.on('connection', (stream) => { + * console.log('someone connected!'); + * }); + * console.log(util.inspect(server.listeners('connection'))); + * // Prints: [ [Function] ] + * ``` + * @since v0.1.26 + */ + listeners(eventName: EventNames): Listener[]; + /** + * Alias for `emitter.removeListener()`. + * @since v10.0.0 + */ + off(eventName: EventNames, listener: Listener): this; + /** + * Adds the `listener` function to the end of the listeners array for the + * event named `eventName`. No checks are made to see if the `listener` has + * already been added. Multiple calls passing the same combination of `eventName` + * and `listener` will result in the `listener` being added, and called, multiple + * times. + * + * ```js + * server.on('connection', (stream) => { + * console.log('someone connected!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * + * By default, event listeners are invoked in the order they are added. The + * `emitter.prependListener()` method can be used as an alternative to add the + * event listener to the beginning of the listeners array. + * + * ```js + * import { EventEmitter } from 'node:events'; + * const myEE = new EventEmitter(); + * myEE.on('foo', () => console.log('a')); + * myEE.prependListener('foo', () => console.log('b')); + * myEE.emit('foo'); + * // Prints: + * // b + * // a + * ``` + * @since v0.1.101 + * @param eventName The name of the event. + * @param listener The callback function + */ + on(eventName: EventNames, listener: Listener): this; + /** + * Adds a **one-time** `listener` function for the event named `eventName`. The + * next time `eventName` is triggered, this listener is removed and then invoked. + * + * ```js + * server.once('connection', (stream) => { + * console.log('Ah, we have our first user!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * + * By default, event listeners are invoked in the order they are added. The + * `emitter.prependOnceListener()` method can be used as an alternative to add the + * event listener to the beginning of the listeners array. + * + * ```js + * import { EventEmitter } from 'node:events'; + * const myEE = new EventEmitter(); + * myEE.once('foo', () => console.log('a')); + * myEE.prependOnceListener('foo', () => console.log('b')); + * myEE.emit('foo'); + * // Prints: + * // b + * // a + * ``` + * @since v0.3.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + once(eventName: EventNames, listener: Listener): this; + /** + * Adds the `listener` function to the _beginning_ of the listeners array for the + * event named `eventName`. No checks are made to see if the `listener` has + * already been added. Multiple calls passing the same combination of `eventName` + * and `listener` will result in the `listener` being added, and called, multiple + * times. + * + * ```js + * server.prependListener('connection', (stream) => { + * console.log('someone connected!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v6.0.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + prependListener(eventName: EventNames, listener: Listener): this; + /** + * Adds a **one-time** `listener` function for the event named `eventName` to the + * _beginning_ of the listeners array. The next time `eventName` is triggered, this + * listener is removed, and then invoked. + * + * ```js + * server.prependOnceListener('connection', (stream) => { + * console.log('Ah, we have our first user!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v6.0.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + prependOnceListener(eventName: EventNames, listener: Listener): this; + /** + * Returns a copy of the array of listeners for the event named `eventName`, + * including any wrappers (such as those created by `.once()`). + * + * ```js + * import { EventEmitter } from 'node:events'; + * const emitter = new EventEmitter(); + * emitter.once('log', () => console.log('log once')); + * + * // Returns a new Array with a function `onceWrapper` which has a property + * // `listener` which contains the original listener bound above + * const listeners = emitter.rawListeners('log'); + * const logFnWrapper = listeners[0]; + * + * // Logs "log once" to the console and does not unbind the `once` event + * logFnWrapper.listener(); + * + * // Logs "log once" to the console and removes the listener + * logFnWrapper(); + * + * emitter.on('log', () => console.log('log persistently')); + * // Will return a new Array with a single function bound by `.on()` above + * const newListeners = emitter.rawListeners('log'); + * + * // Logs "log persistently" twice + * newListeners[0](); + * emitter.emit('log'); + * ``` + * @since v9.4.0 + */ + rawListeners(eventName: EventNames): Listener[]; + /** + * Removes all listeners, or those of the specified `eventName`. + * + * It is bad practice to remove listeners added elsewhere in the code, + * particularly when the `EventEmitter` instance was created by some other + * component or module (e.g. sockets or file streams). + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.1.26 + */ + removeAllListeners(eventName?: EventNames): this; + /** + * Removes the specified `listener` from the listener array for the event named + * `eventName`. + * + * ```js + * const callback = (stream) => { + * console.log('someone connected!'); + * }; + * server.on('connection', callback); + * // ... + * server.removeListener('connection', callback); + * ``` + * + * `removeListener()` will remove, at most, one instance of a listener from the + * listener array. If any single listener has been added multiple times to the + * listener array for the specified `eventName`, then `removeListener()` must be + * called multiple times to remove each instance. + * + * Once an event is emitted, all listeners attached to it at the + * time of emitting are called in order. This implies that any + * `removeListener()` or `removeAllListeners()` calls _after_ emitting and + * _before_ the last listener finishes execution will not remove them from + * `emit()` in progress. Subsequent events behave as expected. + * + * ```js + * import { EventEmitter } from 'node:events'; + * class MyEmitter extends EventEmitter {} + * const myEmitter = new MyEmitter(); + * + * const callbackA = () => { + * console.log('A'); + * myEmitter.removeListener('event', callbackB); + * }; + * + * const callbackB = () => { + * console.log('B'); + * }; + * + * myEmitter.on('event', callbackA); + * + * myEmitter.on('event', callbackB); + * + * // callbackA removes listener callbackB but it will still be called. + * // Internal listener array at time of emit [callbackA, callbackB] + * myEmitter.emit('event'); + * // Prints: + * // A + * // B + * + * // callbackB is now removed. + * // Internal listener array [callbackA] + * myEmitter.emit('event'); + * // Prints: + * // A + * ``` + * + * Because listeners are managed using an internal array, calling this will + * change the position indexes of any listener registered _after_ the listener + * being removed. This will not impact the order in which listeners are called, + * but it means that any copies of the listener array as returned by + * the `emitter.listeners()` method will need to be recreated. + * + * When a single function has been added as a handler multiple times for a single + * event (as in the example below), `removeListener()` will remove the most + * recently added instance. In the example the `once('ping')` + * listener is removed: + * + * ```js + * import { EventEmitter } from 'node:events'; + * const ee = new EventEmitter(); + * + * function pong() { + * console.log('pong'); + * } + * + * ee.on('ping', pong); + * ee.once('ping', pong); + * ee.removeListener('ping', pong); + * + * ee.emit('ping'); + * ee.emit('ping'); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.1.26 + */ + removeListener(eventName: EventNames, listener: Listener): this; + /** + * By default `EventEmitter`s will print a warning if more than `10` listeners are + * added for a particular event. This is a useful default that helps finding + * memory leaks. The `emitter.setMaxListeners()` method allows the limit to be + * modified for this specific `EventEmitter` instance. The value can be set to + * `Infinity` (or `0`) to indicate an unlimited number of listeners. + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.3.5 + */ + setMaxListeners(n: number): this; + } + namespace EventEmitter { + export { EventEmitter, EventEmitterEventMap, EventEmitterOptions }; + } + namespace EventEmitter { + interface Abortable { + signal?: AbortSignal | undefined; + } + /** + * See how to write a custom [rejection handler](https://nodejs.org/docs/latest-v25.x/api/events.html#emittersymbolfornodejsrejectionerr-eventname-args). + * @since v13.4.0, v12.16.0 + */ + const captureRejectionSymbol: unique symbol; + /** + * Change the default `captureRejections` option on all new `EventEmitter` objects. + * @since v13.4.0, v12.16.0 + */ + let captureRejections: boolean; + /** + * By default, a maximum of `10` listeners can be registered for any single + * event. This limit can be changed for individual `EventEmitter` instances + * using the `emitter.setMaxListeners(n)` method. To change the default + * for _all_ `EventEmitter` instances, the `events.defaultMaxListeners` + * property can be used. If this value is not a positive number, a `RangeError` + * is thrown. + * + * Take caution when setting the `events.defaultMaxListeners` because the + * change affects _all_ `EventEmitter` instances, including those created before + * the change is made. However, calling `emitter.setMaxListeners(n)` still has + * precedence over `events.defaultMaxListeners`. + * + * This is not a hard limit. The `EventEmitter` instance will allow + * more listeners to be added but will output a trace warning to stderr indicating + * that a "possible EventEmitter memory leak" has been detected. For any single + * `EventEmitter`, the `emitter.getMaxListeners()` and `emitter.setMaxListeners()` + * methods can be used to temporarily avoid this warning: + * + * `defaultMaxListeners` has no effect on `AbortSignal` instances. While it is + * still possible to use `emitter.setMaxListeners(n)` to set a warning limit + * for individual `AbortSignal` instances, per default `AbortSignal` instances will not warn. + * + * ```js + * import { EventEmitter } from 'node:events'; + * const emitter = new EventEmitter(); + * emitter.setMaxListeners(emitter.getMaxListeners() + 1); + * emitter.once('event', () => { + * // do stuff + * emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0)); + * }); + * ``` + * + * The `--trace-warnings` command-line flag can be used to display the + * stack trace for such warnings. + * + * The emitted warning can be inspected with `process.on('warning')` and will + * have the additional `emitter`, `type`, and `count` properties, referring to + * the event emitter instance, the event's name and the number of attached + * listeners, respectively. + * Its `name` property is set to `'MaxListenersExceededWarning'`. + * @since v0.11.2 + */ + let defaultMaxListeners: number; + /** + * This symbol shall be used to install a listener for only monitoring `'error'` + * events. Listeners installed using this symbol are called before the regular + * `'error'` listeners are called. + * + * Installing a listener using this symbol does not change the behavior once an + * `'error'` event is emitted. Therefore, the process will still crash if no + * regular `'error'` listener is installed. + * @since v13.6.0, v12.17.0 + */ + const errorMonitor: unique symbol; + /** + * Listens once to the `abort` event on the provided `signal`. + * + * Listening to the `abort` event on abort signals is unsafe and may + * lead to resource leaks since another third party with the signal can + * call `e.stopImmediatePropagation()`. Unfortunately Node.js cannot change + * this since it would violate the web standard. Additionally, the original + * API makes it easy to forget to remove listeners. + * + * This API allows safely using `AbortSignal`s in Node.js APIs by solving these + * two issues by listening to the event such that `stopImmediatePropagation` does + * not prevent the listener from running. + * + * Returns a disposable so that it may be unsubscribed from more easily. + * + * ```js + * import { addAbortListener } from 'node:events'; + * + * function example(signal) { + * let disposable; + * try { + * signal.addEventListener('abort', (e) => e.stopImmediatePropagation()); + * disposable = addAbortListener(signal, (e) => { + * // Do something when signal is aborted. + * }); + * } finally { + * disposable?.[Symbol.dispose](); + * } + * } + * ``` + * @since v20.5.0 + * @return Disposable that removes the `abort` listener. + */ + function addAbortListener(signal: AbortSignal, resource: (event: Event) => void): Disposable; + /** + * Returns a copy of the array of listeners for the event named `eventName`. + * + * For `EventEmitter`s this behaves exactly the same as calling `.listeners` on + * the emitter. + * + * For `EventTarget`s this is the only way to get the event listeners for the + * event target. This is useful for debugging and diagnostic purposes. + * + * ```js + * import { getEventListeners, EventEmitter } from 'node:events'; + * + * { + * const ee = new EventEmitter(); + * const listener = () => console.log('Events are fun'); + * ee.on('foo', listener); + * console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ] + * } + * { + * const et = new EventTarget(); + * const listener = () => console.log('Events are fun'); + * et.addEventListener('foo', listener); + * console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ] + * } + * ``` + * @since v15.2.0, v14.17.0 + */ + function getEventListeners(emitter: NodeJS.EventEmitter, name: string | symbol): ((...args: any[]) => void)[]; + function getEventListeners(emitter: EventTarget, name: string): ((...args: any[]) => void)[]; + /** + * Returns the currently set max amount of listeners. + * + * For `EventEmitter`s this behaves exactly the same as calling `.getMaxListeners` on + * the emitter. + * + * For `EventTarget`s this is the only way to get the max event listeners for the + * event target. If the number of event handlers on a single EventTarget exceeds + * the max set, the EventTarget will print a warning. + * + * ```js + * import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events'; + * + * { + * const ee = new EventEmitter(); + * console.log(getMaxListeners(ee)); // 10 + * setMaxListeners(11, ee); + * console.log(getMaxListeners(ee)); // 11 + * } + * { + * const et = new EventTarget(); + * console.log(getMaxListeners(et)); // 10 + * setMaxListeners(11, et); + * console.log(getMaxListeners(et)); // 11 + * } + * ``` + * @since v19.9.0 + */ + function getMaxListeners(emitter: NodeJS.EventEmitter | EventTarget): number; + /** + * A class method that returns the number of listeners for the given `eventName` + * registered on the given `emitter`. + * + * ```js + * import { EventEmitter, listenerCount } from 'node:events'; + * + * const myEmitter = new EventEmitter(); + * myEmitter.on('event', () => {}); + * myEmitter.on('event', () => {}); + * console.log(listenerCount(myEmitter, 'event')); + * // Prints: 2 + * ``` + * @since v0.9.12 + * @deprecated Use `emitter.listenerCount()` instead. + * @param emitter The emitter to query + * @param eventName The event name + */ + function listenerCount(emitter: NodeJS.EventEmitter, eventName: string | symbol): number; + interface OnOptions extends Abortable { + /** + * Names of events that will end the iteration. + */ + close?: readonly string[] | undefined; + /** + * The high watermark. The emitter is paused every time the size of events + * being buffered is higher than it. Supported only on emitters implementing + * `pause()` and `resume()` methods. + * @default Number.MAX_SAFE_INTEGER + */ + highWaterMark?: number | undefined; + /** + * The low watermark. The emitter is resumed every time the size of events + * being buffered is lower than it. Supported only on emitters implementing + * `pause()` and `resume()` methods. + * @default 1 + */ + lowWaterMark?: number | undefined; + } + /** + * ```js + * import { on, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * const ee = new EventEmitter(); + * + * // Emit later on + * process.nextTick(() => { + * ee.emit('foo', 'bar'); + * ee.emit('foo', 42); + * }); + * + * for await (const event of on(ee, 'foo')) { + * // The execution of this inner block is synchronous and it + * // processes one event at a time (even with await). Do not use + * // if concurrent execution is required. + * console.log(event); // prints ['bar'] [42] + * } + * // Unreachable here + * ``` + * + * Returns an `AsyncIterator` that iterates `eventName` events. It will throw + * if the `EventEmitter` emits `'error'`. It removes all listeners when + * exiting the loop. The `value` returned by each iteration is an array + * composed of the emitted event arguments. + * + * An `AbortSignal` can be used to cancel waiting on events: + * + * ```js + * import { on, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * const ac = new AbortController(); + * + * (async () => { + * const ee = new EventEmitter(); + * + * // Emit later on + * process.nextTick(() => { + * ee.emit('foo', 'bar'); + * ee.emit('foo', 42); + * }); + * + * for await (const event of on(ee, 'foo', { signal: ac.signal })) { + * // The execution of this inner block is synchronous and it + * // processes one event at a time (even with await). Do not use + * // if concurrent execution is required. + * console.log(event); // prints ['bar'] [42] + * } + * // Unreachable here + * })(); + * + * process.nextTick(() => ac.abort()); + * ``` + * @since v13.6.0, v12.16.0 + * @returns `AsyncIterator` that iterates `eventName` events emitted by the `emitter` + */ + function on( + emitter: NodeJS.EventEmitter, + eventName: string | symbol, + options?: OnOptions, + ): NodeJS.AsyncIterator; + function on( + emitter: EventTarget, + eventName: string, + options?: OnOptions, + ): NodeJS.AsyncIterator; + interface OnceOptions extends Abortable {} + /** + * Creates a `Promise` that is fulfilled when the `EventEmitter` emits the given + * event or that is rejected if the `EventEmitter` emits `'error'` while waiting. + * The `Promise` will resolve with an array of all the arguments emitted to the + * given event. + * + * This method is intentionally generic and works with the web platform + * [EventTarget][WHATWG-EventTarget] interface, which has no special + * `'error'` event semantics and does not listen to the `'error'` event. + * + * ```js + * import { once, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * const ee = new EventEmitter(); + * + * process.nextTick(() => { + * ee.emit('myevent', 42); + * }); + * + * const [value] = await once(ee, 'myevent'); + * console.log(value); + * + * const err = new Error('kaboom'); + * process.nextTick(() => { + * ee.emit('error', err); + * }); + * + * try { + * await once(ee, 'myevent'); + * } catch (err) { + * console.error('error happened', err); + * } + * ``` + * + * The special handling of the `'error'` event is only used when `events.once()` + * is used to wait for another event. If `events.once()` is used to wait for the + * '`error'` event itself, then it is treated as any other kind of event without + * special handling: + * + * ```js + * import { EventEmitter, once } from 'node:events'; + * + * const ee = new EventEmitter(); + * + * once(ee, 'error') + * .then(([err]) => console.log('ok', err.message)) + * .catch((err) => console.error('error', err.message)); + * + * ee.emit('error', new Error('boom')); + * + * // Prints: ok boom + * ``` + * + * An `AbortSignal` can be used to cancel waiting for the event: + * + * ```js + * import { EventEmitter, once } from 'node:events'; + * + * const ee = new EventEmitter(); + * const ac = new AbortController(); + * + * async function foo(emitter, event, signal) { + * try { + * await once(emitter, event, { signal }); + * console.log('event emitted!'); + * } catch (error) { + * if (error.name === 'AbortError') { + * console.error('Waiting for the event was canceled!'); + * } else { + * console.error('There was an error', error.message); + * } + * } + * } + * + * foo(ee, 'foo', ac.signal); + * ac.abort(); // Prints: Waiting for the event was canceled! + * ``` + * @since v11.13.0, v10.16.0 + */ + function once( + emitter: NodeJS.EventEmitter, + eventName: string | symbol, + options?: OnceOptions, + ): Promise; + function once(emitter: EventTarget, eventName: string, options?: OnceOptions): Promise; + /** + * ```js + * import { setMaxListeners, EventEmitter } from 'node:events'; + * + * const target = new EventTarget(); + * const emitter = new EventEmitter(); + * + * setMaxListeners(5, target, emitter); + * ``` + * @since v15.4.0 + * @param n A non-negative number. The maximum number of listeners per `EventTarget` event. + * @param eventTargets Zero or more `EventTarget` + * or `EventEmitter` instances. If none are specified, `n` is set as the default + * max for all newly created `EventTarget` and `EventEmitter` objects. + * objects. + */ + function setMaxListeners(n: number, ...eventTargets: ReadonlyArray): void; + /** + * This is the interface from which event-emitting Node.js APIs inherit in the types package. + * **It is not intended for consumer use.** + * + * It provides event-mapped definitions similar to EventEmitter, except that its signatures + * are deliberately permissive: they provide type _hinting_, but not rigid type-checking, + * for compatibility reasons. + * + * Classes that inherit directly from EventEmitter in JavaScript can inherit directly from + * this interface in the type definitions. Classes that are more than one inheritance level + * away from EventEmitter (eg. `net.Socket` > `stream.Duplex` > `EventEmitter`) must instead + * copy these method definitions into the derived class. Search "#region InternalEventEmitter" + * for examples. + * @internal + */ + interface InternalEventEmitter> extends EventEmitter { + addListener(eventName: E, listener: (...args: T[E]) => void): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: T[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount(eventName: E, listener?: (...args: T[E]) => void): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners(eventName: E): ((...args: T[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off(eventName: E, listener: (...args: T[E]) => void): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on(eventName: E, listener: (...args: T[E]) => void): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once(eventName: E, listener: (...args: T[E]) => void): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener(eventName: E, listener: (...args: T[E]) => void): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(eventName: E, listener: (...args: T[E]) => void): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners(eventName: E): ((...args: T[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener(eventName: E, listener: (...args: T[E]) => void): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + } + interface EventEmitterReferencingAsyncResource extends AsyncResource { + readonly eventEmitter: EventEmitterAsyncResource; + } + interface EventEmitterAsyncResourceOptions extends AsyncResourceOptions, EventEmitterOptions { + /** + * The type of async event. + * @default new.target.name + */ + name?: string | undefined; + } + /** + * Integrates `EventEmitter` with `AsyncResource` for `EventEmitter`s that + * require manual async tracking. Specifically, all events emitted by instances + * of `events.EventEmitterAsyncResource` will run within its [async context](https://nodejs.org/docs/latest-v25.x/api/async_context.html). + * + * ```js + * import { EventEmitterAsyncResource, EventEmitter } from 'node:events'; + * import { notStrictEqual, strictEqual } from 'node:assert'; + * import { executionAsyncId, triggerAsyncId } from 'node:async_hooks'; + * + * // Async tracking tooling will identify this as 'Q'. + * const ee1 = new EventEmitterAsyncResource({ name: 'Q' }); + * + * // 'foo' listeners will run in the EventEmitters async context. + * ee1.on('foo', () => { + * strictEqual(executionAsyncId(), ee1.asyncId); + * strictEqual(triggerAsyncId(), ee1.triggerAsyncId); + * }); + * + * const ee2 = new EventEmitter(); + * + * // 'foo' listeners on ordinary EventEmitters that do not track async + * // context, however, run in the same async context as the emit(). + * ee2.on('foo', () => { + * notStrictEqual(executionAsyncId(), ee2.asyncId); + * notStrictEqual(triggerAsyncId(), ee2.triggerAsyncId); + * }); + * + * Promise.resolve().then(() => { + * ee1.emit('foo'); + * ee2.emit('foo'); + * }); + * ``` + * + * The `EventEmitterAsyncResource` class has the same methods and takes the + * same options as `EventEmitter` and `AsyncResource` themselves. + * @since v17.4.0, v16.14.0 + */ + class EventEmitterAsyncResource extends EventEmitter { + constructor(options?: EventEmitterAsyncResourceOptions); + /** + * The unique `asyncId` assigned to the resource. + */ + readonly asyncId: number; + /** + * The returned `AsyncResource` object has an additional `eventEmitter` property + * that provides a reference to this `EventEmitterAsyncResource`. + */ + readonly asyncResource: EventEmitterReferencingAsyncResource; + /** + * Call all `destroy` hooks. This should only ever be called once. An error will + * be thrown if it is called more than once. This **must** be manually called. If + * the resource is left to be collected by the GC then the `destroy` hooks will + * never be called. + */ + emitDestroy(): void; + /** + * The same `triggerAsyncId` that is passed to the + * `AsyncResource` constructor. + */ + readonly triggerAsyncId: number; + } + /** + * The `NodeEventTarget` is a Node.js-specific extension to `EventTarget` + * that emulates a subset of the `EventEmitter` API. + * @since v14.5.0 + */ + interface NodeEventTarget extends EventTarget { + /** + * Node.js-specific extension to the `EventTarget` class that emulates the + * equivalent `EventEmitter` API. The only difference between `addListener()` and + * `addEventListener()` is that `addListener()` will return a reference to the + * `EventTarget`. + * @since v14.5.0 + */ + addListener(type: string, listener: (arg: any) => void): this; + /** + * Node.js-specific extension to the `EventTarget` class that dispatches the + * `arg` to the list of handlers for `type`. + * @since v15.2.0 + * @returns `true` if event listeners registered for the `type` exist, + * otherwise `false`. + */ + emit(type: string, arg: any): boolean; + /** + * Node.js-specific extension to the `EventTarget` class that returns an array + * of event `type` names for which event listeners are registered. + * @since 14.5.0 + */ + eventNames(): string[]; + /** + * Node.js-specific extension to the `EventTarget` class that returns the number + * of event listeners registered for the `type`. + * @since v14.5.0 + */ + listenerCount(type: string): number; + /** + * Node.js-specific extension to the `EventTarget` class that sets the number + * of max event listeners as `n`. + * @since v14.5.0 + */ + setMaxListeners(n: number): void; + /** + * Node.js-specific extension to the `EventTarget` class that returns the number + * of max event listeners. + * @since v14.5.0 + */ + getMaxListeners(): number; + /** + * Node.js-specific alias for `eventTarget.removeEventListener()`. + * @since v14.5.0 + */ + off(type: string, listener: (arg: any) => void, options?: EventListenerOptions): this; + /** + * Node.js-specific alias for `eventTarget.addEventListener()`. + * @since v14.5.0 + */ + on(type: string, listener: (arg: any) => void): this; + /** + * Node.js-specific extension to the `EventTarget` class that adds a `once` + * listener for the given event `type`. This is equivalent to calling `on` + * with the `once` option set to `true`. + * @since v14.5.0 + */ + once(type: string, listener: (arg: any) => void): this; + /** + * Node.js-specific extension to the `EventTarget` class. If `type` is specified, + * removes all registered listeners for `type`, otherwise removes all registered + * listeners. + * @since v14.5.0 + */ + removeAllListeners(type?: string): this; + /** + * Node.js-specific extension to the `EventTarget` class that removes the + * `listener` for the given `type`. The only difference between `removeListener()` + * and `removeEventListener()` is that `removeListener()` will return a reference + * to the `EventTarget`. + * @since v14.5.0 + */ + removeListener(type: string, listener: (arg: any) => void, options?: EventListenerOptions): this; + } + /** @internal */ + type InternalEventTargetEventProperties = { + [K in keyof T & string as `on${K}`]: ((ev: T[K]) => void) | null; + }; + } + global { + import _ = EventEmitter; + namespace NodeJS { + interface EventEmitter = any> extends _ {} + } + } + export = EventEmitter; +} +declare module "events" { + import events = require("node:events"); + export = events; +} diff --git a/backend/node_modules/@types/node/fs.d.ts b/backend/node_modules/@types/node/fs.d.ts new file mode 100644 index 0000000..6eb6984 --- /dev/null +++ b/backend/node_modules/@types/node/fs.d.ts @@ -0,0 +1,4676 @@ +/** + * The `node:fs` module enables interacting with the file system in a + * way modeled on standard POSIX functions. + * + * To use the promise-based APIs: + * + * ```js + * import * as fs from 'node:fs/promises'; + * ``` + * + * To use the callback and sync APIs: + * + * ```js + * import * as fs from 'node:fs'; + * ``` + * + * All file system operations have synchronous, callback, and promise-based + * forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM). + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/fs.js) + */ +declare module "node:fs" { + import { NonSharedBuffer } from "node:buffer"; + import { Abortable, EventEmitter, InternalEventEmitter } from "node:events"; + import { FileHandle } from "node:fs/promises"; + import * as stream from "node:stream"; + import { URL } from "node:url"; + /** + * Valid types for path values in "fs". + */ + type PathLike = string | Buffer | URL; + type PathOrFileDescriptor = PathLike | number; + type TimeLike = string | number | Date; + type NoParamCallback = (err: NodeJS.ErrnoException | null) => void; + type BufferEncodingOption = + | "buffer" + | { + encoding: "buffer"; + }; + interface ObjectEncodingOptions { + encoding?: BufferEncoding | null | undefined; + } + type EncodingOption = ObjectEncodingOptions | BufferEncoding | undefined | null; + type OpenMode = number | string; + type Mode = number | string; + interface StatsBase { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + dev: T; + ino: T; + mode: T; + nlink: T; + uid: T; + gid: T; + rdev: T; + size: T; + blksize: T; + blocks: T; + atimeMs: T; + mtimeMs: T; + ctimeMs: T; + birthtimeMs: T; + atime: Date; + mtime: Date; + ctime: Date; + birthtime: Date; + } + interface Stats extends StatsBase {} + /** + * A `fs.Stats` object provides information about a file. + * + * Objects returned from {@link stat}, {@link lstat}, {@link fstat}, and + * their synchronous counterparts are of this type. + * If `bigint` in the `options` passed to those methods is true, the numeric values + * will be `bigint` instead of `number`, and the object will contain additional + * nanosecond-precision properties suffixed with `Ns`. `Stat` objects are not to be created directly using the `new` keyword. + * + * ```console + * Stats { + * dev: 2114, + * ino: 48064969, + * mode: 33188, + * nlink: 1, + * uid: 85, + * gid: 100, + * rdev: 0, + * size: 527, + * blksize: 4096, + * blocks: 8, + * atimeMs: 1318289051000.1, + * mtimeMs: 1318289051000.1, + * ctimeMs: 1318289051000.1, + * birthtimeMs: 1318289051000.1, + * atime: Mon, 10 Oct 2011 23:24:11 GMT, + * mtime: Mon, 10 Oct 2011 23:24:11 GMT, + * ctime: Mon, 10 Oct 2011 23:24:11 GMT, + * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } + * ``` + * + * `bigint` version: + * + * ```console + * BigIntStats { + * dev: 2114n, + * ino: 48064969n, + * mode: 33188n, + * nlink: 1n, + * uid: 85n, + * gid: 100n, + * rdev: 0n, + * size: 527n, + * blksize: 4096n, + * blocks: 8n, + * atimeMs: 1318289051000n, + * mtimeMs: 1318289051000n, + * ctimeMs: 1318289051000n, + * birthtimeMs: 1318289051000n, + * atimeNs: 1318289051000000000n, + * mtimeNs: 1318289051000000000n, + * ctimeNs: 1318289051000000000n, + * birthtimeNs: 1318289051000000000n, + * atime: Mon, 10 Oct 2011 23:24:11 GMT, + * mtime: Mon, 10 Oct 2011 23:24:11 GMT, + * ctime: Mon, 10 Oct 2011 23:24:11 GMT, + * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } + * ``` + * @since v0.1.21 + */ + class Stats { + private constructor(); + } + interface StatsFsBase { + /** Type of file system. */ + type: T; + /** Optimal transfer block size. */ + bsize: T; + /** Total data blocks in file system. */ + blocks: T; + /** Free blocks in file system. */ + bfree: T; + /** Available blocks for unprivileged users */ + bavail: T; + /** Total file nodes in file system. */ + files: T; + /** Free file nodes in file system. */ + ffree: T; + } + interface StatsFs extends StatsFsBase {} + /** + * Provides information about a mounted file system. + * + * Objects returned from {@link statfs} and its synchronous counterpart are of + * this type. If `bigint` in the `options` passed to those methods is `true`, the + * numeric values will be `bigint` instead of `number`. + * + * ```console + * StatFs { + * type: 1397114950, + * bsize: 4096, + * blocks: 121938943, + * bfree: 61058895, + * bavail: 61058895, + * files: 999, + * ffree: 1000000 + * } + * ``` + * + * `bigint` version: + * + * ```console + * StatFs { + * type: 1397114950n, + * bsize: 4096n, + * blocks: 121938943n, + * bfree: 61058895n, + * bavail: 61058895n, + * files: 999n, + * ffree: 1000000n + * } + * ``` + * @since v19.6.0, v18.15.0 + */ + class StatsFs {} + interface BigIntStatsFs extends StatsFsBase {} + interface StatFsOptions { + bigint?: boolean | undefined; + } + /** + * A representation of a directory entry, which can be a file or a subdirectory + * within the directory, as returned by reading from an `fs.Dir`. The + * directory entry is a combination of the file name and file type pairs. + * + * Additionally, when {@link readdir} or {@link readdirSync} is called with + * the `withFileTypes` option set to `true`, the resulting array is filled with `fs.Dirent` objects, rather than strings or `Buffer` s. + * @since v10.10.0 + */ + class Dirent { + /** + * Returns `true` if the `fs.Dirent` object describes a regular file. + * @since v10.10.0 + */ + isFile(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a file system + * directory. + * @since v10.10.0 + */ + isDirectory(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a block device. + * @since v10.10.0 + */ + isBlockDevice(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a character device. + * @since v10.10.0 + */ + isCharacterDevice(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a symbolic link. + * @since v10.10.0 + */ + isSymbolicLink(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a first-in-first-out + * (FIFO) pipe. + * @since v10.10.0 + */ + isFIFO(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a socket. + * @since v10.10.0 + */ + isSocket(): boolean; + /** + * The file name that this `fs.Dirent` object refers to. The type of this + * value is determined by the `options.encoding` passed to {@link readdir} or {@link readdirSync}. + * @since v10.10.0 + */ + name: Name; + /** + * The path to the parent directory of the file this `fs.Dirent` object refers to. + * @since v20.12.0, v18.20.0 + */ + parentPath: string; + } + /** + * A class representing a directory stream. + * + * Created by {@link opendir}, {@link opendirSync}, or `fsPromises.opendir()`. + * + * ```js + * import { opendir } from 'node:fs/promises'; + * + * try { + * const dir = await opendir('./'); + * for await (const dirent of dir) + * console.log(dirent.name); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * When using the async iterator, the `fs.Dir` object will be automatically + * closed after the iterator exits. + * @since v12.12.0 + */ + class Dir implements AsyncIterable { + /** + * The read-only path of this directory as was provided to {@link opendir},{@link opendirSync}, or `fsPromises.opendir()`. + * @since v12.12.0 + */ + readonly path: string; + /** + * Asynchronously iterates over the directory via `readdir(3)` until all entries have been read. + */ + [Symbol.asyncIterator](): NodeJS.AsyncIterator; + /** + * Asynchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + * + * A promise is returned that will be fulfilled after the resource has been + * closed. + * @since v12.12.0 + */ + close(): Promise; + close(cb: NoParamCallback): void; + /** + * Synchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + * @since v12.12.0 + */ + closeSync(): void; + /** + * Asynchronously read the next directory entry via [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) as an `fs.Dirent`. + * + * A promise is returned that will be fulfilled with an `fs.Dirent`, or `null` if there are no more directory entries to read. + * + * Directory entries returned by this function are in no particular order as + * provided by the operating system's underlying directory mechanisms. + * Entries added or removed while iterating over the directory might not be + * included in the iteration results. + * @since v12.12.0 + * @return containing {fs.Dirent|null} + */ + read(): Promise; + read(cb: (err: NodeJS.ErrnoException | null, dirEnt: Dirent | null) => void): void; + /** + * Synchronously read the next directory entry as an `fs.Dirent`. See the + * POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more detail. + * + * If there are no more directory entries to read, `null` will be returned. + * + * Directory entries returned by this function are in no particular order as + * provided by the operating system's underlying directory mechanisms. + * Entries added or removed while iterating over the directory might not be + * included in the iteration results. + * @since v12.12.0 + */ + readSync(): Dirent | null; + /** + * Calls `dir.close()` if the directory handle is open, and returns a promise that + * fulfills when disposal is complete. + * @since v24.1.0 + */ + [Symbol.asyncDispose](): Promise; + /** + * Calls `dir.closeSync()` if the directory handle is open, and returns + * `undefined`. + * @since v24.1.0 + */ + [Symbol.dispose](): void; + } + /** + * Class: fs.StatWatcher + * @since v14.3.0, v12.20.0 + * Extends `EventEmitter` + * A successful call to {@link watchFile} method will return a new fs.StatWatcher object. + */ + interface StatWatcher extends EventEmitter { + /** + * When called, requests that the Node.js event loop _not_ exit so long as the `fs.StatWatcher` is active. Calling `watcher.ref()` multiple times will have + * no effect. + * + * By default, all `fs.StatWatcher` objects are "ref'ed", making it normally + * unnecessary to call `watcher.ref()` unless `watcher.unref()` had been + * called previously. + * @since v14.3.0, v12.20.0 + */ + ref(): this; + /** + * When called, the active `fs.StatWatcher` object will not require the Node.js + * event loop to remain active. If there is no other activity keeping the + * event loop running, the process may exit before the `fs.StatWatcher` object's + * callback is invoked. Calling `watcher.unref()` multiple times will have + * no effect. + * @since v14.3.0, v12.20.0 + */ + unref(): this; + } + interface FSWatcherEventMap { + "change": [eventType: string, filename: string | NonSharedBuffer]; + "close": []; + "error": [error: Error]; + } + interface FSWatcher extends InternalEventEmitter { + /** + * Stop watching for changes on the given `fs.FSWatcher`. Once stopped, the `fs.FSWatcher` object is no longer usable. + * @since v0.5.8 + */ + close(): void; + /** + * When called, requests that the Node.js event loop _not_ exit so long as the `fs.FSWatcher` is active. Calling `watcher.ref()` multiple times will have + * no effect. + * + * By default, all `fs.FSWatcher` objects are "ref'ed", making it normally + * unnecessary to call `watcher.ref()` unless `watcher.unref()` had been + * called previously. + * @since v14.3.0, v12.20.0 + */ + ref(): this; + /** + * When called, the active `fs.FSWatcher` object will not require the Node.js + * event loop to remain active. If there is no other activity keeping the + * event loop running, the process may exit before the `fs.FSWatcher` object's + * callback is invoked. Calling `watcher.unref()` multiple times will have + * no effect. + * @since v14.3.0, v12.20.0 + */ + unref(): this; + } + interface ReadStreamEventMap extends stream.ReadableEventMap { + "close": []; + "data": [chunk: string | NonSharedBuffer]; + "open": [fd: number]; + "ready": []; + } + /** + * Instances of `fs.ReadStream` are created and returned using the {@link createReadStream} function. + * @since v0.1.93 + */ + class ReadStream extends stream.Readable { + close(callback?: (err?: NodeJS.ErrnoException | null) => void): void; + /** + * The number of bytes that have been read so far. + * @since v6.4.0 + */ + bytesRead: number; + /** + * The path to the file the stream is reading from as specified in the first + * argument to `fs.createReadStream()`. If `path` is passed as a string, then`readStream.path` will be a string. If `path` is passed as a `Buffer`, then`readStream.path` will be a + * `Buffer`. If `fd` is specified, then`readStream.path` will be `undefined`. + * @since v0.1.93 + */ + path: string | Buffer; + /** + * This property is `true` if the underlying file has not been opened yet, + * i.e. before the `'ready'` event is emitted. + * @since v11.2.0, v10.16.0 + */ + pending: boolean; + // #region InternalEventEmitter + addListener( + eventName: E, + listener: (...args: ReadStreamEventMap[E]) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: ReadStreamEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: ReadStreamEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners(eventName: E): ((...args: ReadStreamEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off(eventName: E, listener: (...args: ReadStreamEventMap[E]) => void): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on(eventName: E, listener: (...args: ReadStreamEventMap[E]) => void): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: (...args: ReadStreamEventMap[E]) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: ReadStreamEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: ReadStreamEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners(eventName: E): ((...args: ReadStreamEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: ReadStreamEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + interface Utf8StreamOptions { + /** + * Appends writes to dest file instead of truncating it. + * @default true + */ + append?: boolean | undefined; + /** + * Which type of data you can send to the write + * function, supported values are `'utf8'` or `'buffer'`. + * @default 'utf8' + */ + contentMode?: "utf8" | "buffer" | undefined; + /** + * A path to a file to be written to (mode controlled by the + * append option). + */ + dest?: string | undefined; + /** + * A file descriptor, something that is returned by `fs.open()` + * or `fs.openSync()`. + */ + fd?: number | undefined; + /** + * An object that has the same API as the `fs` module, useful + * for mocking, testing, or customizing the behavior of the stream. + */ + fs?: object | undefined; + /** + * Perform a `fs.fsyncSync()` every time a write is + * completed. + */ + fsync?: boolean | undefined; + /** + * The maximum length of the internal buffer. If a write + * operation would cause the buffer to exceed `maxLength`, the data written is + * dropped and a drop event is emitted with the dropped data + */ + maxLength?: number | undefined; + /** + * The maximum number of bytes that can be written; + * @default 16384 + */ + maxWrite?: number | undefined; + /** + * The minimum length of the internal buffer that is + * required to be full before flushing. + */ + minLength?: number | undefined; + /** + * Ensure directory for `dest` file exists when true. + * @default false + */ + mkdir?: boolean | undefined; + /** + * Specify the creating file mode (see `fs.open()`). + */ + mode?: number | string | undefined; + /** + * Calls flush every `periodicFlush` milliseconds. + */ + periodicFlush?: number | undefined; + /** + * A function that will be called when `write()`, + * `writeSync()`, or `flushSync()` encounters an `EAGAIN` or `EBUSY` error. + * If the return value is `true` the operation will be retried, otherwise it + * will bubble the error. The `err` is the error that caused this function to + * be called, `writeBufferLen` is the length of the buffer that was written, + * and `remainingBufferLen` is the length of the remaining buffer that the + * stream did not try to write. + */ + retryEAGAIN?: ((err: Error | null, writeBufferLen: number, remainingBufferLen: number) => boolean) | undefined; + /** + * Perform writes synchronously. + */ + sync?: boolean | undefined; + } + interface Utf8StreamEventMap { + "close": []; + "drain": []; + "drop": [data: string | Buffer]; + "error": [error: Error]; + "finish": []; + "ready": []; + "write": [n: number]; + } + /** + * An optimized UTF-8 stream writer that allows for flushing all the internal + * buffering on demand. It handles `EAGAIN` errors correctly, allowing for + * customization, for example, by dropping content if the disk is busy. + * @since v24.6.0 + * @experimental + */ + class Utf8Stream implements EventEmitter { + constructor(options: Utf8StreamOptions); + /** + * Whether the stream is appending to the file or truncating it. + */ + readonly append: boolean; + /** + * The type of data that can be written to the stream. Supported + * values are `'utf8'` or `'buffer'`. + * @default 'utf8' + */ + readonly contentMode: "utf8" | "buffer"; + /** + * Close the stream immediately, without flushing the internal buffer. + */ + destroy(): void; + /** + * Close the stream gracefully, flushing the internal buffer before closing. + */ + end(): void; + /** + * The file descriptor that is being written to. + */ + readonly fd: number; + /** + * The file that is being written to. + */ + readonly file: string; + /** + * Writes the current buffer to the file if a write was not in progress. Do + * nothing if `minLength` is zero or if it is already writing. + */ + flush(callback: (err: Error | null) => void): void; + /** + * Flushes the buffered data synchronously. This is a costly operation. + */ + flushSync(): void; + /** + * Whether the stream is performing a `fs.fsyncSync()` after every + * write operation. + */ + readonly fsync: boolean; + /** + * The maximum length of the internal buffer. If a write + * operation would cause the buffer to exceed `maxLength`, the data written is + * dropped and a drop event is emitted with the dropped data. + */ + readonly maxLength: number; + /** + * The minimum length of the internal buffer that is required to be + * full before flushing. + */ + readonly minLength: number; + /** + * Whether the stream should ensure that the directory for the + * `dest` file exists. If `true`, it will create the directory if it does not + * exist. + * @default false + */ + readonly mkdir: boolean; + /** + * The mode of the file that is being written to. + */ + readonly mode: number | string; + /** + * The number of milliseconds between flushes. If set to `0`, no + * periodic flushes will be performed. + */ + readonly periodicFlush: number; + /** + * Reopen the file in place, useful for log rotation. + * @param file A path to a file to be written to (mode + * controlled by the append option). + */ + reopen(file: PathLike): void; + /** + * Whether the stream is writing synchronously or asynchronously. + */ + readonly sync: boolean; + /** + * When the `options.contentMode` is set to `'utf8'` when the stream is created, + * the `data` argument must be a string. If the `contentMode` is set to `'buffer'`, + * the `data` argument must be a `Buffer`. + * @param data The data to write. + */ + write(data: string | Buffer): boolean; + /** + * Whether the stream is currently writing data to the file. + */ + readonly writing: boolean; + /** + * Calls `utf8Stream.destroy()`. + */ + [Symbol.dispose](): void; + } + interface Utf8Stream extends InternalEventEmitter {} + interface WriteStreamEventMap extends stream.WritableEventMap { + "close": []; + "open": [fd: number]; + "ready": []; + } + /** + * Instances of `fs.WriteStream` are created and returned using the {@link createWriteStream} function. + * @since v0.1.93 + */ + class WriteStream extends stream.Writable { + /** + * Closes `writeStream`. Optionally accepts a + * callback that will be executed once the `writeStream`is closed. + * @since v0.9.4 + */ + close(callback?: (err?: NodeJS.ErrnoException | null) => void): void; + /** + * The number of bytes written so far. Does not include data that is still queued + * for writing. + * @since v0.4.7 + */ + bytesWritten: number; + /** + * The path to the file the stream is writing to as specified in the first + * argument to {@link createWriteStream}. If `path` is passed as a string, then`writeStream.path` will be a string. If `path` is passed as a `Buffer`, then`writeStream.path` will be a + * `Buffer`. + * @since v0.1.93 + */ + path: string | Buffer; + /** + * This property is `true` if the underlying file has not been opened yet, + * i.e. before the `'ready'` event is emitted. + * @since v11.2.0 + */ + pending: boolean; + // #region InternalEventEmitter + addListener( + eventName: E, + listener: (...args: WriteStreamEventMap[E]) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: WriteStreamEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: WriteStreamEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners(eventName: E): ((...args: WriteStreamEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off( + eventName: E, + listener: (...args: WriteStreamEventMap[E]) => void, + ): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on( + eventName: E, + listener: (...args: WriteStreamEventMap[E]) => void, + ): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: (...args: WriteStreamEventMap[E]) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: WriteStreamEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: WriteStreamEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners(eventName: E): ((...args: WriteStreamEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: WriteStreamEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + /** + * Asynchronously rename file at `oldPath` to the pathname provided + * as `newPath`. In the case that `newPath` already exists, it will + * be overwritten. If there is a directory at `newPath`, an error will + * be raised instead. No arguments other than a possible exception are + * given to the completion callback. + * + * See also: [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html). + * + * ```js + * import { rename } from 'node:fs'; + * + * rename('oldFile.txt', 'newFile.txt', (err) => { + * if (err) throw err; + * console.log('Rename complete!'); + * }); + * ``` + * @since v0.0.2 + */ + function rename(oldPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + namespace rename { + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(oldPath: PathLike, newPath: PathLike): Promise; + } + /** + * Renames the file from `oldPath` to `newPath`. Returns `undefined`. + * + * See the POSIX [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html) documentation for more details. + * @since v0.1.21 + */ + function renameSync(oldPath: PathLike, newPath: PathLike): void; + /** + * Truncates the file. No arguments other than a possible exception are + * given to the completion callback. A file descriptor can also be passed as the + * first argument. In this case, `fs.ftruncate()` is called. + * + * ```js + * import { truncate } from 'node:fs'; + * // Assuming that 'path/file.txt' is a regular file. + * truncate('path/file.txt', (err) => { + * if (err) throw err; + * console.log('path/file.txt was truncated'); + * }); + * ``` + * + * Passing a file descriptor is deprecated and may result in an error being thrown + * in the future. + * + * See the POSIX [`truncate(2)`](http://man7.org/linux/man-pages/man2/truncate.2.html) documentation for more details. + * @since v0.8.6 + * @param [len=0] + */ + function truncate(path: PathLike, len: number | undefined, callback: NoParamCallback): void; + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function truncate(path: PathLike, callback: NoParamCallback): void; + namespace truncate { + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(path: PathLike, len?: number): Promise; + } + /** + * Truncates the file. Returns `undefined`. A file descriptor can also be + * passed as the first argument. In this case, `fs.ftruncateSync()` is called. + * + * Passing a file descriptor is deprecated and may result in an error being thrown + * in the future. + * @since v0.8.6 + * @param [len=0] + */ + function truncateSync(path: PathLike, len?: number): void; + /** + * Truncates the file descriptor. No arguments other than a possible exception are + * given to the completion callback. + * + * See the POSIX [`ftruncate(2)`](http://man7.org/linux/man-pages/man2/ftruncate.2.html) documentation for more detail. + * + * If the file referred to by the file descriptor was larger than `len` bytes, only + * the first `len` bytes will be retained in the file. + * + * For example, the following program retains only the first four bytes of the + * file: + * + * ```js + * import { open, close, ftruncate } from 'node:fs'; + * + * function closeFd(fd) { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * + * open('temp.txt', 'r+', (err, fd) => { + * if (err) throw err; + * + * try { + * ftruncate(fd, 4, (err) => { + * closeFd(fd); + * if (err) throw err; + * }); + * } catch (err) { + * closeFd(fd); + * if (err) throw err; + * } + * }); + * ``` + * + * If the file previously was shorter than `len` bytes, it is extended, and the + * extended part is filled with null bytes (`'\0'`): + * + * If `len` is negative then `0` will be used. + * @since v0.8.6 + * @param [len=0] + */ + function ftruncate(fd: number, len: number | undefined, callback: NoParamCallback): void; + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + */ + function ftruncate(fd: number, callback: NoParamCallback): void; + namespace ftruncate { + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(fd: number, len?: number): Promise; + } + /** + * Truncates the file descriptor. Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link ftruncate}. + * @since v0.8.6 + * @param [len=0] + */ + function ftruncateSync(fd: number, len?: number): void; + /** + * Asynchronously changes owner and group of a file. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. + * @since v0.1.97 + */ + function chown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + namespace chown { + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + /** + * Synchronously changes owner and group of a file. Returns `undefined`. + * This is the synchronous version of {@link chown}. + * + * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. + * @since v0.1.97 + */ + function chownSync(path: PathLike, uid: number, gid: number): void; + /** + * Sets the owner of the file. No arguments other than a possible exception are + * given to the completion callback. + * + * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. + * @since v0.4.7 + */ + function fchown(fd: number, uid: number, gid: number, callback: NoParamCallback): void; + namespace fchown { + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function __promisify__(fd: number, uid: number, gid: number): Promise; + } + /** + * Sets the owner of the file. Returns `undefined`. + * + * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. + * @since v0.4.7 + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + */ + function fchownSync(fd: number, uid: number, gid: number): void; + /** + * Set the owner of the symbolic link. No arguments other than a possible + * exception are given to the completion callback. + * + * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more detail. + */ + function lchown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + namespace lchown { + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + /** + * Set the owner for the path. Returns `undefined`. + * + * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more details. + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + */ + function lchownSync(path: PathLike, uid: number, gid: number): void; + /** + * Changes the access and modification times of a file in the same way as {@link utimes}, with the difference that if the path refers to a symbolic + * link, then the link is not dereferenced: instead, the timestamps of the + * symbolic link itself are changed. + * + * No arguments other than a possible exception are given to the completion + * callback. + * @since v14.5.0, v12.19.0 + */ + function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + namespace lutimes { + /** + * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, + * with the difference that if the path refers to a symbolic link, then the link is not + * dereferenced: instead, the timestamps of the symbolic link itself are changed. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Change the file system timestamps of the symbolic link referenced by `path`. + * Returns `undefined`, or throws an exception when parameters are incorrect or + * the operation fails. This is the synchronous version of {@link lutimes}. + * @since v14.5.0, v12.19.0 + */ + function lutimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; + /** + * Asynchronously changes the permissions of a file. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. + * + * ```js + * import { chmod } from 'node:fs'; + * + * chmod('my_file.txt', 0o775, (err) => { + * if (err) throw err; + * console.log('The permissions for file "my_file.txt" have been changed!'); + * }); + * ``` + * @since v0.1.30 + */ + function chmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + namespace chmod { + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: Mode): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link chmod}. + * + * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. + * @since v0.6.7 + */ + function chmodSync(path: PathLike, mode: Mode): void; + /** + * Sets the permissions on the file. No arguments other than a possible exception + * are given to the completion callback. + * + * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. + * @since v0.4.7 + */ + function fchmod(fd: number, mode: Mode, callback: NoParamCallback): void; + namespace fchmod { + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(fd: number, mode: Mode): Promise; + } + /** + * Sets the permissions on the file. Returns `undefined`. + * + * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. + * @since v0.4.7 + */ + function fchmodSync(fd: number, mode: Mode): void; + /** + * Changes the permissions on a symbolic link. No arguments other than a possible + * exception are given to the completion callback. + * + * This method is only implemented on macOS. + * + * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. + * @deprecated Since v0.4.7 + */ + function lchmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + /** @deprecated */ + namespace lchmod { + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: Mode): Promise; + } + /** + * Changes the permissions on a symbolic link. Returns `undefined`. + * + * This method is only implemented on macOS. + * + * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. + * @deprecated Since v0.4.7 + */ + function lchmodSync(path: PathLike, mode: Mode): void; + /** + * Asynchronous [`stat(2)`](http://man7.org/linux/man-pages/man2/stat.2.html). The callback gets two arguments `(err, stats)` where`stats` is an `fs.Stats` object. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * + * {@link stat} follows symbolic links. Use {@link lstat} to look at the + * links themselves. + * + * Using `fs.stat()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. + * Instead, user code should open/read/write the file directly and handle the + * error raised if the file is not available. + * + * To check if a file exists without manipulating it afterwards, {@link access} is recommended. + * + * For example, given the following directory structure: + * + * ```text + * - txtDir + * -- file.txt + * - app.js + * ``` + * + * The next program will check for the stats of the given paths: + * + * ```js + * import { stat } from 'node:fs'; + * + * const pathsToCheck = ['./txtDir', './txtDir/file.txt']; + * + * for (let i = 0; i < pathsToCheck.length; i++) { + * stat(pathsToCheck[i], (err, stats) => { + * console.log(stats.isDirectory()); + * console.log(stats); + * }); + * } + * ``` + * + * The resulting output will resemble: + * + * ```console + * true + * Stats { + * dev: 16777220, + * mode: 16877, + * nlink: 3, + * uid: 501, + * gid: 20, + * rdev: 0, + * blksize: 4096, + * ino: 14214262, + * size: 96, + * blocks: 0, + * atimeMs: 1561174653071.963, + * mtimeMs: 1561174614583.3518, + * ctimeMs: 1561174626623.5366, + * birthtimeMs: 1561174126937.2893, + * atime: 2019-06-22T03:37:33.072Z, + * mtime: 2019-06-22T03:36:54.583Z, + * ctime: 2019-06-22T03:37:06.624Z, + * birthtime: 2019-06-22T03:28:46.937Z + * } + * false + * Stats { + * dev: 16777220, + * mode: 33188, + * nlink: 1, + * uid: 501, + * gid: 20, + * rdev: 0, + * blksize: 4096, + * ino: 14214074, + * size: 8, + * blocks: 8, + * atimeMs: 1561174616618.8555, + * mtimeMs: 1561174614584, + * ctimeMs: 1561174614583.8145, + * birthtimeMs: 1561174007710.7478, + * atime: 2019-06-22T03:36:56.619Z, + * mtime: 2019-06-22T03:36:54.584Z, + * ctime: 2019-06-22T03:36:54.584Z, + * birthtime: 2019-06-22T03:26:47.711Z + * } + * ``` + * @since v0.0.2 + */ + function stat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + function stat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, + ): void; + function stat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, + ): void; + function stat( + path: PathLike, + options: StatOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, + ): void; + namespace stat { + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__( + path: PathLike, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(path: PathLike, options?: StatOptions): Promise; + } + interface StatSyncFn extends Function { + (path: PathLike, options?: undefined): Stats; + ( + path: PathLike, + options?: StatSyncOptions & { + bigint?: false | undefined; + throwIfNoEntry: false; + }, + ): Stats | undefined; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: true; + throwIfNoEntry: false; + }, + ): BigIntStats | undefined; + ( + path: PathLike, + options?: StatSyncOptions & { + bigint?: false | undefined; + }, + ): Stats; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: true; + }, + ): BigIntStats; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: boolean; + throwIfNoEntry?: false | undefined; + }, + ): Stats | BigIntStats; + (path: PathLike, options?: StatSyncOptions): Stats | BigIntStats | undefined; + } + /** + * Synchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + const statSync: StatSyncFn; + /** + * Invokes the callback with the `fs.Stats` for the file descriptor. + * + * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail. + * @since v0.1.95 + */ + function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + function fstat( + fd: number, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, + ): void; + function fstat( + fd: number, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, + ): void; + function fstat( + fd: number, + options: StatOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, + ): void; + namespace fstat { + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function __promisify__( + fd: number, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + fd: number, + options: StatOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(fd: number, options?: StatOptions): Promise; + } + /** + * Retrieves the `fs.Stats` for the file descriptor. + * + * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail. + * @since v0.1.95 + */ + function fstatSync( + fd: number, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Stats; + function fstatSync( + fd: number, + options: StatOptions & { + bigint: true; + }, + ): BigIntStats; + function fstatSync(fd: number, options?: StatOptions): Stats | BigIntStats; + /** + * Retrieves the `fs.Stats` for the symbolic link referred to by the path. + * The callback gets two arguments `(err, stats)` where `stats` is a `fs.Stats` object. `lstat()` is identical to `stat()`, except that if `path` is a symbolic + * link, then the link itself is stat-ed, not the file that it refers to. + * + * See the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) documentation for more details. + * @since v0.1.30 + */ + function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + function lstat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, + ): void; + function lstat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, + ): void; + function lstat( + path: PathLike, + options: StatOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, + ): void; + namespace lstat { + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__( + path: PathLike, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(path: PathLike, options?: StatOptions): Promise; + } + /** + * Asynchronous [`statfs(2)`](http://man7.org/linux/man-pages/man2/statfs.2.html). Returns information about the mounted file system which + * contains `path`. The callback gets two arguments `(err, stats)` where `stats`is an `fs.StatFs` object. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * @since v19.6.0, v18.15.0 + * @param path A path to an existing file or directory on the file system to be queried. + */ + function statfs(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: StatsFs) => void): void; + function statfs( + path: PathLike, + options: + | (StatFsOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: StatsFs) => void, + ): void; + function statfs( + path: PathLike, + options: StatFsOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStatsFs) => void, + ): void; + function statfs( + path: PathLike, + options: StatFsOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: StatsFs | BigIntStatsFs) => void, + ): void; + namespace statfs { + /** + * Asynchronous statfs(2) - Returns information about the mounted file system which contains path. The callback gets two arguments (err, stats) where stats is an object. + * @param path A path to an existing file or directory on the file system to be queried. + */ + function __promisify__( + path: PathLike, + options?: StatFsOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + path: PathLike, + options: StatFsOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(path: PathLike, options?: StatFsOptions): Promise; + } + /** + * Synchronous [`statfs(2)`](http://man7.org/linux/man-pages/man2/statfs.2.html). Returns information about the mounted file system which + * contains `path`. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * @since v19.6.0, v18.15.0 + * @param path A path to an existing file or directory on the file system to be queried. + */ + function statfsSync( + path: PathLike, + options?: StatFsOptions & { + bigint?: false | undefined; + }, + ): StatsFs; + function statfsSync( + path: PathLike, + options: StatFsOptions & { + bigint: true; + }, + ): BigIntStatsFs; + function statfsSync(path: PathLike, options?: StatFsOptions): StatsFs | BigIntStatsFs; + /** + * Synchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + const lstatSync: StatSyncFn; + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. No arguments other than + * a possible + * exception are given to the completion callback. + * @since v0.1.31 + */ + function link(existingPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + namespace link { + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(existingPath: PathLike, newPath: PathLike): Promise; + } + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. Returns `undefined`. + * @since v0.1.31 + */ + function linkSync(existingPath: PathLike, newPath: PathLike): void; + /** + * Creates the link called `path` pointing to `target`. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`symlink(2)`](http://man7.org/linux/man-pages/man2/symlink.2.html) documentation for more details. + * + * The `type` argument is only available on Windows and ignored on other platforms. + * It can be set to `'dir'`, `'file'`, or `'junction'`. If the `type` argument is + * not a string, Node.js will autodetect `target` type and use `'file'` or `'dir'`. + * If the `target` does not exist, `'file'` will be used. Windows junction points + * require the destination path to be absolute. When using `'junction'`, the`target` argument will automatically be normalized to absolute path. Junction + * points on NTFS volumes can only point to directories. + * + * Relative targets are relative to the link's parent directory. + * + * ```js + * import { symlink } from 'node:fs'; + * + * symlink('./mew', './mewtwo', callback); + * ``` + * + * The above example creates a symbolic link `mewtwo` which points to `mew` in the + * same directory: + * + * ```bash + * $ tree . + * . + * ├── mew + * └── mewtwo -> ./mew + * ``` + * @since v0.1.31 + * @param [type='null'] + */ + function symlink( + target: PathLike, + path: PathLike, + type: symlink.Type | undefined | null, + callback: NoParamCallback, + ): void; + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + */ + function symlink(target: PathLike, path: PathLike, callback: NoParamCallback): void; + namespace symlink { + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise; + type Type = "dir" | "file" | "junction"; + } + /** + * Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link symlink}. + * @since v0.1.31 + * @param [type='null'] + */ + function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void; + /** + * Reads the contents of the symbolic link referred to by `path`. The callback gets + * two arguments `(err, linkString)`. + * + * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path passed to the callback. If the `encoding` is set to `'buffer'`, + * the link path returned will be passed as a `Buffer` object. + * @since v0.1.31 + */ + function readlink( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, linkString: string) => void, + ): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink( + path: PathLike, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, linkString: NonSharedBuffer) => void, + ): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, linkString: string | NonSharedBuffer) => void, + ): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function readlink( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, linkString: string) => void, + ): void; + namespace readlink { + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + } + /** + * Returns the symbolic link's string value. + * + * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path returned. If the `encoding` is set to `'buffer'`, + * the link path returned will be passed as a `Buffer` object. + * @since v0.1.31 + */ + function readlinkSync(path: PathLike, options?: EncodingOption): string; + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlinkSync(path: PathLike, options: BufferEncodingOption): NonSharedBuffer; + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlinkSync(path: PathLike, options?: EncodingOption): string | NonSharedBuffer; + /** + * Asynchronously computes the canonical pathname by resolving `.`, `..`, and + * symbolic links. + * + * A canonical pathname is not necessarily unique. Hard links and bind mounts can + * expose a file system entity through many pathnames. + * + * This function behaves like [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html), with some exceptions: + * + * 1. No case conversion is performed on case-insensitive file systems. + * 2. The maximum number of symbolic links is platform-independent and generally + * (much) higher than what the native [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html) implementation supports. + * + * The `callback` gets two arguments `(err, resolvedPath)`. May use `process.cwd` to resolve relative paths. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path passed to the callback. If the `encoding` is set to `'buffer'`, + * the path returned will be passed as a `Buffer` object. + * + * If `path` resolves to a socket or a pipe, the function will return a system + * dependent name for that object. + * @since v0.1.31 + */ + function realpath( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath( + path: PathLike, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: NonSharedBuffer) => void, + ): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | NonSharedBuffer) => void, + ): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function realpath( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + namespace realpath { + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html). + * + * The `callback` gets two arguments `(err, resolvedPath)`. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path passed to the callback. If the `encoding` is set to `'buffer'`, + * the path returned will be passed as a `Buffer` object. + * + * On Linux, when Node.js is linked against musl libc, the procfs file system must + * be mounted on `/proc` in order for this function to work. Glibc does not have + * this restriction. + * @since v9.2.0 + */ + function native( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + function native( + path: PathLike, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: NonSharedBuffer) => void, + ): void; + function native( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | NonSharedBuffer) => void, + ): void; + function native( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + } + /** + * Returns the resolved pathname. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link realpath}. + * @since v0.1.31 + */ + function realpathSync(path: PathLike, options?: EncodingOption): string; + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpathSync(path: PathLike, options: BufferEncodingOption): NonSharedBuffer; + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpathSync(path: PathLike, options?: EncodingOption): string | NonSharedBuffer; + namespace realpathSync { + function native(path: PathLike, options?: EncodingOption): string; + function native(path: PathLike, options: BufferEncodingOption): NonSharedBuffer; + function native(path: PathLike, options?: EncodingOption): string | NonSharedBuffer; + } + /** + * Asynchronously removes a file or symbolic link. No arguments other than a + * possible exception are given to the completion callback. + * + * ```js + * import { unlink } from 'node:fs'; + * // Assuming that 'path/file.txt' is a regular file. + * unlink('path/file.txt', (err) => { + * if (err) throw err; + * console.log('path/file.txt was deleted'); + * }); + * ``` + * + * `fs.unlink()` will not work on a directory, empty or otherwise. To remove a + * directory, use {@link rmdir}. + * + * See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more details. + * @since v0.0.2 + */ + function unlink(path: PathLike, callback: NoParamCallback): void; + namespace unlink { + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise; + } + /** + * Synchronous [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html). Returns `undefined`. + * @since v0.1.21 + */ + function unlinkSync(path: PathLike): void; + /** @deprecated `rmdir()` no longer provides any options. This interface will be removed in a future version. */ + // TODO: remove in future major + interface RmDirOptions {} + /** + * Asynchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). No arguments other than a possible exception are given + * to the completion callback. + * + * Using `fs.rmdir()` on a file (not a directory) results in an `ENOENT` error on + * Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use {@link rm} with options `{ recursive: true, force: true }`. + * @since v0.0.2 + */ + function rmdir(path: PathLike, callback: NoParamCallback): void; + namespace rmdir { + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise; + } + /** + * Synchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). Returns `undefined`. + * + * Using `fs.rmdirSync()` on a file (not a directory) results in an `ENOENT` error + * on Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use {@link rmSync} with options `{ recursive: true, force: true }`. + * @since v0.1.21 + */ + function rmdirSync(path: PathLike): void; + interface RmOptions { + /** + * When `true`, exceptions will be ignored if `path` does not exist. + * @default false + */ + force?: boolean | undefined; + /** + * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or + * `EPERM` error is encountered, Node.js will retry the operation with a linear + * backoff wait of `retryDelay` ms longer on each try. This option represents the + * number of retries. This option is ignored if the `recursive` option is not + * `true`. + * @default 0 + */ + maxRetries?: number | undefined; + /** + * If `true`, perform a recursive directory removal. In + * recursive mode, operations are retried on failure. + * @default false + */ + recursive?: boolean | undefined; + /** + * The amount of time in milliseconds to wait between retries. + * This option is ignored if the `recursive` option is not `true`. + * @default 100 + */ + retryDelay?: number | undefined; + } + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). No arguments other than a possible exception are given to the + * completion callback. + * @since v14.14.0 + */ + function rm(path: PathLike, callback: NoParamCallback): void; + function rm(path: PathLike, options: RmOptions, callback: NoParamCallback): void; + namespace rm { + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). + */ + function __promisify__(path: PathLike, options?: RmOptions): Promise; + } + /** + * Synchronously removes files and directories (modeled on the standard POSIX `rm` utility). Returns `undefined`. + * @since v14.14.0 + */ + function rmSync(path: PathLike, options?: RmOptions): void; + interface MakeDirectoryOptions { + /** + * Indicates whether parent folders should be created. + * If a folder was created, the path to the first created folder will be returned. + * @default false + */ + recursive?: boolean | undefined; + /** + * A file mode. If a string is passed, it is parsed as an octal integer. If not specified + * @default 0o777 + */ + mode?: Mode | undefined; + } + /** + * Asynchronously creates a directory. + * + * The callback is given a possible exception and, if `recursive` is `true`, the + * first directory path created, `(err[, path])`.`path` can still be `undefined` when `recursive` is `true`, if no directory was + * created (for instance, if it was previously created). + * + * The optional `options` argument can be an integer specifying `mode` (permission + * and sticky bits), or an object with a `mode` property and a `recursive` property indicating whether parent directories should be created. Calling `fs.mkdir()` when `path` is a directory that + * exists results in an error only + * when `recursive` is false. If `recursive` is false and the directory exists, + * an `EEXIST` error occurs. + * + * ```js + * import { mkdir } from 'node:fs'; + * + * // Create ./tmp/a/apple, regardless of whether ./tmp and ./tmp/a exist. + * mkdir('./tmp/a/apple', { recursive: true }, (err) => { + * if (err) throw err; + * }); + * ``` + * + * On Windows, using `fs.mkdir()` on the root directory even with recursion will + * result in an error: + * + * ```js + * import { mkdir } from 'node:fs'; + * + * mkdir('/', { recursive: true }, (err) => { + * // => [Error: EPERM: operation not permitted, mkdir 'C:\'] + * }); + * ``` + * + * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. + * @since v0.1.8 + */ + function mkdir( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + callback: (err: NodeJS.ErrnoException | null, path?: string) => void, + ): void; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir( + path: PathLike, + options: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null + | undefined, + callback: NoParamCallback, + ): void; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir( + path: PathLike, + options: Mode | MakeDirectoryOptions | null | undefined, + callback: (err: NodeJS.ErrnoException | null, path?: string) => void, + ): void; + /** + * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function mkdir(path: PathLike, callback: NoParamCallback): void; + namespace mkdir { + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options?: Mode | MakeDirectoryOptions | null, + ): Promise; + } + /** + * Synchronously creates a directory. Returns `undefined`, or if `recursive` is `true`, the first directory path created. + * This is the synchronous version of {@link mkdir}. + * + * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. + * @since v0.1.21 + */ + function mkdirSync( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + ): string | undefined; + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdirSync( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null, + ): void; + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdirSync(path: PathLike, options?: Mode | MakeDirectoryOptions | null): string | undefined; + /** + * Creates a unique temporary directory. + * + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. Due to platform + * inconsistencies, avoid trailing `X` characters in `prefix`. Some platforms, + * notably the BSDs, can return more than six random characters, and replace + * trailing `X` characters in `prefix` with random characters. + * + * The created directory path is passed as a string to the callback's second + * parameter. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * + * ```js + * import { mkdtemp } from 'node:fs'; + * import { join } from 'node:path'; + * import { tmpdir } from 'node:os'; + * + * mkdtemp(join(tmpdir(), 'foo-'), (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2 + * }); + * ``` + * + * The `fs.mkdtemp()` method will append the six randomly selected characters + * directly to the `prefix` string. For instance, given a directory `/tmp`, if the + * intention is to create a temporary directory _within_`/tmp`, the `prefix`must end with a trailing platform-specific path separator + * (`import { sep } from 'node:path'`). + * + * ```js + * import { tmpdir } from 'node:os'; + * import { mkdtemp } from 'node:fs'; + * + * // The parent directory for the new temporary directory + * const tmpDir = tmpdir(); + * + * // This method is *INCORRECT*: + * mkdtemp(tmpDir, (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Will print something similar to `/tmpabc123`. + * // A new temporary directory is created at the file system root + * // rather than *within* the /tmp directory. + * }); + * + * // This method is *CORRECT*: + * import { sep } from 'node:path'; + * mkdtemp(`${tmpDir}${sep}`, (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Will print something similar to `/tmp/abc123`. + * // A new temporary directory is created within + * // the /tmp directory. + * }); + * ``` + * @since v5.10.0 + */ + function mkdtemp( + prefix: string, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, folder: string) => void, + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp( + prefix: string, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, folder: NonSharedBuffer) => void, + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp( + prefix: string, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, folder: string | NonSharedBuffer) => void, + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + */ + function mkdtemp( + prefix: string, + callback: (err: NodeJS.ErrnoException | null, folder: string) => void, + ): void; + namespace mkdtemp { + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: EncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options: BufferEncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: EncodingOption): Promise; + } + /** + * Returns the created directory path. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link mkdtemp}. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * @since v5.10.0 + */ + function mkdtempSync(prefix: string, options?: EncodingOption): string; + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtempSync(prefix: string, options: BufferEncodingOption): NonSharedBuffer; + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtempSync(prefix: string, options?: EncodingOption): string | NonSharedBuffer; + interface DisposableTempDir extends AsyncDisposable { + /** + * The path of the created directory. + */ + path: string; + /** + * A function which removes the created directory. + */ + remove(): Promise; + /** + * The same as `remove`. + */ + [Symbol.asyncDispose](): Promise; + } + /** + * Returns a disposable object whose `path` property holds the created directory + * path. When the object is disposed, the directory and its contents will be + * removed if it still exists. If the directory cannot be deleted, disposal will + * throw an error. The object has a `remove()` method which will perform the same + * task. + * + * + * + * For detailed information, see the documentation of `fs.mkdtemp()`. + * + * There is no callback-based version of this API because it is designed for use + * with the `using` syntax. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * @since v24.4.0 + */ + function mkdtempDisposableSync(prefix: string, options?: EncodingOption): DisposableTempDir; + /** + * Reads the contents of a directory. The callback gets two arguments `(err, files)` where `files` is an array of the names of the files in the directory excluding `'.'` and `'..'`. + * + * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames passed to the callback. If the `encoding` is set to `'buffer'`, + * the filenames returned will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the `files` array will contain `fs.Dirent` objects. + * @since v0.1.8 + */ + function readdir( + path: PathLike, + options: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + callback: (err: NodeJS.ErrnoException | null, files: NonSharedBuffer[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, files: string[] | NonSharedBuffer[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function readdir( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdir( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Must include `withFileTypes: true` and `encoding: 'buffer'`. + */ + function readdir( + path: PathLike, + options: { + encoding: "buffer"; + withFileTypes: true; + recursive?: boolean | undefined; + }, + callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void, + ): void; + namespace readdir { + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options?: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options: + | "buffer" + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent + */ + function __promisify__( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Must include `withFileTypes: true` and `encoding: 'buffer'`. + */ + function __promisify__( + path: PathLike, + options: { + encoding: "buffer"; + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise[]>; + } + /** + * Reads the contents of the directory. + * + * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames returned. If the `encoding` is set to `'buffer'`, + * the filenames returned will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the result will contain `fs.Dirent` objects. + * @since v0.1.21 + */ + function readdirSync( + path: PathLike, + options?: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | BufferEncoding + | null, + ): string[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdirSync( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + ): NonSharedBuffer[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdirSync( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): string[] | NonSharedBuffer[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdirSync( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Dirent[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Must include `withFileTypes: true` and `encoding: 'buffer'`. + */ + function readdirSync( + path: PathLike, + options: { + encoding: "buffer"; + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Dirent[]; + /** + * Closes the file descriptor. No arguments other than a possible exception are + * given to the completion callback. + * + * Calling `fs.close()` on any file descriptor (`fd`) that is currently in use + * through any other `fs` operation may lead to undefined behavior. + * + * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. + * @since v0.0.2 + */ + function close(fd: number, callback?: NoParamCallback): void; + namespace close { + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Closes the file descriptor. Returns `undefined`. + * + * Calling `fs.closeSync()` on any file descriptor (`fd`) that is currently in use + * through any other `fs` operation may lead to undefined behavior. + * + * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. + * @since v0.1.21 + */ + function closeSync(fd: number): void; + /** + * Asynchronous file open. See the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more details. + * + * `mode` sets the file mode (permission and sticky bits), but only if the file was + * created. On Windows, only the write permission can be manipulated; see {@link chmod}. + * + * The callback gets two arguments `(err, fd)`. + * + * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented + * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains + * a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). + * + * Functions based on `fs.open()` exhibit this behavior as well:`fs.writeFile()`, `fs.readFile()`, etc. + * @since v0.0.2 + * @param [flags='r'] See `support of file system `flags``. + * @param [mode=0o666] + */ + function open( + path: PathLike, + flags: OpenMode | undefined, + mode: Mode | undefined | null, + callback: (err: NodeJS.ErrnoException | null, fd: number) => void, + ): void; + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param [flags='r'] See `support of file system `flags``. + */ + function open( + path: PathLike, + flags: OpenMode | undefined, + callback: (err: NodeJS.ErrnoException | null, fd: number) => void, + ): void; + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function open(path: PathLike, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + namespace open { + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function __promisify__(path: PathLike, flags: OpenMode, mode?: Mode | null): Promise; + } + /** + * Returns an integer representing the file descriptor. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link open}. + * @since v0.1.21 + * @param [flags='r'] + * @param [mode=0o666] + */ + function openSync(path: PathLike, flags: OpenMode, mode?: Mode | null): number; + /** + * Change the file system timestamps of the object referenced by `path`. + * + * The `atime` and `mtime` arguments follow these rules: + * + * * Values can be either numbers representing Unix epoch time in seconds, `Date`s, or a numeric string like `'123456789.0'`. + * * If the value can not be converted to a number, or is `NaN`, `Infinity`, or `-Infinity`, an `Error` will be thrown. + * @since v0.4.2 + */ + function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + namespace utimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link utimes}. + * @since v0.4.2 + */ + function utimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; + /** + * Change the file system timestamps of the object referenced by the supplied file + * descriptor. See {@link utimes}. + * @since v0.4.2 + */ + function futimes(fd: number, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + namespace futimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(fd: number, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Synchronous version of {@link futimes}. Returns `undefined`. + * @since v0.4.2 + */ + function futimesSync(fd: number, atime: TimeLike, mtime: TimeLike): void; + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. No arguments other + * than a possible exception are given to the completion callback. + * @since v0.1.96 + */ + function fsync(fd: number, callback: NoParamCallback): void; + namespace fsync { + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. Returns `undefined`. + * @since v0.1.96 + */ + function fsyncSync(fd: number): void; + interface WriteOptions { + /** + * @default 0 + */ + offset?: number | undefined; + /** + * @default `buffer.byteLength - offset` + */ + length?: number | undefined; + /** + * @default null + */ + position?: number | null | undefined; + } + /** + * Write `buffer` to the file specified by `fd`. + * + * `offset` determines the part of the buffer to be written, and `length` is + * an integer specifying the number of bytes to write. + * + * `position` refers to the offset from the beginning of the file where this data + * should be written. If `typeof position !== 'number'`, the data will be written + * at the current position. See [`pwrite(2)`](http://man7.org/linux/man-pages/man2/pwrite.2.html). + * + * The callback will be given three arguments `(err, bytesWritten, buffer)` where `bytesWritten` specifies how many _bytes_ were written from `buffer`. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesWritten` and `buffer` properties. + * + * It is unsafe to use `fs.write()` multiple times on the same file without waiting + * for the callback. For this scenario, {@link createWriteStream} is + * recommended. + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v0.0.2 + * @param [offset=0] + * @param [length=buffer.byteLength - offset] + * @param [position='null'] + */ + function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + position: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + */ + function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + */ + function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + */ + function write( + fd: number, + buffer: TBuffer, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param options An object with the following properties: + * * `offset` The part of the buffer to be written. If not supplied, defaults to `0`. + * * `length` The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * * `position` The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function write( + fd: number, + buffer: TBuffer, + options: WriteOptions, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function write( + fd: number, + string: string, + position: number | undefined | null, + encoding: BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function write( + fd: number, + string: string, + position: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + */ + function write( + fd: number, + string: string, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + namespace write { + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function __promisify__( + fd: number, + buffer?: TBuffer, + offset?: number, + length?: number, + position?: number | null, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param options An object with the following properties: + * * `offset` The part of the buffer to be written. If not supplied, defaults to `0`. + * * `length` The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * * `position` The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function __promisify__( + fd: number, + buffer?: TBuffer, + options?: WriteOptions, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function __promisify__( + fd: number, + string: string, + position?: number | null, + encoding?: BufferEncoding | null, + ): Promise<{ + bytesWritten: number; + buffer: string; + }>; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link write}. + * @since v0.1.21 + * @param [offset=0] + * @param [length=buffer.byteLength - offset] + * @param [position='null'] + * @return The number of bytes written. + */ + function writeSync( + fd: number, + buffer: NodeJS.ArrayBufferView, + offset?: number | null, + length?: number | null, + position?: number | null, + ): number; + /** + * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function writeSync( + fd: number, + string: string, + position?: number | null, + encoding?: BufferEncoding | null, + ): number; + type ReadPosition = number | bigint; + interface ReadOptions { + /** + * @default 0 + */ + offset?: number | undefined; + /** + * @default `length of buffer` + */ + length?: number | undefined; + /** + * @default null + */ + position?: ReadPosition | null | undefined; + } + interface ReadOptionsWithBuffer extends ReadOptions { + buffer?: T | undefined; + } + /** @deprecated Use `ReadOptions` instead. */ + // TODO: remove in future major + interface ReadSyncOptions extends ReadOptions {} + /** @deprecated Use `ReadOptionsWithBuffer` instead. */ + // TODO: remove in future major + interface ReadAsyncOptions extends ReadOptionsWithBuffer {} + /** + * Read data from the file specified by `fd`. + * + * The callback is given the three arguments, `(err, bytesRead, buffer)`. + * + * If the file is not modified concurrently, the end-of-file is reached when the + * number of bytes read is zero. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesRead` and `buffer` properties. + * @since v0.0.2 + * @param buffer The buffer that the data will be written to. + * @param offset The position in `buffer` to write the data to. + * @param length The number of bytes to read. + * @param position Specifies where to begin reading from in the file. If `position` is `null` or `-1 `, data will be read from the current file position, and the file position will be updated. If + * `position` is an integer, the file position will be unchanged. + */ + function read( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: ReadPosition | null, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + /** + * Similar to the above `fs.read` function, this version takes an optional `options` object. + * If not otherwise specified in an `options` object, + * `buffer` defaults to `Buffer.alloc(16384)`, + * `offset` defaults to `0`, + * `length` defaults to `buffer.byteLength`, `- offset` as of Node 17.6.0 + * `position` defaults to `null` + * @since v12.17.0, 13.11.0 + */ + function read( + fd: number, + options: ReadOptionsWithBuffer, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + function read( + fd: number, + buffer: TBuffer, + options: ReadOptions, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + function read( + fd: number, + buffer: TBuffer, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + function read( + fd: number, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: NonSharedBuffer) => void, + ): void; + namespace read { + /** + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function __promisify__( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: ReadPosition | null, + ): Promise<{ + bytesRead: number; + buffer: TBuffer; + }>; + function __promisify__( + fd: number, + options: ReadOptionsWithBuffer, + ): Promise<{ + bytesRead: number; + buffer: TBuffer; + }>; + function __promisify__(fd: number): Promise<{ + bytesRead: number; + buffer: NonSharedBuffer; + }>; + } + /** + * Returns the number of `bytesRead`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link read}. + * @since v0.1.21 + * @param [position='null'] + */ + function readSync( + fd: number, + buffer: NodeJS.ArrayBufferView, + offset: number, + length: number, + position: ReadPosition | null, + ): number; + /** + * Similar to the above `fs.readSync` function, this version takes an optional `options` object. + * If no `options` object is specified, it will default with the above values. + */ + function readSync(fd: number, buffer: NodeJS.ArrayBufferView, opts?: ReadOptions): number; + /** + * Asynchronously reads the entire contents of a file. + * + * ```js + * import { readFile } from 'node:fs'; + * + * readFile('/etc/passwd', (err, data) => { + * if (err) throw err; + * console.log(data); + * }); + * ``` + * + * The callback is passed two arguments `(err, data)`, where `data` is the + * contents of the file. + * + * If no encoding is specified, then the raw buffer is returned. + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { readFile } from 'node:fs'; + * + * readFile('/etc/passwd', 'utf8', callback); + * ``` + * + * When the path is a directory, the behavior of `fs.readFile()` and {@link readFileSync} is platform-specific. On macOS, Linux, and Windows, an + * error will be returned. On FreeBSD, a representation of the directory's contents + * will be returned. + * + * ```js + * import { readFile } from 'node:fs'; + * + * // macOS, Linux, and Windows + * readFile('', (err, data) => { + * // => [Error: EISDIR: illegal operation on a directory, read ] + * }); + * + * // FreeBSD + * readFile('', (err, data) => { + * // => null, + * }); + * ``` + * + * It is possible to abort an ongoing request using an `AbortSignal`. If a + * request is aborted the callback is called with an `AbortError`: + * + * ```js + * import { readFile } from 'node:fs'; + * + * const controller = new AbortController(); + * const signal = controller.signal; + * readFile(fileInfo[0].name, { signal }, (err, buf) => { + * // ... + * }); + * // When you want to abort the request + * controller.abort(); + * ``` + * + * The `fs.readFile()` function buffers the entire file. To minimize memory costs, + * when possible prefer streaming via `fs.createReadStream()`. + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.readFile` performs. + * @since v0.1.29 + * @param path filename or file descriptor + */ + function readFile( + path: PathOrFileDescriptor, + options: + | ({ + encoding?: null | undefined; + flag?: string | undefined; + } & Abortable) + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, data: NonSharedBuffer) => void, + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathOrFileDescriptor, + options: + | ({ + encoding: BufferEncoding; + flag?: string | undefined; + } & Abortable) + | BufferEncoding, + callback: (err: NodeJS.ErrnoException | null, data: string) => void, + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathOrFileDescriptor, + options: + | (ObjectEncodingOptions & { + flag?: string | undefined; + } & Abortable) + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, data: string | NonSharedBuffer) => void, + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + */ + function readFile( + path: PathOrFileDescriptor, + callback: (err: NodeJS.ErrnoException | null, data: NonSharedBuffer) => void, + ): void; + namespace readFile { + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options?: { + encoding?: null | undefined; + flag?: string | undefined; + } | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options: + | { + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options?: + | (ObjectEncodingOptions & { + flag?: string | undefined; + }) + | BufferEncoding + | null, + ): Promise; + } + /** + * Returns the contents of the `path`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link readFile}. + * + * If the `encoding` option is specified then this function returns a + * string. Otherwise it returns a buffer. + * + * Similar to {@link readFile}, when the path is a directory, the behavior of `fs.readFileSync()` is platform-specific. + * + * ```js + * import { readFileSync } from 'node:fs'; + * + * // macOS, Linux, and Windows + * readFileSync(''); + * // => [Error: EISDIR: illegal operation on a directory, read ] + * + * // FreeBSD + * readFileSync(''); // => + * ``` + * @since v0.1.8 + * @param path filename or file descriptor + */ + function readFileSync( + path: PathOrFileDescriptor, + options?: { + encoding?: null | undefined; + flag?: string | undefined; + } | null, + ): NonSharedBuffer; + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFileSync( + path: PathOrFileDescriptor, + options: + | { + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding, + ): string; + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFileSync( + path: PathOrFileDescriptor, + options?: + | (ObjectEncodingOptions & { + flag?: string | undefined; + }) + | BufferEncoding + | null, + ): string | NonSharedBuffer; + type WriteFileOptions = + | ( + & ObjectEncodingOptions + & Abortable + & { + mode?: Mode | undefined; + flag?: string | undefined; + flush?: boolean | undefined; + } + ) + | BufferEncoding + | null; + /** + * When `file` is a filename, asynchronously writes data to the file, replacing the + * file if it already exists. `data` can be a string or a buffer. + * + * When `file` is a file descriptor, the behavior is similar to calling `fs.write()` directly (which is recommended). See the notes below on using + * a file descriptor. + * + * The `encoding` option is ignored if `data` is a buffer. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { writeFile } from 'node:fs'; + * import { Buffer } from 'node:buffer'; + * + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * writeFile('message.txt', data, (err) => { + * if (err) throw err; + * console.log('The file has been saved!'); + * }); + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { writeFile } from 'node:fs'; + * + * writeFile('message.txt', 'Hello Node.js', 'utf8', callback); + * ``` + * + * It is unsafe to use `fs.writeFile()` multiple times on the same file without + * waiting for the callback. For this scenario, {@link createWriteStream} is + * recommended. + * + * Similarly to `fs.readFile` \- `fs.writeFile` is a convenience method that + * performs multiple `write` calls internally to write the buffer passed to it. + * For performance sensitive code consider using {@link createWriteStream}. + * + * It is possible to use an `AbortSignal` to cancel an `fs.writeFile()`. + * Cancelation is "best effort", and some amount of data is likely still + * to be written. + * + * ```js + * import { writeFile } from 'node:fs'; + * import { Buffer } from 'node:buffer'; + * + * const controller = new AbortController(); + * const { signal } = controller; + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * writeFile('message.txt', data, { signal }, (err) => { + * // When a request is aborted - the callback is called with an AbortError + * }); + * // When the request should be aborted + * controller.abort(); + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.writeFile` performs. + * @since v0.1.29 + * @param file filename or file descriptor + */ + function writeFile( + file: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + options: WriteFileOptions, + callback: NoParamCallback, + ): void; + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + function writeFile( + path: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + callback: NoParamCallback, + ): void; + namespace writeFile { + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function __promisify__( + path: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + options?: WriteFileOptions, + ): Promise; + } + /** + * Returns `undefined`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link writeFile}. + * @since v0.1.29 + * @param file filename or file descriptor + */ + function writeFileSync( + file: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + options?: WriteFileOptions, + ): void; + /** + * Asynchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { appendFile } from 'node:fs'; + * + * appendFile('message.txt', 'data to append', (err) => { + * if (err) throw err; + * console.log('The "data to append" was appended to file!'); + * }); + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { appendFile } from 'node:fs'; + * + * appendFile('message.txt', 'data to append', 'utf8', callback); + * ``` + * + * The `path` may be specified as a numeric file descriptor that has been opened + * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will + * not be closed automatically. + * + * ```js + * import { open, close, appendFile } from 'node:fs'; + * + * function closeFd(fd) { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * + * open('message.txt', 'a', (err, fd) => { + * if (err) throw err; + * + * try { + * appendFile(fd, 'data to append', 'utf8', (err) => { + * closeFd(fd); + * if (err) throw err; + * }); + * } catch (err) { + * closeFd(fd); + * throw err; + * } + * }); + * ``` + * @since v0.6.7 + * @param path filename or file descriptor + */ + function appendFile( + path: PathOrFileDescriptor, + data: string | Uint8Array, + options: WriteFileOptions, + callback: NoParamCallback, + ): void; + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + function appendFile(file: PathOrFileDescriptor, data: string | Uint8Array, callback: NoParamCallback): void; + namespace appendFile { + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function __promisify__( + file: PathOrFileDescriptor, + data: string | Uint8Array, + options?: WriteFileOptions, + ): Promise; + } + /** + * Synchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { appendFileSync } from 'node:fs'; + * + * try { + * appendFileSync('message.txt', 'data to append'); + * console.log('The "data to append" was appended to file!'); + * } catch (err) { + * // Handle the error + * } + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { appendFileSync } from 'node:fs'; + * + * appendFileSync('message.txt', 'data to append', 'utf8'); + * ``` + * + * The `path` may be specified as a numeric file descriptor that has been opened + * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will + * not be closed automatically. + * + * ```js + * import { openSync, closeSync, appendFileSync } from 'node:fs'; + * + * let fd; + * + * try { + * fd = openSync('message.txt', 'a'); + * appendFileSync(fd, 'data to append', 'utf8'); + * } catch (err) { + * // Handle the error + * } finally { + * if (fd !== undefined) + * closeSync(fd); + * } + * ``` + * @since v0.6.7 + * @param path filename or file descriptor + */ + function appendFileSync( + path: PathOrFileDescriptor, + data: string | Uint8Array, + options?: WriteFileOptions, + ): void; + /** + * Watch for changes on `filename`. The callback `listener` will be called each + * time the file is accessed. + * + * The `options` argument may be omitted. If provided, it should be an object. The `options` object may contain a boolean named `persistent` that indicates + * whether the process should continue to run as long as files are being watched. + * The `options` object may specify an `interval` property indicating how often the + * target should be polled in milliseconds. + * + * The `listener` gets two arguments the current stat object and the previous + * stat object: + * + * ```js + * import { watchFile } from 'node:fs'; + * + * watchFile('message.text', (curr, prev) => { + * console.log(`the current mtime is: ${curr.mtime}`); + * console.log(`the previous mtime was: ${prev.mtime}`); + * }); + * ``` + * + * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, + * the numeric values in these objects are specified as `BigInt`s. + * + * To be notified when the file was modified, not just accessed, it is necessary + * to compare `curr.mtimeMs` and `prev.mtimeMs`. + * + * When an `fs.watchFile` operation results in an `ENOENT` error, it + * will invoke the listener once, with all the fields zeroed (or, for dates, the + * Unix Epoch). If the file is created later on, the listener will be called + * again, with the latest stat objects. This is a change in functionality since + * v0.10. + * + * Using {@link watch} is more efficient than `fs.watchFile` and `fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` when possible. + * + * When a file being watched by `fs.watchFile()` disappears and reappears, + * then the contents of `previous` in the second callback event (the file's + * reappearance) will be the same as the contents of `previous` in the first + * callback event (its disappearance). + * + * This happens when: + * + * * the file is deleted, followed by a restore + * * the file is renamed and then renamed a second time back to its original name + * @since v0.1.31 + */ + interface WatchFileOptions { + bigint?: boolean | undefined; + persistent?: boolean | undefined; + interval?: number | undefined; + } + /** + * Watch for changes on `filename`. The callback `listener` will be called each + * time the file is accessed. + * + * The `options` argument may be omitted. If provided, it should be an object. The `options` object may contain a boolean named `persistent` that indicates + * whether the process should continue to run as long as files are being watched. + * The `options` object may specify an `interval` property indicating how often the + * target should be polled in milliseconds. + * + * The `listener` gets two arguments the current stat object and the previous + * stat object: + * + * ```js + * import { watchFile } from 'node:fs'; + * + * watchFile('message.text', (curr, prev) => { + * console.log(`the current mtime is: ${curr.mtime}`); + * console.log(`the previous mtime was: ${prev.mtime}`); + * }); + * ``` + * + * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, + * the numeric values in these objects are specified as `BigInt`s. + * + * To be notified when the file was modified, not just accessed, it is necessary + * to compare `curr.mtimeMs` and `prev.mtimeMs`. + * + * When an `fs.watchFile` operation results in an `ENOENT` error, it + * will invoke the listener once, with all the fields zeroed (or, for dates, the + * Unix Epoch). If the file is created later on, the listener will be called + * again, with the latest stat objects. This is a change in functionality since + * v0.10. + * + * Using {@link watch} is more efficient than `fs.watchFile` and `fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` when possible. + * + * When a file being watched by `fs.watchFile()` disappears and reappears, + * then the contents of `previous` in the second callback event (the file's + * reappearance) will be the same as the contents of `previous` in the first + * callback event (its disappearance). + * + * This happens when: + * + * * the file is deleted, followed by a restore + * * the file is renamed and then renamed a second time back to its original name + * @since v0.1.31 + */ + function watchFile( + filename: PathLike, + options: + | (WatchFileOptions & { + bigint?: false | undefined; + }) + | undefined, + listener: StatsListener, + ): StatWatcher; + function watchFile( + filename: PathLike, + options: + | (WatchFileOptions & { + bigint: true; + }) + | undefined, + listener: BigIntStatsListener, + ): StatWatcher; + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + function watchFile(filename: PathLike, listener: StatsListener): StatWatcher; + /** + * Stop watching for changes on `filename`. If `listener` is specified, only that + * particular listener is removed. Otherwise, _all_ listeners are removed, + * effectively stopping watching of `filename`. + * + * Calling `fs.unwatchFile()` with a filename that is not being watched is a + * no-op, not an error. + * + * Using {@link watch} is more efficient than `fs.watchFile()` and `fs.unwatchFile()`. `fs.watch()` should be used instead of `fs.watchFile()` and `fs.unwatchFile()` when possible. + * @since v0.1.31 + * @param listener Optional, a listener previously attached using `fs.watchFile()` + */ + function unwatchFile(filename: PathLike, listener?: StatsListener): void; + function unwatchFile(filename: PathLike, listener?: BigIntStatsListener): void; + interface WatchOptions extends Abortable { + encoding?: BufferEncoding | "buffer" | undefined; + persistent?: boolean | undefined; + recursive?: boolean | undefined; + } + interface WatchOptionsWithBufferEncoding extends WatchOptions { + encoding: "buffer"; + } + interface WatchOptionsWithStringEncoding extends WatchOptions { + encoding?: BufferEncoding | undefined; + } + type WatchEventType = "rename" | "change"; + type WatchListener = (event: WatchEventType, filename: T | null) => void; + type StatsListener = (curr: Stats, prev: Stats) => void; + type BigIntStatsListener = (curr: BigIntStats, prev: BigIntStats) => void; + /** + * Watch for changes on `filename`, where `filename` is either a file or a + * directory. + * + * The second argument is optional. If `options` is provided as a string, it + * specifies the `encoding`. Otherwise `options` should be passed as an object. + * + * The listener callback gets two arguments `(eventType, filename)`. `eventType`is either `'rename'` or `'change'`, and `filename` is the name of the file + * which triggered the event. + * + * On most platforms, `'rename'` is emitted whenever a filename appears or + * disappears in the directory. + * + * The listener callback is attached to the `'change'` event fired by `fs.FSWatcher`, but it is not the same thing as the `'change'` value of `eventType`. + * + * If a `signal` is passed, aborting the corresponding AbortController will close + * the returned `fs.FSWatcher`. + * @since v0.5.10 + * @param listener + */ + function watch( + filename: PathLike, + options?: WatchOptionsWithStringEncoding | BufferEncoding | null, + listener?: WatchListener, + ): FSWatcher; + function watch( + filename: PathLike, + options: WatchOptionsWithBufferEncoding | "buffer", + listener: WatchListener, + ): FSWatcher; + function watch( + filename: PathLike, + options: WatchOptions | BufferEncoding | "buffer" | null, + listener: WatchListener, + ): FSWatcher; + function watch(filename: PathLike, listener: WatchListener): FSWatcher; + /** + * Test whether or not the given path exists by checking with the file system. + * Then call the `callback` argument with either true or false: + * + * ```js + * import { exists } from 'node:fs'; + * + * exists('/etc/passwd', (e) => { + * console.log(e ? 'it exists' : 'no passwd!'); + * }); + * ``` + * + * **The parameters for this callback are not consistent with other Node.js** + * **callbacks.** Normally, the first parameter to a Node.js callback is an `err` parameter, optionally followed by other parameters. The `fs.exists()` callback + * has only one boolean parameter. This is one reason `fs.access()` is recommended + * instead of `fs.exists()`. + * + * Using `fs.exists()` to check for the existence of a file before calling `fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. Doing + * so introduces a race condition, since other processes may change the file's + * state between the two calls. Instead, user code should open/read/write the + * file directly and handle the error raised if the file does not exist. + * + * **write (NOT RECOMMENDED)** + * + * ```js + * import { exists, open, close } from 'node:fs'; + * + * exists('myfile', (e) => { + * if (e) { + * console.error('myfile already exists'); + * } else { + * open('myfile', 'wx', (err, fd) => { + * if (err) throw err; + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * } + * }); + * ``` + * + * **write (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * open('myfile', 'wx', (err, fd) => { + * if (err) { + * if (err.code === 'EEXIST') { + * console.error('myfile already exists'); + * return; + * } + * + * throw err; + * } + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * **read (NOT RECOMMENDED)** + * + * ```js + * import { open, close, exists } from 'node:fs'; + * + * exists('myfile', (e) => { + * if (e) { + * open('myfile', 'r', (err, fd) => { + * if (err) throw err; + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * } else { + * console.error('myfile does not exist'); + * } + * }); + * ``` + * + * **read (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * + * open('myfile', 'r', (err, fd) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * The "not recommended" examples above check for existence and then use the + * file; the "recommended" examples are better because they use the file directly + * and handle the error, if any. + * + * In general, check for the existence of a file only if the file won't be + * used directly, for example when its existence is a signal from another + * process. + * @since v0.0.2 + * @deprecated Since v1.0.0 - Use {@link stat} or {@link access} instead. + */ + function exists(path: PathLike, callback: (exists: boolean) => void): void; + /** @deprecated */ + namespace exists { + /** + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike): Promise; + } + /** + * Returns `true` if the path exists, `false` otherwise. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link exists}. + * + * `fs.exists()` is deprecated, but `fs.existsSync()` is not. The `callback` parameter to `fs.exists()` accepts parameters that are inconsistent with other + * Node.js callbacks. `fs.existsSync()` does not use a callback. + * + * ```js + * import { existsSync } from 'node:fs'; + * + * if (existsSync('/etc/passwd')) + * console.log('The path exists.'); + * ``` + * @since v0.1.21 + */ + function existsSync(path: PathLike): boolean; + namespace constants { + // File Access Constants + /** Constant for fs.access(). File is visible to the calling process. */ + const F_OK: number; + /** Constant for fs.access(). File can be read by the calling process. */ + const R_OK: number; + /** Constant for fs.access(). File can be written by the calling process. */ + const W_OK: number; + /** Constant for fs.access(). File can be executed by the calling process. */ + const X_OK: number; + // File Copy Constants + /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */ + const COPYFILE_EXCL: number; + /** + * Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. + */ + const COPYFILE_FICLONE: number; + /** + * Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then the operation will fail with an error. + */ + const COPYFILE_FICLONE_FORCE: number; + // File Open Constants + /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ + const O_RDONLY: number; + /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ + const O_WRONLY: number; + /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ + const O_RDWR: number; + /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ + const O_CREAT: number; + /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */ + const O_EXCL: number; + /** + * Constant for fs.open(). Flag indicating that if path identifies a terminal device, + * opening the path shall not cause that terminal to become the controlling terminal for the process + * (if the process does not already have one). + */ + const O_NOCTTY: number; + /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */ + const O_TRUNC: number; + /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ + const O_APPEND: number; + /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ + const O_DIRECTORY: number; + /** + * constant for fs.open(). + * Flag indicating reading accesses to the file system will no longer result in + * an update to the atime information associated with the file. + * This flag is available on Linux operating systems only. + */ + const O_NOATIME: number; + /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ + const O_NOFOLLOW: number; + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ + const O_SYNC: number; + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */ + const O_DSYNC: number; + /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ + const O_SYMLINK: number; + /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ + const O_DIRECT: number; + /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ + const O_NONBLOCK: number; + // File Type Constants + /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */ + const S_IFMT: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ + const S_IFREG: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ + const S_IFDIR: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ + const S_IFCHR: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ + const S_IFBLK: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ + const S_IFIFO: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ + const S_IFLNK: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ + const S_IFSOCK: number; + // File Mode Constants + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */ + const S_IRWXU: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ + const S_IRUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ + const S_IWUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ + const S_IXUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */ + const S_IRWXG: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ + const S_IRGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ + const S_IWGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ + const S_IXGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */ + const S_IRWXO: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ + const S_IROTH: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ + const S_IWOTH: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ + const S_IXOTH: number; + /** + * When set, a memory file mapping is used to access the file. This flag + * is available on Windows operating systems only. On other operating systems, + * this flag is ignored. + */ + const UV_FS_O_FILEMAP: number; + } + /** + * Tests a user's permissions for the file or directory specified by `path`. + * The `mode` argument is an optional integer that specifies the accessibility + * checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and `fs.constants.X_OK` + * (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * The final argument, `callback`, is a callback function that is invoked with + * a possible error argument. If any of the accessibility checks fail, the error + * argument will be an `Error` object. The following examples check if `package.json` exists, and if it is readable or writable. + * + * ```js + * import { access, constants } from 'node:fs'; + * + * const file = 'package.json'; + * + * // Check if the file exists in the current directory. + * access(file, constants.F_OK, (err) => { + * console.log(`${file} ${err ? 'does not exist' : 'exists'}`); + * }); + * + * // Check if the file is readable. + * access(file, constants.R_OK, (err) => { + * console.log(`${file} ${err ? 'is not readable' : 'is readable'}`); + * }); + * + * // Check if the file is writable. + * access(file, constants.W_OK, (err) => { + * console.log(`${file} ${err ? 'is not writable' : 'is writable'}`); + * }); + * + * // Check if the file is readable and writable. + * access(file, constants.R_OK | constants.W_OK, (err) => { + * console.log(`${file} ${err ? 'is not' : 'is'} readable and writable`); + * }); + * ``` + * + * Do not use `fs.access()` to check for the accessibility of a file before calling `fs.open()`, `fs.readFile()`, or `fs.writeFile()`. Doing + * so introduces a race condition, since other processes may change the file's + * state between the two calls. Instead, user code should open/read/write the + * file directly and handle the error raised if the file is not accessible. + * + * **write (NOT RECOMMENDED)** + * + * ```js + * import { access, open, close } from 'node:fs'; + * + * access('myfile', (err) => { + * if (!err) { + * console.error('myfile already exists'); + * return; + * } + * + * open('myfile', 'wx', (err, fd) => { + * if (err) throw err; + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * }); + * ``` + * + * **write (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * + * open('myfile', 'wx', (err, fd) => { + * if (err) { + * if (err.code === 'EEXIST') { + * console.error('myfile already exists'); + * return; + * } + * + * throw err; + * } + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * **read (NOT RECOMMENDED)** + * + * ```js + * import { access, open, close } from 'node:fs'; + * access('myfile', (err) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * open('myfile', 'r', (err, fd) => { + * if (err) throw err; + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * }); + * ``` + * + * **read (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * + * open('myfile', 'r', (err, fd) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * The "not recommended" examples above check for accessibility and then use the + * file; the "recommended" examples are better because they use the file directly + * and handle the error, if any. + * + * In general, check for the accessibility of a file only if the file will not be + * used directly, for example when its accessibility is a signal from another + * process. + * + * On Windows, access-control policies (ACLs) on a directory may limit access to + * a file or directory. The `fs.access()` function, however, does not check the + * ACL and therefore may report that a path is accessible even if the ACL restricts + * the user from reading or writing to it. + * @since v0.11.15 + * @param [mode=fs.constants.F_OK] + */ + function access(path: PathLike, mode: number | undefined, callback: NoParamCallback): void; + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + function access(path: PathLike, callback: NoParamCallback): void; + namespace access { + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike, mode?: number): Promise; + } + /** + * Synchronously tests a user's permissions for the file or directory specified + * by `path`. The `mode` argument is an optional integer that specifies the + * accessibility checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and + * `fs.constants.X_OK` (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * If any of the accessibility checks fail, an `Error` will be thrown. Otherwise, + * the method will return `undefined`. + * + * ```js + * import { accessSync, constants } from 'node:fs'; + * + * try { + * accessSync('etc/passwd', constants.R_OK | constants.W_OK); + * console.log('can read/write'); + * } catch (err) { + * console.error('no access!'); + * } + * ``` + * @since v0.11.15 + * @param [mode=fs.constants.F_OK] + */ + function accessSync(path: PathLike, mode?: number): void; + interface StreamOptions { + flags?: string | undefined; + encoding?: BufferEncoding | undefined; + fd?: number | FileHandle | undefined; + mode?: number | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + signal?: AbortSignal | null | undefined; + highWaterMark?: number | undefined; + } + interface FSImplementation { + open?: (...args: any[]) => any; + close?: (...args: any[]) => any; + } + interface CreateReadStreamFSImplementation extends FSImplementation { + read: (...args: any[]) => any; + } + interface CreateWriteStreamFSImplementation extends FSImplementation { + write: (...args: any[]) => any; + writev?: (...args: any[]) => any; + } + interface ReadStreamOptions extends StreamOptions { + fs?: CreateReadStreamFSImplementation | null | undefined; + end?: number | undefined; + } + interface WriteStreamOptions extends StreamOptions { + fs?: CreateWriteStreamFSImplementation | null | undefined; + flush?: boolean | undefined; + } + /** + * `options` can include `start` and `end` values to read a range of bytes from + * the file instead of the entire file. Both `start` and `end` are inclusive and + * start counting at 0, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `fd` is specified and `start` is + * omitted or `undefined`, `fs.createReadStream()` reads sequentially from the + * current file position. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `fd` is specified, `ReadStream` will ignore the `path` argument and will use + * the specified file descriptor. This means that no `'open'` event will be + * emitted. `fd` should be blocking; non-blocking `fd`s should be passed to `net.Socket`. + * + * If `fd` points to a character device that only supports blocking reads + * (such as keyboard or sound card), read operations do not finish until data is + * available. This can prevent the process from exiting and the stream from + * closing naturally. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * By providing the `fs` option, it is possible to override the corresponding `fs` implementations for `open`, `read`, and `close`. When providing the `fs` option, + * an override for `read` is required. If no `fd` is provided, an override for `open` is also required. If `autoClose` is `true`, an override for `close` is + * also required. + * + * ```js + * import { createReadStream } from 'node:fs'; + * + * // Create a stream from some character device. + * const stream = createReadStream('/dev/input/event0'); + * setTimeout(() => { + * stream.close(); // This may not close the stream. + * // Artificially marking end-of-stream, as if the underlying resource had + * // indicated end-of-file by itself, allows the stream to close. + * // This does not cancel pending read operations, and if there is such an + * // operation, the process may still not be able to exit successfully + * // until it finishes. + * stream.push(null); + * stream.read(0); + * }, 100); + * ``` + * + * If `autoClose` is false, then the file descriptor won't be closed, even if + * there's an error. It is the application's responsibility to close it and make + * sure there's no file descriptor leak. If `autoClose` is set to true (default + * behavior), on `'error'` or `'end'` the file descriptor will be closed + * automatically. + * + * `mode` sets the file mode (permission and sticky bits), but only if the + * file was created. + * + * An example to read the last 10 bytes of a file which is 100 bytes long: + * + * ```js + * import { createReadStream } from 'node:fs'; + * + * createReadStream('sample.txt', { start: 90, end: 99 }); + * ``` + * + * If `options` is a string, then it specifies the encoding. + * @since v0.1.31 + */ + function createReadStream(path: PathLike, options?: BufferEncoding | ReadStreamOptions): ReadStream; + /** + * `options` may also include a `start` option to allow writing data at some + * position past the beginning of the file, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than + * replacing it may require the `flags` option to be set to `r+` rather than the + * default `w`. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'` the file descriptor will be closed automatically. If `autoClose` is false, + * then the file descriptor won't be closed, even if there's an error. + * It is the application's responsibility to close it and make sure there's no + * file descriptor leak. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * By providing the `fs` option it is possible to override the corresponding `fs` implementations for `open`, `write`, `writev`, and `close`. Overriding `write()` without `writev()` can reduce + * performance as some optimizations (`_writev()`) + * will be disabled. When providing the `fs` option, overrides for at least one of `write` and `writev` are required. If no `fd` option is supplied, an override + * for `open` is also required. If `autoClose` is `true`, an override for `close` is also required. + * + * Like `fs.ReadStream`, if `fd` is specified, `fs.WriteStream` will ignore the `path` argument and will use the specified file descriptor. This means that no `'open'` event will be + * emitted. `fd` should be blocking; non-blocking `fd`s + * should be passed to `net.Socket`. + * + * If `options` is a string, then it specifies the encoding. + * @since v0.1.31 + */ + function createWriteStream(path: PathLike, options?: BufferEncoding | WriteStreamOptions): WriteStream; + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. No arguments other + * than a possible + * exception are given to the completion callback. + * @since v0.1.96 + */ + function fdatasync(fd: number, callback: NoParamCallback): void; + namespace fdatasync { + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. Returns `undefined`. + * @since v0.1.96 + */ + function fdatasyncSync(fd: number): void; + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. No arguments other than a possible exception are given to the + * callback function. Node.js makes no guarantees about the atomicity of the copy + * operation. If an error occurs after the destination file has been opened for + * writing, Node.js will attempt to remove the destination. + * + * `mode` is an optional integer that specifies the behavior + * of the copy operation. It is possible to create a mask consisting of the bitwise + * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). + * + * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already + * exists. + * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a + * copy-on-write reflink. If the platform does not support copy-on-write, then a + * fallback copy mechanism is used. + * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to + * create a copy-on-write reflink. If the platform does not support + * copy-on-write, then the operation will fail. + * + * ```js + * import { copyFile, constants } from 'node:fs'; + * + * function callback(err) { + * if (err) throw err; + * console.log('source.txt was copied to destination.txt'); + * } + * + * // destination.txt will be created or overwritten by default. + * copyFile('source.txt', 'destination.txt', callback); + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback); + * ``` + * @since v8.5.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] modifiers for copy operation. + */ + function copyFile(src: PathLike, dest: PathLike, callback: NoParamCallback): void; + function copyFile(src: PathLike, dest: PathLike, mode: number, callback: NoParamCallback): void; + namespace copyFile { + function __promisify__(src: PathLike, dst: PathLike, mode?: number): Promise; + } + /** + * Synchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. Returns `undefined`. Node.js makes no guarantees about the + * atomicity of the copy operation. If an error occurs after the destination file + * has been opened for writing, Node.js will attempt to remove the destination. + * + * `mode` is an optional integer that specifies the behavior + * of the copy operation. It is possible to create a mask consisting of the bitwise + * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). + * + * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already + * exists. + * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a + * copy-on-write reflink. If the platform does not support copy-on-write, then a + * fallback copy mechanism is used. + * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to + * create a copy-on-write reflink. If the platform does not support + * copy-on-write, then the operation will fail. + * + * ```js + * import { copyFileSync, constants } from 'node:fs'; + * + * // destination.txt will be created or overwritten by default. + * copyFileSync('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * copyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL); + * ``` + * @since v8.5.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] modifiers for copy operation. + */ + function copyFileSync(src: PathLike, dest: PathLike, mode?: number): void; + /** + * Write an array of `ArrayBufferView`s to the file specified by `fd` using `writev()`. + * + * `position` is the offset from the beginning of the file where this data + * should be written. If `typeof position !== 'number'`, the data will be written + * at the current position. + * + * The callback will be given three arguments: `err`, `bytesWritten`, and `buffers`. `bytesWritten` is how many bytes were written from `buffers`. + * + * If this method is `util.promisify()` ed, it returns a promise for an `Object` with `bytesWritten` and `buffers` properties. + * + * It is unsafe to use `fs.writev()` multiple times on the same file without + * waiting for the callback. For this scenario, use {@link createWriteStream}. + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v12.9.0 + * @param [position='null'] + */ + function writev( + fd: number, + buffers: TBuffers, + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: TBuffers) => void, + ): void; + function writev( + fd: number, + buffers: TBuffers, + position: number | null, + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: TBuffers) => void, + ): void; + // Providing a default type parameter doesn't provide true BC for userland consumers, but at least suppresses TS2314 + // TODO: remove default in future major version + interface WriteVResult { + bytesWritten: number; + buffers: T; + } + namespace writev { + function __promisify__( + fd: number, + buffers: TBuffers, + position?: number, + ): Promise>; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link writev}. + * @since v12.9.0 + * @param [position='null'] + * @return The number of bytes written. + */ + function writevSync(fd: number, buffers: readonly NodeJS.ArrayBufferView[], position?: number): number; + /** + * Read from a file specified by `fd` and write to an array of `ArrayBufferView`s + * using `readv()`. + * + * `position` is the offset from the beginning of the file from where data + * should be read. If `typeof position !== 'number'`, the data will be read + * from the current position. + * + * The callback will be given three arguments: `err`, `bytesRead`, and `buffers`. `bytesRead` is how many bytes were read from the file. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesRead` and `buffers` properties. + * @since v13.13.0, v12.17.0 + * @param [position='null'] + */ + function readv( + fd: number, + buffers: TBuffers, + cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: TBuffers) => void, + ): void; + function readv( + fd: number, + buffers: TBuffers, + position: number | null, + cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: TBuffers) => void, + ): void; + // Providing a default type parameter doesn't provide true BC for userland consumers, but at least suppresses TS2314 + // TODO: remove default in future major version + interface ReadVResult { + bytesRead: number; + buffers: T; + } + namespace readv { + function __promisify__( + fd: number, + buffers: TBuffers, + position?: number, + ): Promise>; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link readv}. + * @since v13.13.0, v12.17.0 + * @param [position='null'] + * @return The number of bytes read. + */ + function readvSync(fd: number, buffers: readonly NodeJS.ArrayBufferView[], position?: number): number; + + interface OpenAsBlobOptions { + /** + * An optional mime type for the blob. + * + * @default 'undefined' + */ + type?: string | undefined; + } + + /** + * Returns a `Blob` whose data is backed by the given file. + * + * The file must not be modified after the `Blob` is created. Any modifications + * will cause reading the `Blob` data to fail with a `DOMException` error. + * Synchronous stat operations on the file when the `Blob` is created, and before + * each read in order to detect whether the file data has been modified on disk. + * + * ```js + * import { openAsBlob } from 'node:fs'; + * + * const blob = await openAsBlob('the.file.txt'); + * const ab = await blob.arrayBuffer(); + * blob.stream(); + * ``` + * @since v19.8.0 + */ + function openAsBlob(path: PathLike, options?: OpenAsBlobOptions): Promise; + + interface OpenDirOptions { + /** + * @default 'utf8' + */ + encoding?: BufferEncoding | undefined; + /** + * Number of directory entries that are buffered + * internally when reading from the directory. Higher values lead to better + * performance but higher memory usage. + * @default 32 + */ + bufferSize?: number | undefined; + /** + * @default false + */ + recursive?: boolean | undefined; + } + /** + * Synchronously open a directory. See [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html). + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * @since v12.12.0 + */ + function opendirSync(path: PathLike, options?: OpenDirOptions): Dir; + /** + * Asynchronously open a directory. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for + * more details. + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * @since v12.12.0 + */ + function opendir(path: PathLike, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; + function opendir( + path: PathLike, + options: OpenDirOptions, + cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void, + ): void; + namespace opendir { + function __promisify__(path: PathLike, options?: OpenDirOptions): Promise; + } + interface BigIntStats extends StatsBase { + atimeNs: bigint; + mtimeNs: bigint; + ctimeNs: bigint; + birthtimeNs: bigint; + } + interface BigIntOptions { + bigint: true; + } + interface StatOptions { + bigint?: boolean | undefined; + } + interface StatSyncOptions extends StatOptions { + throwIfNoEntry?: boolean | undefined; + } + interface CopyOptionsBase { + /** + * Dereference symlinks + * @default false + */ + dereference?: boolean | undefined; + /** + * When `force` is `false`, and the destination + * exists, throw an error. + * @default false + */ + errorOnExist?: boolean | undefined; + /** + * Overwrite existing file or directory. _The copy + * operation will ignore errors if you set this to false and the destination + * exists. Use the `errorOnExist` option to change this behavior. + * @default true + */ + force?: boolean | undefined; + /** + * Modifiers for copy operation. See `mode` flag of {@link copyFileSync()} + */ + mode?: number | undefined; + /** + * When `true` timestamps from `src` will + * be preserved. + * @default false + */ + preserveTimestamps?: boolean | undefined; + /** + * Copy directories recursively. + * @default false + */ + recursive?: boolean | undefined; + /** + * When true, path resolution for symlinks will be skipped + * @default false + */ + verbatimSymlinks?: boolean | undefined; + } + interface CopyOptions extends CopyOptionsBase { + /** + * Function to filter copied files/directories. Return + * `true` to copy the item, `false` to ignore it. + */ + filter?: ((source: string, destination: string) => boolean | Promise) | undefined; + } + interface CopySyncOptions extends CopyOptionsBase { + /** + * Function to filter copied files/directories. Return + * `true` to copy the item, `false` to ignore it. + */ + filter?: ((source: string, destination: string) => boolean) | undefined; + } + /** + * Asynchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + */ + function cp( + source: string | URL, + destination: string | URL, + callback: (err: NodeJS.ErrnoException | null) => void, + ): void; + function cp( + source: string | URL, + destination: string | URL, + opts: CopyOptions, + callback: (err: NodeJS.ErrnoException | null) => void, + ): void; + /** + * Synchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + */ + function cpSync(source: string | URL, destination: string | URL, opts?: CopySyncOptions): void; + + // TODO: collapse + interface _GlobOptions { + /** + * Current working directory. + * @default process.cwd() + */ + cwd?: string | URL | undefined; + /** + * `true` if the glob should return paths as `Dirent`s, `false` otherwise. + * @default false + * @since v22.2.0 + */ + withFileTypes?: boolean | undefined; + /** + * Function to filter out files/directories or a + * list of glob patterns to be excluded. If a function is provided, return + * `true` to exclude the item, `false` to include it. + * If a string array is provided, each string should be a glob pattern that + * specifies paths to exclude. Note: Negation patterns (e.g., '!foo.js') are + * not supported. + * @default undefined + */ + exclude?: ((fileName: T) => boolean) | readonly string[] | undefined; + } + interface GlobOptions extends _GlobOptions {} + interface GlobOptionsWithFileTypes extends _GlobOptions { + withFileTypes: true; + } + interface GlobOptionsWithoutFileTypes extends _GlobOptions { + withFileTypes?: false | undefined; + } + + /** + * Retrieves the files matching the specified pattern. + * + * ```js + * import { glob } from 'node:fs'; + * + * glob('*.js', (err, matches) => { + * if (err) throw err; + * console.log(matches); + * }); + * ``` + * @since v22.0.0 + */ + function glob( + pattern: string | readonly string[], + callback: (err: NodeJS.ErrnoException | null, matches: string[]) => void, + ): void; + function glob( + pattern: string | readonly string[], + options: GlobOptionsWithFileTypes, + callback: ( + err: NodeJS.ErrnoException | null, + matches: Dirent[], + ) => void, + ): void; + function glob( + pattern: string | readonly string[], + options: GlobOptionsWithoutFileTypes, + callback: ( + err: NodeJS.ErrnoException | null, + matches: string[], + ) => void, + ): void; + function glob( + pattern: string | readonly string[], + options: GlobOptions, + callback: ( + err: NodeJS.ErrnoException | null, + matches: Dirent[] | string[], + ) => void, + ): void; + /** + * ```js + * import { globSync } from 'node:fs'; + * + * console.log(globSync('*.js')); + * ``` + * @since v22.0.0 + * @returns paths of files that match the pattern. + */ + function globSync(pattern: string | readonly string[]): string[]; + function globSync( + pattern: string | readonly string[], + options: GlobOptionsWithFileTypes, + ): Dirent[]; + function globSync( + pattern: string | readonly string[], + options: GlobOptionsWithoutFileTypes, + ): string[]; + function globSync( + pattern: string | readonly string[], + options: GlobOptions, + ): Dirent[] | string[]; +} +declare module "node:fs" { + export * as promises from "node:fs/promises"; +} +declare module "fs" { + export * from "node:fs"; +} diff --git a/backend/node_modules/@types/node/fs/promises.d.ts b/backend/node_modules/@types/node/fs/promises.d.ts new file mode 100644 index 0000000..ded1b24 --- /dev/null +++ b/backend/node_modules/@types/node/fs/promises.d.ts @@ -0,0 +1,1316 @@ +/** + * The `fs/promises` API provides asynchronous file system methods that return + * promises. + * + * The promise APIs use the underlying Node.js threadpool to perform file + * system operations off the event loop thread. These operations are not + * synchronized or threadsafe. Care must be taken when performing multiple + * concurrent modifications on the same file or data corruption may occur. + * @since v10.0.0 + */ +declare module "node:fs/promises" { + import { NonSharedBuffer } from "node:buffer"; + import { Abortable } from "node:events"; + import { Interface as ReadlineInterface } from "node:readline"; + import { + BigIntStats, + BigIntStatsFs, + BufferEncodingOption, + constants as fsConstants, + CopyOptions, + Dir, + Dirent, + DisposableTempDir, + EncodingOption, + GlobOptions, + GlobOptionsWithFileTypes, + GlobOptionsWithoutFileTypes, + MakeDirectoryOptions, + Mode, + ObjectEncodingOptions, + OpenDirOptions, + OpenMode, + PathLike, + ReadOptions, + ReadOptionsWithBuffer, + ReadPosition, + ReadStream, + ReadVResult, + RmOptions, + StatFsOptions, + StatOptions, + Stats, + StatsFs, + TimeLike, + WatchEventType, + WatchOptions as _WatchOptions, + WriteStream, + WriteVResult, + } from "node:fs"; + import { Stream } from "node:stream"; + import { ReadableStream } from "node:stream/web"; + interface FileChangeInfo { + eventType: WatchEventType; + filename: T | null; + } + interface FlagAndOpenMode { + mode?: Mode | undefined; + flag?: OpenMode | undefined; + } + interface FileReadResult { + bytesRead: number; + buffer: T; + } + /** @deprecated This interface will be removed in a future version. Use `import { ReadOptionsWithBuffer } from "node:fs"` instead. */ + interface FileReadOptions { + /** + * @default `Buffer.alloc(0xffff)` + */ + buffer?: T; + /** + * @default 0 + */ + offset?: number | null; + /** + * @default `buffer.byteLength` + */ + length?: number | null; + position?: ReadPosition | null; + } + interface CreateReadStreamOptions extends Abortable { + encoding?: BufferEncoding | null | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + end?: number | undefined; + highWaterMark?: number | undefined; + } + interface CreateWriteStreamOptions { + encoding?: BufferEncoding | null | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + highWaterMark?: number | undefined; + flush?: boolean | undefined; + } + interface ReadableWebStreamOptions { + autoClose?: boolean | undefined; + } + // TODO: Add `EventEmitter` close + interface FileHandle { + /** + * The numeric file descriptor managed by the {FileHandle} object. + * @since v10.0.0 + */ + readonly fd: number; + /** + * Alias of `filehandle.writeFile()`. + * + * When operating on file handles, the mode cannot be changed from what it was set + * to with `fsPromises.open()`. Therefore, this is equivalent to `filehandle.writeFile()`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + appendFile( + data: string | Uint8Array, + options?: + | (ObjectEncodingOptions & Abortable) + | BufferEncoding + | null, + ): Promise; + /** + * Changes the ownership of the file. A wrapper for [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html). + * @since v10.0.0 + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + * @return Fulfills with `undefined` upon success. + */ + chown(uid: number, gid: number): Promise; + /** + * Modifies the permissions on the file. See [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html). + * @since v10.0.0 + * @param mode the file mode bit mask. + * @return Fulfills with `undefined` upon success. + */ + chmod(mode: Mode): Promise; + /** + * Unlike the 16 KiB default `highWaterMark` for a `stream.Readable`, the stream + * returned by this method has a default `highWaterMark` of 64 KiB. + * + * `options` can include `start` and `end` values to read a range of bytes from + * the file instead of the entire file. Both `start` and `end` are inclusive and + * start counting at 0, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `start` is + * omitted or `undefined`, `filehandle.createReadStream()` reads sequentially from + * the current file position. The `encoding` can be any one of those accepted by `Buffer`. + * + * If the `FileHandle` points to a character device that only supports blocking + * reads (such as keyboard or sound card), read operations do not finish until data + * is available. This can prevent the process from exiting and the stream from + * closing naturally. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const fd = await open('/dev/input/event0'); + * // Create a stream from some character device. + * const stream = fd.createReadStream(); + * setTimeout(() => { + * stream.close(); // This may not close the stream. + * // Artificially marking end-of-stream, as if the underlying resource had + * // indicated end-of-file by itself, allows the stream to close. + * // This does not cancel pending read operations, and if there is such an + * // operation, the process may still not be able to exit successfully + * // until it finishes. + * stream.push(null); + * stream.read(0); + * }, 100); + * ``` + * + * If `autoClose` is false, then the file descriptor won't be closed, even if + * there's an error. It is the application's responsibility to close it and make + * sure there's no file descriptor leak. If `autoClose` is set to true (default + * behavior), on `'error'` or `'end'` the file descriptor will be closed + * automatically. + * + * An example to read the last 10 bytes of a file which is 100 bytes long: + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const fd = await open('sample.txt'); + * fd.createReadStream({ start: 90, end: 99 }); + * ``` + * @since v16.11.0 + */ + createReadStream(options?: CreateReadStreamOptions): ReadStream; + /** + * `options` may also include a `start` option to allow writing data at some + * position past the beginning of the file, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than + * replacing it may require the `flags` `open` option to be set to `r+` rather than + * the default `r`. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'` the file descriptor will be closed automatically. If `autoClose` is false, + * then the file descriptor won't be closed, even if there's an error. + * It is the application's responsibility to close it and make sure there's no + * file descriptor leak. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * @since v16.11.0 + */ + createWriteStream(options?: CreateWriteStreamOptions): WriteStream; + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. + * + * Unlike `filehandle.sync` this method does not flush modified metadata. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + datasync(): Promise; + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + sync(): Promise; + /** + * Reads data from the file and stores that in the given buffer. + * + * If the file is not modified concurrently, the end-of-file is reached when the + * number of bytes read is zero. + * @since v10.0.0 + * @param buffer A buffer that will be filled with the file data read. + * @param offset The location in the buffer at which to start filling. + * @param length The number of bytes to read. + * @param position The location where to begin reading data from the file. If `null`, data will be read from the current file position, and the position will be updated. If `position` is an + * integer, the current file position will remain unchanged. + * @return Fulfills upon success with an object with two properties: + */ + read( + buffer: T, + offset?: number | null, + length?: number | null, + position?: ReadPosition | null, + ): Promise>; + read( + buffer: T, + options?: ReadOptions, + ): Promise>; + read( + options?: ReadOptionsWithBuffer, + ): Promise>; + /** + * Returns a byte-oriented `ReadableStream` that may be used to read the file's + * contents. + * + * An error will be thrown if this method is called more than once or is called + * after the `FileHandle` is closed or closing. + * + * ```js + * import { + * open, + * } from 'node:fs/promises'; + * + * const file = await open('./some/file/to/read'); + * + * for await (const chunk of file.readableWebStream()) + * console.log(chunk); + * + * await file.close(); + * ``` + * + * While the `ReadableStream` will read the file to completion, it will not + * close the `FileHandle` automatically. User code must still call the`fileHandle.close()` method. + * @since v17.0.0 + */ + readableWebStream(options?: ReadableWebStreamOptions): ReadableStream; + /** + * Asynchronously reads the entire contents of a file. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `FileHandle` has to support reading. + * + * If one or more `filehandle.read()` calls are made on a file handle and then a `filehandle.readFile()` call is made, the data will be read from the current + * position till the end of the file. It doesn't always read from the beginning + * of the file. + * @since v10.0.0 + * @return Fulfills upon a successful read with the contents of the file. If no encoding is specified (using `options.encoding`), the data is returned as a {Buffer} object. Otherwise, the + * data will be a string. + */ + readFile( + options?: + | ({ encoding?: null | undefined } & Abortable) + | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + */ + readFile( + options: + | ({ encoding: BufferEncoding } & Abortable) + | BufferEncoding, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + */ + readFile( + options?: + | (ObjectEncodingOptions & Abortable) + | BufferEncoding + | null, + ): Promise; + /** + * Convenience method to create a `readline` interface and stream over the file. + * See `filehandle.createReadStream()` for the options. + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const file = await open('./some/file/to/read'); + * + * for await (const line of file.readLines()) { + * console.log(line); + * } + * ``` + * @since v18.11.0 + */ + readLines(options?: CreateReadStreamOptions): ReadlineInterface; + /** + * @since v10.0.0 + * @return Fulfills with an {fs.Stats} for the file. + */ + stat( + opts?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + stat( + opts: StatOptions & { + bigint: true; + }, + ): Promise; + stat(opts?: StatOptions): Promise; + /** + * Truncates the file. + * + * If the file was larger than `len` bytes, only the first `len` bytes will be + * retained in the file. + * + * The following example retains only the first four bytes of the file: + * + * ```js + * import { open } from 'node:fs/promises'; + * + * let filehandle = null; + * try { + * filehandle = await open('temp.txt', 'r+'); + * await filehandle.truncate(4); + * } finally { + * await filehandle?.close(); + * } + * ``` + * + * If the file previously was shorter than `len` bytes, it is extended, and the + * extended part is filled with null bytes (`'\0'`): + * + * If `len` is negative then `0` will be used. + * @since v10.0.0 + * @param [len=0] + * @return Fulfills with `undefined` upon success. + */ + truncate(len?: number): Promise; + /** + * Change the file system timestamps of the object referenced by the `FileHandle` then fulfills the promise with no arguments upon success. + * @since v10.0.0 + */ + utimes(atime: TimeLike, mtime: TimeLike): Promise; + /** + * Asynchronously writes data to a file, replacing the file if it already exists. `data` can be a string, a buffer, an + * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. + * The promise is fulfilled with no arguments upon success. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `FileHandle` has to support writing. + * + * It is unsafe to use `filehandle.writeFile()` multiple times on the same file + * without waiting for the promise to be fulfilled (or rejected). + * + * If one or more `filehandle.write()` calls are made on a file handle and then a`filehandle.writeFile()` call is made, the data will be written from the + * current position till the end of the file. It doesn't always write from the + * beginning of the file. + * @since v10.0.0 + */ + writeFile( + data: string | Uint8Array, + options?: + | (ObjectEncodingOptions & Abortable) + | BufferEncoding + | null, + ): Promise; + /** + * Write `buffer` to the file. + * + * The promise is fulfilled with an object containing two properties: + * + * It is unsafe to use `filehandle.write()` multiple times on the same file + * without waiting for the promise to be fulfilled (or rejected). For this + * scenario, use `filehandle.createWriteStream()`. + * + * On Linux, positional writes do not work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v10.0.0 + * @param offset The start position from within `buffer` where the data to write begins. + * @param [length=buffer.byteLength - offset] The number of bytes from `buffer` to write. + * @param [position='null'] The offset from the beginning of the file where the data from `buffer` should be written. If `position` is not a `number`, the data will be written at the current + * position. See the POSIX pwrite(2) documentation for more detail. + */ + write( + buffer: TBuffer, + offset?: number | null, + length?: number | null, + position?: number | null, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + write( + buffer: TBuffer, + options?: { offset?: number; length?: number; position?: number }, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + write( + data: string, + position?: number | null, + encoding?: BufferEncoding | null, + ): Promise<{ + bytesWritten: number; + buffer: string; + }>; + /** + * Write an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s to the file. + * + * The promise is fulfilled with an object containing a two properties: + * + * It is unsafe to call `writev()` multiple times on the same file without waiting + * for the promise to be fulfilled (or rejected). + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v12.9.0 + * @param [position='null'] The offset from the beginning of the file where the data from `buffers` should be written. If `position` is not a `number`, the data will be written at the current + * position. + */ + writev( + buffers: TBuffers, + position?: number, + ): Promise>; + /** + * Read from a file and write to an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s + * @since v13.13.0, v12.17.0 + * @param [position='null'] The offset from the beginning of the file where the data should be read from. If `position` is not a `number`, the data will be read from the current position. + * @return Fulfills upon success an object containing two properties: + */ + readv( + buffers: TBuffers, + position?: number, + ): Promise>; + /** + * Closes the file handle after waiting for any pending operation on the handle to + * complete. + * + * ```js + * import { open } from 'node:fs/promises'; + * + * let filehandle; + * try { + * filehandle = await open('thefile.txt', 'r'); + * } finally { + * await filehandle?.close(); + * } + * ``` + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + close(): Promise; + /** + * Calls `filehandle.close()` and returns a promise that fulfills when the + * filehandle is closed. + * @since v20.4.0, v18.8.0 + */ + [Symbol.asyncDispose](): Promise; + } + const constants: typeof fsConstants; + /** + * Tests a user's permissions for the file or directory specified by `path`. + * The `mode` argument is an optional integer that specifies the accessibility + * checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and `fs.constants.X_OK` + * (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * If the accessibility check is successful, the promise is fulfilled with no + * value. If any of the accessibility checks fail, the promise is rejected + * with an [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object. The following example checks if the file`/etc/passwd` can be read and + * written by the current process. + * + * ```js + * import { access, constants } from 'node:fs/promises'; + * + * try { + * await access('/etc/passwd', constants.R_OK | constants.W_OK); + * console.log('can access'); + * } catch { + * console.error('cannot access'); + * } + * ``` + * + * Using `fsPromises.access()` to check for the accessibility of a file before + * calling `fsPromises.open()` is not recommended. Doing so introduces a race + * condition, since other processes may change the file's state between the two + * calls. Instead, user code should open/read/write the file directly and handle + * the error raised if the file is not accessible. + * @since v10.0.0 + * @param [mode=fs.constants.F_OK] + * @return Fulfills with `undefined` upon success. + */ + function access(path: PathLike, mode?: number): Promise; + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. + * + * No guarantees are made about the atomicity of the copy operation. If an + * error occurs after the destination file has been opened for writing, an attempt + * will be made to remove the destination. + * + * ```js + * import { copyFile, constants } from 'node:fs/promises'; + * + * try { + * await copyFile('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.error('The file could not be copied'); + * } + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * try { + * await copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.error('The file could not be copied'); + * } + * ``` + * @since v10.0.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] Optional modifiers that specify the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g. + * `fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`) + * @return Fulfills with `undefined` upon success. + */ + function copyFile(src: PathLike, dest: PathLike, mode?: number): Promise; + /** + * Opens a `FileHandle`. + * + * Refer to the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more detail. + * + * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented + * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains + * a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). + * @since v10.0.0 + * @param [flags='r'] See `support of file system `flags``. + * @param [mode=0o666] Sets the file mode (permission and sticky bits) if the file is created. + * @return Fulfills with a {FileHandle} object. + */ + function open(path: PathLike, flags?: string | number, mode?: Mode): Promise; + /** + * Renames `oldPath` to `newPath`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function rename(oldPath: PathLike, newPath: PathLike): Promise; + /** + * Truncates (shortens or extends the length) of the content at `path` to `len` bytes. + * @since v10.0.0 + * @param [len=0] + * @return Fulfills with `undefined` upon success. + */ + function truncate(path: PathLike, len?: number): Promise; + /** + * Removes the directory identified by `path`. + * + * Using `fsPromises.rmdir()` on a file (not a directory) results in the + * promise being rejected with an `ENOENT` error on Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use `fsPromises.rm()` with options `{ recursive: true, force: true }`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function rmdir(path: PathLike): Promise; + /** + * Removes files and directories (modeled on the standard POSIX `rm` utility). + * @since v14.14.0 + * @return Fulfills with `undefined` upon success. + */ + function rm(path: PathLike, options?: RmOptions): Promise; + /** + * Asynchronously creates a directory. + * + * The optional `options` argument can be an integer specifying `mode` (permission + * and sticky bits), or an object with a `mode` property and a `recursive` property indicating whether parent directories should be created. Calling `fsPromises.mkdir()` when `path` is a directory + * that exists results in a + * rejection only when `recursive` is false. + * + * ```js + * import { mkdir } from 'node:fs/promises'; + * + * try { + * const projectFolder = new URL('./test/project/', import.meta.url); + * const createDir = await mkdir(projectFolder, { recursive: true }); + * + * console.log(`created ${createDir}`); + * } catch (err) { + * console.error(err.message); + * } + * ``` + * @since v10.0.0 + * @return Upon success, fulfills with `undefined` if `recursive` is `false`, or the first directory path created if `recursive` is `true`. + */ + function mkdir( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, options?: Mode | MakeDirectoryOptions | null): Promise; + /** + * Reads the contents of a directory. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames. If the `encoding` is set to `'buffer'`, the filenames returned + * will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the returned array will contain `fs.Dirent` objects. + * + * ```js + * import { readdir } from 'node:fs/promises'; + * + * try { + * const files = await readdir(path); + * for (const file of files) + * console.log(file); + * } catch (err) { + * console.error(err); + * } + * ``` + * @since v10.0.0 + * @return Fulfills with an array of the names of the files in the directory excluding `'.'` and `'..'`. + */ + function readdir( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdir( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a directory. If a URL is provided, it must use the `file:` protocol. + * @param options Must include `withFileTypes: true` and `encoding: 'buffer'`. + */ + function readdir( + path: PathLike, + options: { + encoding: "buffer"; + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise[]>; + /** + * Reads the contents of the symbolic link referred to by `path`. See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more detail. The promise is + * fulfilled with the`linkString` upon success. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path returned. If the `encoding` is set to `'buffer'`, the link path + * returned will be passed as a `Buffer` object. + * @since v10.0.0 + * @return Fulfills with the `linkString` upon success. + */ + function readlink(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink( + path: PathLike, + options?: ObjectEncodingOptions | string | null, + ): Promise; + /** + * Creates a symbolic link. + * + * The `type` argument is only used on Windows platforms and can be one of `'dir'`, `'file'`, or `'junction'`. If the `type` argument is not a string, Node.js will + * autodetect `target` type and use `'file'` or `'dir'`. If the `target` does not + * exist, `'file'` will be used. Windows junction points require the destination + * path to be absolute. When using `'junction'`, the `target` argument will + * automatically be normalized to absolute path. Junction points on NTFS volumes + * can only point to directories. + * @since v10.0.0 + * @param [type='null'] + * @return Fulfills with `undefined` upon success. + */ + function symlink(target: PathLike, path: PathLike, type?: string | null): Promise; + /** + * Equivalent to `fsPromises.stat()` unless `path` refers to a symbolic link, + * in which case the link itself is stat-ed, not the file that it refers to. + * Refer to the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) document for more detail. + * @since v10.0.0 + * @return Fulfills with the {fs.Stats} object for the given symbolic link `path`. + */ + function lstat( + path: PathLike, + opts?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function lstat( + path: PathLike, + opts: StatOptions & { + bigint: true; + }, + ): Promise; + function lstat(path: PathLike, opts?: StatOptions): Promise; + /** + * @since v10.0.0 + * @return Fulfills with the {fs.Stats} object for the given `path`. + */ + function stat( + path: PathLike, + opts?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function stat( + path: PathLike, + opts: StatOptions & { + bigint: true; + }, + ): Promise; + function stat(path: PathLike, opts?: StatOptions): Promise; + /** + * @since v19.6.0, v18.15.0 + * @return Fulfills with the {fs.StatFs} object for the given `path`. + */ + function statfs( + path: PathLike, + opts?: StatFsOptions & { + bigint?: false | undefined; + }, + ): Promise; + function statfs( + path: PathLike, + opts: StatFsOptions & { + bigint: true; + }, + ): Promise; + function statfs(path: PathLike, opts?: StatFsOptions): Promise; + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function link(existingPath: PathLike, newPath: PathLike): Promise; + /** + * If `path` refers to a symbolic link, then the link is removed without affecting + * the file or directory to which that link refers. If the `path` refers to a file + * path that is not a symbolic link, the file is deleted. See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function unlink(path: PathLike): Promise; + /** + * Changes the permissions of a file. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function chmod(path: PathLike, mode: Mode): Promise; + /** + * Changes the permissions on a symbolic link. + * + * This method is only implemented on macOS. + * @deprecated Since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function lchmod(path: PathLike, mode: Mode): Promise; + /** + * Changes the ownership on a symbolic link. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function lchown(path: PathLike, uid: number, gid: number): Promise; + /** + * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, with the difference that if the path refers to a + * symbolic link, then the link is not dereferenced: instead, the timestamps of + * the symbolic link itself are changed. + * @since v14.5.0, v12.19.0 + * @return Fulfills with `undefined` upon success. + */ + function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + /** + * Changes the ownership of a file. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function chown(path: PathLike, uid: number, gid: number): Promise; + /** + * Change the file system timestamps of the object referenced by `path`. + * + * The `atime` and `mtime` arguments follow these rules: + * + * * Values can be either numbers representing Unix epoch time, `Date`s, or a + * numeric string like `'123456789.0'`. + * * If the value can not be converted to a number, or is `NaN`, `Infinity`, or `-Infinity`, an `Error` will be thrown. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + /** + * Determines the actual location of `path` using the same semantics as the `fs.realpath.native()` function. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path. If the `encoding` is set to `'buffer'`, the path returned will be + * passed as a `Buffer` object. + * + * On Linux, when Node.js is linked against musl libc, the procfs file system must + * be mounted on `/proc` in order for this function to work. Glibc does not have + * this restriction. + * @since v10.0.0 + * @return Fulfills with the resolved path upon success. + */ + function realpath(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath( + path: PathLike, + options?: ObjectEncodingOptions | BufferEncoding | null, + ): Promise; + /** + * Creates a unique temporary directory. A unique directory name is generated by + * appending six random characters to the end of the provided `prefix`. Due to + * platform inconsistencies, avoid trailing `X` characters in `prefix`. Some + * platforms, notably the BSDs, can return more than six random characters, and + * replace trailing `X` characters in `prefix` with random characters. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * + * ```js + * import { mkdtemp } from 'node:fs/promises'; + * import { join } from 'node:path'; + * import { tmpdir } from 'node:os'; + * + * try { + * await mkdtemp(join(tmpdir(), 'foo-')); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * The `fsPromises.mkdtemp()` method will append the six randomly selected + * characters directly to the `prefix` string. For instance, given a directory `/tmp`, if the intention is to create a temporary directory _within_ `/tmp`, the `prefix` must end with a trailing + * platform-specific path separator + * (`import { sep } from 'node:path'`). + * @since v10.0.0 + * @return Fulfills with a string containing the file system path of the newly created temporary directory. + */ + function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: BufferEncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp( + prefix: string, + options?: ObjectEncodingOptions | BufferEncoding | null, + ): Promise; + /** + * The resulting Promise holds an async-disposable object whose `path` property + * holds the created directory path. When the object is disposed, the directory + * and its contents will be removed asynchronously if it still exists. If the + * directory cannot be deleted, disposal will throw an error. The object has an + * async `remove()` method which will perform the same task. + * + * Both this function and the disposal function on the resulting object are + * async, so it should be used with `await` + `await using` as in + * `await using dir = await fsPromises.mkdtempDisposable('prefix')`. + * + * + * + * For detailed information, see the documentation of `fsPromises.mkdtemp()`. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * @since v24.4.0 + */ + function mkdtempDisposable(prefix: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronously writes data to a file, replacing the file if it already exists. `data` can be a string, a buffer, an + * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. + * + * The `encoding` option is ignored if `data` is a buffer. + * + * If `options` is a string, then it specifies the encoding. + * + * The `mode` option only affects the newly created file. See `fs.open()` for more details. + * + * Any specified `FileHandle` has to support writing. + * + * It is unsafe to use `fsPromises.writeFile()` multiple times on the same file + * without waiting for the promise to be settled. + * + * Similarly to `fsPromises.readFile` \- `fsPromises.writeFile` is a convenience + * method that performs multiple `write` calls internally to write the buffer + * passed to it. For performance sensitive code consider using `fs.createWriteStream()` or `filehandle.createWriteStream()`. + * + * It is possible to use an `AbortSignal` to cancel an `fsPromises.writeFile()`. + * Cancelation is "best effort", and some amount of data is likely still + * to be written. + * + * ```js + * import { writeFile } from 'node:fs/promises'; + * import { Buffer } from 'node:buffer'; + * + * try { + * const controller = new AbortController(); + * const { signal } = controller; + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * const promise = writeFile('message.txt', data, { signal }); + * + * // Abort the request before the promise settles. + * controller.abort(); + * + * await promise; + * } catch (err) { + * // When a request is aborted - err is an AbortError + * console.error(err); + * } + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.writeFile` performs. + * @since v10.0.0 + * @param file filename or `FileHandle` + * @return Fulfills with `undefined` upon success. + */ + function writeFile( + file: PathLike | FileHandle, + data: + | string + | NodeJS.ArrayBufferView + | Iterable + | AsyncIterable + | Stream, + options?: + | (ObjectEncodingOptions & { + mode?: Mode | undefined; + flag?: OpenMode | undefined; + /** + * If all data is successfully written to the file, and `flush` + * is `true`, `filehandle.sync()` is used to flush the data. + * @default false + */ + flush?: boolean | undefined; + } & Abortable) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `mode` option only affects the newly created file. See `fs.open()` for more details. + * + * The `path` may be specified as a `FileHandle` that has been opened + * for appending (using `fsPromises.open()`). + * @since v10.0.0 + * @param path filename or {FileHandle} + * @return Fulfills with `undefined` upon success. + */ + function appendFile( + path: PathLike | FileHandle, + data: string | Uint8Array, + options?: (ObjectEncodingOptions & FlagAndOpenMode & { flush?: boolean | undefined }) | BufferEncoding | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * + * If no encoding is specified (using `options.encoding`), the data is returned + * as a `Buffer` object. Otherwise, the data will be a string. + * + * If `options` is a string, then it specifies the encoding. + * + * When the `path` is a directory, the behavior of `fsPromises.readFile()` is + * platform-specific. On macOS, Linux, and Windows, the promise will be rejected + * with an error. On FreeBSD, a representation of the directory's contents will be + * returned. + * + * An example of reading a `package.json` file located in the same directory of the + * running code: + * + * ```js + * import { readFile } from 'node:fs/promises'; + * try { + * const filePath = new URL('./package.json', import.meta.url); + * const contents = await readFile(filePath, { encoding: 'utf8' }); + * console.log(contents); + * } catch (err) { + * console.error(err.message); + * } + * ``` + * + * It is possible to abort an ongoing `readFile` using an `AbortSignal`. If a + * request is aborted the promise returned is rejected with an `AbortError`: + * + * ```js + * import { readFile } from 'node:fs/promises'; + * + * try { + * const controller = new AbortController(); + * const { signal } = controller; + * const promise = readFile(fileName, { signal }); + * + * // Abort the request before the promise settles. + * controller.abort(); + * + * await promise; + * } catch (err) { + * // When a request is aborted - err is an AbortError + * console.error(err); + * } + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.readFile` performs. + * + * Any specified `FileHandle` has to support reading. + * @since v10.0.0 + * @param path filename or `FileHandle` + * @return Fulfills with the contents of the file. + */ + function readFile( + path: PathLike | FileHandle, + options?: + | ({ + encoding?: null | undefined; + flag?: OpenMode | undefined; + } & Abortable) + | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | FileHandle, + options: + | ({ + encoding: BufferEncoding; + flag?: OpenMode | undefined; + } & Abortable) + | BufferEncoding, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | FileHandle, + options?: + | ( + & ObjectEncodingOptions + & Abortable + & { + flag?: OpenMode | undefined; + } + ) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronously open a directory for iterative scanning. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for more detail. + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * + * Example using async iteration: + * + * ```js + * import { opendir } from 'node:fs/promises'; + * + * try { + * const dir = await opendir('./'); + * for await (const dirent of dir) + * console.log(dirent.name); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * When using the async iterator, the `fs.Dir` object will be automatically + * closed after the iterator exits. + * @since v12.12.0 + * @return Fulfills with an {fs.Dir}. + */ + function opendir(path: PathLike, options?: OpenDirOptions): Promise; + interface WatchOptions extends _WatchOptions { + maxQueue?: number | undefined; + overflow?: "ignore" | "throw" | undefined; + } + interface WatchOptionsWithBufferEncoding extends WatchOptions { + encoding: "buffer"; + } + interface WatchOptionsWithStringEncoding extends WatchOptions { + encoding?: BufferEncoding | undefined; + } + /** + * Returns an async iterator that watches for changes on `filename`, where `filename`is either a file or a directory. + * + * ```js + * import { watch } from 'node:fs/promises'; + * + * const ac = new AbortController(); + * const { signal } = ac; + * setTimeout(() => ac.abort(), 10000); + * + * (async () => { + * try { + * const watcher = watch(__filename, { signal }); + * for await (const event of watcher) + * console.log(event); + * } catch (err) { + * if (err.name === 'AbortError') + * return; + * throw err; + * } + * })(); + * ``` + * + * On most platforms, `'rename'` is emitted whenever a filename appears or + * disappears in the directory. + * + * All the `caveats` for `fs.watch()` also apply to `fsPromises.watch()`. + * @since v15.9.0, v14.18.0 + * @return of objects with the properties: + */ + function watch( + filename: PathLike, + options?: WatchOptionsWithStringEncoding | BufferEncoding, + ): NodeJS.AsyncIterator>; + function watch( + filename: PathLike, + options: WatchOptionsWithBufferEncoding | "buffer", + ): NodeJS.AsyncIterator>; + function watch( + filename: PathLike, + options: WatchOptions | BufferEncoding | "buffer", + ): NodeJS.AsyncIterator>; + /** + * Asynchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + * @return Fulfills with `undefined` upon success. + */ + function cp(source: string | URL, destination: string | URL, opts?: CopyOptions): Promise; + /** + * ```js + * import { glob } from 'node:fs/promises'; + * + * for await (const entry of glob('*.js')) + * console.log(entry); + * ``` + * @since v22.0.0 + * @returns An AsyncIterator that yields the paths of files + * that match the pattern. + */ + function glob(pattern: string | readonly string[]): NodeJS.AsyncIterator; + function glob( + pattern: string | readonly string[], + options: GlobOptionsWithFileTypes, + ): NodeJS.AsyncIterator; + function glob( + pattern: string | readonly string[], + options: GlobOptionsWithoutFileTypes, + ): NodeJS.AsyncIterator; + function glob( + pattern: string | readonly string[], + options: GlobOptions, + ): NodeJS.AsyncIterator; +} +declare module "fs/promises" { + export * from "node:fs/promises"; +} diff --git a/backend/node_modules/@types/node/globals.d.ts b/backend/node_modules/@types/node/globals.d.ts new file mode 100644 index 0000000..36e7f90 --- /dev/null +++ b/backend/node_modules/@types/node/globals.d.ts @@ -0,0 +1,150 @@ +declare var global: typeof globalThis; + +declare var process: NodeJS.Process; + +interface ErrorConstructor { + /** + * Creates a `.stack` property on `targetObject`, which when accessed returns + * a string representing the location in the code at which + * `Error.captureStackTrace()` was called. + * + * ```js + * const myObject = {}; + * Error.captureStackTrace(myObject); + * myObject.stack; // Similar to `new Error().stack` + * ``` + * + * The first line of the trace will be prefixed with + * `${myObject.name}: ${myObject.message}`. + * + * The optional `constructorOpt` argument accepts a function. If given, all frames + * above `constructorOpt`, including `constructorOpt`, will be omitted from the + * generated stack trace. + * + * The `constructorOpt` argument is useful for hiding implementation + * details of error generation from the user. For instance: + * + * ```js + * function a() { + * b(); + * } + * + * function b() { + * c(); + * } + * + * function c() { + * // Create an error without stack trace to avoid calculating the stack trace twice. + * const { stackTraceLimit } = Error; + * Error.stackTraceLimit = 0; + * const error = new Error(); + * Error.stackTraceLimit = stackTraceLimit; + * + * // Capture the stack trace above function b + * Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace + * throw error; + * } + * + * a(); + * ``` + */ + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + /** + * @see https://v8.dev/docs/stack-trace-api#customizing-stack-traces + */ + prepareStackTrace(err: Error, stackTraces: NodeJS.CallSite[]): any; + /** + * The `Error.stackTraceLimit` property specifies the number of stack frames + * collected by a stack trace (whether generated by `new Error().stack` or + * `Error.captureStackTrace(obj)`). + * + * The default value is `10` but may be set to any valid JavaScript number. Changes + * will affect any stack trace captured _after_ the value has been changed. + * + * If set to a non-number value, or set to a negative number, stack traces will + * not capture any frames. + */ + stackTraceLimit: number; +} + +/** + * Enable this API with the `--expose-gc` CLI flag. + */ +declare var gc: NodeJS.GCFunction | undefined; + +declare namespace NodeJS { + interface CallSite { + getColumnNumber(): number | null; + getEnclosingColumnNumber(): number | null; + getEnclosingLineNumber(): number | null; + getEvalOrigin(): string | undefined; + getFileName(): string | null; + getFunction(): Function | undefined; + getFunctionName(): string | null; + getLineNumber(): number | null; + getMethodName(): string | null; + getPosition(): number; + getPromiseIndex(): number | null; + getScriptHash(): string; + getScriptNameOrSourceURL(): string | null; + getThis(): unknown; + getTypeName(): string | null; + isAsync(): boolean; + isConstructor(): boolean; + isEval(): boolean; + isNative(): boolean; + isPromiseAll(): boolean; + isToplevel(): boolean; + } + + interface ErrnoException extends Error { + errno?: number | undefined; + code?: string | undefined; + path?: string | undefined; + syscall?: string | undefined; + } + + interface RefCounted { + ref(): this; + unref(): this; + } + + interface Dict { + [key: string]: T | undefined; + } + + interface ReadOnlyDict { + readonly [key: string]: T | undefined; + } + + type PartialOptions = { [K in keyof T]?: T[K] | undefined }; + + interface GCFunction { + (minor?: boolean): void; + (options: NodeJS.GCOptions & { execution: "async" }): Promise; + (options: NodeJS.GCOptions): void; + } + + interface GCOptions { + execution?: "sync" | "async" | undefined; + flavor?: "regular" | "last-resort" | undefined; + type?: "major-snapshot" | "major" | "minor" | undefined; + filename?: string | undefined; + } + + /** An iterable iterator returned by the Node.js API. */ + interface Iterator extends IteratorObject { + [Symbol.iterator](): NodeJS.Iterator; + } + + /** An async iterable iterator returned by the Node.js API. */ + interface AsyncIterator extends AsyncIteratorObject { + [Symbol.asyncIterator](): NodeJS.AsyncIterator; + } + + /** The [`BufferSource`](https://webidl.spec.whatwg.org/#BufferSource) type from the Web IDL specification. */ + type BufferSource = NonSharedArrayBufferView | ArrayBuffer; + + /** The [`AllowSharedBufferSource`](https://webidl.spec.whatwg.org/#AllowSharedBufferSource) type from the Web IDL specification. */ + type AllowSharedBufferSource = ArrayBufferView | ArrayBufferLike; +} diff --git a/backend/node_modules/@types/node/globals.typedarray.d.ts b/backend/node_modules/@types/node/globals.typedarray.d.ts new file mode 100644 index 0000000..e69dd0c --- /dev/null +++ b/backend/node_modules/@types/node/globals.typedarray.d.ts @@ -0,0 +1,101 @@ +export {}; // Make this a module + +declare global { + namespace NodeJS { + type TypedArray = + | Uint8Array + | Uint8ClampedArray + | Uint16Array + | Uint32Array + | Int8Array + | Int16Array + | Int32Array + | BigUint64Array + | BigInt64Array + | Float16Array + | Float32Array + | Float64Array; + type ArrayBufferView = + | TypedArray + | DataView; + + // The following aliases are required to allow use of non-shared ArrayBufferViews in @types/node + // while maintaining compatibility with TS <=5.6. + // TODO: remove once @types/node no longer supports TS 5.6, and replace with native types. + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedUint8Array = Uint8Array; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedUint8ClampedArray = Uint8ClampedArray; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedUint16Array = Uint16Array; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedUint32Array = Uint32Array; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedInt8Array = Int8Array; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedInt16Array = Int16Array; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedInt32Array = Int32Array; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedBigUint64Array = BigUint64Array; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedBigInt64Array = BigInt64Array; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedFloat16Array = Float16Array; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedFloat32Array = Float32Array; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedFloat64Array = Float64Array; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedDataView = DataView; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedTypedArray = TypedArray; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedArrayBufferView = ArrayBufferView; + } +} diff --git a/backend/node_modules/@types/node/http.d.ts b/backend/node_modules/@types/node/http.d.ts new file mode 100644 index 0000000..44444d3 --- /dev/null +++ b/backend/node_modules/@types/node/http.d.ts @@ -0,0 +1,2143 @@ +/** + * To use the HTTP server and client one must import the `node:http` module. + * + * The HTTP interfaces in Node.js are designed to support many features + * of the protocol which have been traditionally difficult to use. + * In particular, large, possibly chunk-encoded, messages. The interface is + * careful to never buffer entire requests or responses, so the + * user is able to stream data. + * + * HTTP message headers are represented by an object like this: + * + * ```json + * { "content-length": "123", + * "content-type": "text/plain", + * "connection": "keep-alive", + * "host": "example.com", + * "accept": "*" } + * ``` + * + * Keys are lowercased. Values are not modified. + * + * In order to support the full spectrum of possible HTTP applications, the Node.js + * HTTP API is very low-level. It deals with stream handling and message + * parsing only. It parses a message into headers and body but it does not + * parse the actual headers or the body. + * + * See `message.headers` for details on how duplicate headers are handled. + * + * The raw headers as they were received are retained in the `rawHeaders` property, which is an array of `[key, value, key2, value2, ...]`. For + * example, the previous message header object might have a `rawHeaders` list like the following: + * + * ```js + * [ 'ConTent-Length', '123456', + * 'content-LENGTH', '123', + * 'content-type', 'text/plain', + * 'CONNECTION', 'keep-alive', + * 'Host', 'example.com', + * 'accepT', '*' ] + * ``` + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/http.js) + */ +declare module "node:http" { + import { NonSharedBuffer } from "node:buffer"; + import { LookupOptions } from "node:dns"; + import { EventEmitter } from "node:events"; + import * as net from "node:net"; + import * as stream from "node:stream"; + import { URL } from "node:url"; + // incoming headers will never contain number + interface IncomingHttpHeaders extends NodeJS.Dict { + accept?: string | undefined; + "accept-encoding"?: string | undefined; + "accept-language"?: string | undefined; + "accept-patch"?: string | undefined; + "accept-ranges"?: string | undefined; + "access-control-allow-credentials"?: string | undefined; + "access-control-allow-headers"?: string | undefined; + "access-control-allow-methods"?: string | undefined; + "access-control-allow-origin"?: string | undefined; + "access-control-expose-headers"?: string | undefined; + "access-control-max-age"?: string | undefined; + "access-control-request-headers"?: string | undefined; + "access-control-request-method"?: string | undefined; + age?: string | undefined; + allow?: string | undefined; + "alt-svc"?: string | undefined; + authorization?: string | undefined; + "cache-control"?: string | undefined; + connection?: string | undefined; + "content-disposition"?: string | undefined; + "content-encoding"?: string | undefined; + "content-language"?: string | undefined; + "content-length"?: string | undefined; + "content-location"?: string | undefined; + "content-range"?: string | undefined; + "content-type"?: string | undefined; + cookie?: string | undefined; + date?: string | undefined; + etag?: string | undefined; + expect?: string | undefined; + expires?: string | undefined; + forwarded?: string | undefined; + from?: string | undefined; + host?: string | undefined; + "if-match"?: string | undefined; + "if-modified-since"?: string | undefined; + "if-none-match"?: string | undefined; + "if-unmodified-since"?: string | undefined; + "last-modified"?: string | undefined; + location?: string | undefined; + origin?: string | undefined; + pragma?: string | undefined; + "proxy-authenticate"?: string | undefined; + "proxy-authorization"?: string | undefined; + "public-key-pins"?: string | undefined; + range?: string | undefined; + referer?: string | undefined; + "retry-after"?: string | undefined; + "sec-fetch-site"?: string | undefined; + "sec-fetch-mode"?: string | undefined; + "sec-fetch-user"?: string | undefined; + "sec-fetch-dest"?: string | undefined; + "sec-websocket-accept"?: string | undefined; + "sec-websocket-extensions"?: string | undefined; + "sec-websocket-key"?: string | undefined; + "sec-websocket-protocol"?: string | undefined; + "sec-websocket-version"?: string | undefined; + "set-cookie"?: string[] | undefined; + "strict-transport-security"?: string | undefined; + tk?: string | undefined; + trailer?: string | undefined; + "transfer-encoding"?: string | undefined; + upgrade?: string | undefined; + "user-agent"?: string | undefined; + vary?: string | undefined; + via?: string | undefined; + warning?: string | undefined; + "www-authenticate"?: string | undefined; + } + // outgoing headers allows numbers (as they are converted internally to strings) + type OutgoingHttpHeader = number | string | string[]; + interface OutgoingHttpHeaders extends NodeJS.Dict { + accept?: string | string[] | undefined; + "accept-charset"?: string | string[] | undefined; + "accept-encoding"?: string | string[] | undefined; + "accept-language"?: string | string[] | undefined; + "accept-ranges"?: string | undefined; + "access-control-allow-credentials"?: string | undefined; + "access-control-allow-headers"?: string | undefined; + "access-control-allow-methods"?: string | undefined; + "access-control-allow-origin"?: string | undefined; + "access-control-expose-headers"?: string | undefined; + "access-control-max-age"?: string | undefined; + "access-control-request-headers"?: string | undefined; + "access-control-request-method"?: string | undefined; + age?: string | undefined; + allow?: string | undefined; + authorization?: string | undefined; + "cache-control"?: string | undefined; + "cdn-cache-control"?: string | undefined; + connection?: string | string[] | undefined; + "content-disposition"?: string | undefined; + "content-encoding"?: string | undefined; + "content-language"?: string | undefined; + "content-length"?: string | number | undefined; + "content-location"?: string | undefined; + "content-range"?: string | undefined; + "content-security-policy"?: string | undefined; + "content-security-policy-report-only"?: string | undefined; + "content-type"?: string | undefined; + cookie?: string | string[] | undefined; + dav?: string | string[] | undefined; + dnt?: string | undefined; + date?: string | undefined; + etag?: string | undefined; + expect?: string | undefined; + expires?: string | undefined; + forwarded?: string | undefined; + from?: string | undefined; + host?: string | undefined; + "if-match"?: string | undefined; + "if-modified-since"?: string | undefined; + "if-none-match"?: string | undefined; + "if-range"?: string | undefined; + "if-unmodified-since"?: string | undefined; + "last-modified"?: string | undefined; + link?: string | string[] | undefined; + location?: string | undefined; + "max-forwards"?: string | undefined; + origin?: string | undefined; + pragma?: string | string[] | undefined; + "proxy-authenticate"?: string | string[] | undefined; + "proxy-authorization"?: string | undefined; + "public-key-pins"?: string | undefined; + "public-key-pins-report-only"?: string | undefined; + range?: string | undefined; + referer?: string | undefined; + "referrer-policy"?: string | undefined; + refresh?: string | undefined; + "retry-after"?: string | undefined; + "sec-websocket-accept"?: string | undefined; + "sec-websocket-extensions"?: string | string[] | undefined; + "sec-websocket-key"?: string | undefined; + "sec-websocket-protocol"?: string | string[] | undefined; + "sec-websocket-version"?: string | undefined; + server?: string | undefined; + "set-cookie"?: string | string[] | undefined; + "strict-transport-security"?: string | undefined; + te?: string | undefined; + trailer?: string | undefined; + "transfer-encoding"?: string | undefined; + "user-agent"?: string | undefined; + upgrade?: string | undefined; + "upgrade-insecure-requests"?: string | undefined; + vary?: string | undefined; + via?: string | string[] | undefined; + warning?: string | undefined; + "www-authenticate"?: string | string[] | undefined; + "x-content-type-options"?: string | undefined; + "x-dns-prefetch-control"?: string | undefined; + "x-frame-options"?: string | undefined; + "x-xss-protection"?: string | undefined; + } + interface ClientRequestArgs extends Pick { + _defaultAgent?: Agent | undefined; + agent?: Agent | boolean | undefined; + auth?: string | null | undefined; + createConnection?: + | (( + options: ClientRequestArgs, + oncreate: (err: Error | null, socket: stream.Duplex) => void, + ) => stream.Duplex | null | undefined) + | undefined; + defaultPort?: number | string | undefined; + family?: number | undefined; + headers?: OutgoingHttpHeaders | readonly string[] | undefined; + host?: string | null | undefined; + hostname?: string | null | undefined; + insecureHTTPParser?: boolean | undefined; + localAddress?: string | undefined; + localPort?: number | undefined; + lookup?: net.LookupFunction | undefined; + /** + * @default 16384 + */ + maxHeaderSize?: number | undefined; + method?: string | undefined; + path?: string | null | undefined; + port?: number | string | null | undefined; + protocol?: string | null | undefined; + setDefaultHeaders?: boolean | undefined; + setHost?: boolean | undefined; + signal?: AbortSignal | undefined; + socketPath?: string | undefined; + timeout?: number | undefined; + uniqueHeaders?: Array | undefined; + joinDuplicateHeaders?: boolean | undefined; + } + interface ServerOptions< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + > { + /** + * Specifies the `IncomingMessage` class to be used. Useful for extending the original `IncomingMessage`. + */ + IncomingMessage?: Request | undefined; + /** + * Specifies the `ServerResponse` class to be used. Useful for extending the original `ServerResponse`. + */ + ServerResponse?: Response | undefined; + /** + * Sets the timeout value in milliseconds for receiving the entire request from the client. + * @see Server.requestTimeout for more information. + * @default 300000 + * @since v18.0.0 + */ + requestTimeout?: number | undefined; + /** + * It joins the field line values of multiple headers in a request with `, ` instead of discarding the duplicates. + * @default false + * @since v18.14.0 + */ + joinDuplicateHeaders?: boolean | undefined; + /** + * The number of milliseconds of inactivity a server needs to wait for additional incoming data, + * after it has finished writing the last response, before a socket will be destroyed. + * @see Server.keepAliveTimeout for more information. + * @default 5000 + * @since v18.0.0 + */ + keepAliveTimeout?: number | undefined; + /** + * An additional buffer time added to the + * `server.keepAliveTimeout` to extend the internal socket timeout. + * @since 24.6.0 + * @default 1000 + */ + keepAliveTimeoutBuffer?: number | undefined; + /** + * Sets the interval value in milliseconds to check for request and headers timeout in incomplete requests. + * @default 30000 + */ + connectionsCheckingInterval?: number | undefined; + /** + * Sets the timeout value in milliseconds for receiving the complete HTTP headers from the client. + * See {@link Server.headersTimeout} for more information. + * @default 60000 + * @since 18.0.0 + */ + headersTimeout?: number | undefined; + /** + * Optionally overrides all `socket`s' `readableHighWaterMark` and `writableHighWaterMark`. + * This affects `highWaterMark` property of both `IncomingMessage` and `ServerResponse`. + * Default: @see stream.getDefaultHighWaterMark(). + * @since v20.1.0 + */ + highWaterMark?: number | undefined; + /** + * Use an insecure HTTP parser that accepts invalid HTTP headers when `true`. + * Using the insecure parser should be avoided. + * See --insecure-http-parser for more information. + * @default false + */ + insecureHTTPParser?: boolean | undefined; + /** + * Optionally overrides the value of `--max-http-header-size` for requests received by + * this server, i.e. the maximum length of request headers in bytes. + * @default 16384 + * @since v13.3.0 + */ + maxHeaderSize?: number | undefined; + /** + * If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. + * @default true + * @since v16.5.0 + */ + noDelay?: boolean | undefined; + /** + * If set to `true`, it forces the server to respond with a 400 (Bad Request) status code + * to any HTTP/1.1 request message that lacks a Host header (as mandated by the specification). + * @default true + * @since 20.0.0 + */ + requireHostHeader?: boolean | undefined; + /** + * If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, + * similarly on what is done in `socket.setKeepAlive([enable][, initialDelay])`. + * @default false + * @since v16.5.0 + */ + keepAlive?: boolean | undefined; + /** + * If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. + * @default 0 + * @since v16.5.0 + */ + keepAliveInitialDelay?: number | undefined; + /** + * A list of response headers that should be sent only once. + * If the header's value is an array, the items will be joined using `; `. + */ + uniqueHeaders?: Array | undefined; + /** + * A callback which receives an + * incoming request and returns a boolean, to control which upgrade attempts + * should be accepted. Accepted upgrades will fire an `'upgrade'` event (or + * their sockets will be destroyed, if no listener is registered) while + * rejected upgrades will fire a `'request'` event like any non-upgrade + * request. + * @since v24.9.0 + * @default () => server.listenerCount('upgrade') > 0 + */ + shouldUpgradeCallback?: ((request: InstanceType) => boolean) | undefined; + /** + * If set to `true`, an error is thrown when writing to an HTTP response which does not have a body. + * @default false + * @since v18.17.0, v20.2.0 + */ + rejectNonStandardBodyWrites?: boolean | undefined; + } + type RequestListener< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + > = (request: InstanceType, response: InstanceType & { req: InstanceType }) => void; + interface ServerEventMap< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + > extends net.ServerEventMap { + "checkContinue": Parameters>; + "checkExpectation": Parameters>; + "clientError": [exception: Error, socket: stream.Duplex]; + "connect": [request: InstanceType, socket: stream.Duplex, head: NonSharedBuffer]; + "connection": [socket: net.Socket]; + "dropRequest": [request: InstanceType, socket: stream.Duplex]; + "request": Parameters>; + "upgrade": [req: InstanceType, socket: stream.Duplex, head: NonSharedBuffer]; + } + /** + * @since v0.1.17 + */ + class Server< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + > extends net.Server { + constructor(requestListener?: RequestListener); + constructor(options: ServerOptions, requestListener?: RequestListener); + /** + * Sets the timeout value for sockets, and emits a `'timeout'` event on + * the Server object, passing the socket as an argument, if a timeout + * occurs. + * + * If there is a `'timeout'` event listener on the Server object, then it + * will be called with the timed-out socket as an argument. + * + * By default, the Server does not timeout sockets. However, if a callback + * is assigned to the Server's `'timeout'` event, timeouts must be handled + * explicitly. + * @since v0.9.12 + * @param [msecs=0 (no timeout)] + */ + setTimeout(msecs?: number, callback?: (socket: net.Socket) => void): this; + setTimeout(callback: (socket: net.Socket) => void): this; + /** + * Limits maximum incoming headers count. If set to 0, no limit will be applied. + * @since v0.7.0 + */ + maxHeadersCount: number | null; + /** + * The maximum number of requests socket can handle + * before closing keep alive connection. + * + * A value of `0` will disable the limit. + * + * When the limit is reached it will set the `Connection` header value to `close`, + * but will not actually close the connection, subsequent requests sent + * after the limit is reached will get `503 Service Unavailable` as a response. + * @since v16.10.0 + */ + maxRequestsPerSocket: number | null; + /** + * The number of milliseconds of inactivity before a socket is presumed + * to have timed out. + * + * A value of `0` will disable the timeout behavior on incoming connections. + * + * The socket timeout logic is set up on connection, so changing this + * value only affects new connections to the server, not any existing connections. + * @since v0.9.12 + */ + timeout: number; + /** + * Limit the amount of time the parser will wait to receive the complete HTTP + * headers. + * + * If the timeout expires, the server responds with status 408 without + * forwarding the request to the request listener and then closes the connection. + * + * It must be set to a non-zero value (e.g. 120 seconds) to protect against + * potential Denial-of-Service attacks in case the server is deployed without a + * reverse proxy in front. + * @since v11.3.0, v10.14.0 + */ + headersTimeout: number; + /** + * The number of milliseconds of inactivity a server needs to wait for additional + * incoming data, after it has finished writing the last response, before a socket + * will be destroyed. + * + * This timeout value is combined with the + * `server.keepAliveTimeoutBuffer` option to determine the actual socket + * timeout, calculated as: + * socketTimeout = keepAliveTimeout + keepAliveTimeoutBuffer + * If the server receives new data before the keep-alive timeout has fired, it + * will reset the regular inactivity timeout, i.e., `server.timeout`. + * + * A value of `0` will disable the keep-alive timeout behavior on incoming + * connections. + * A value of `0` makes the HTTP server behave similarly to Node.js versions prior + * to 8.0.0, which did not have a keep-alive timeout. + * + * The socket timeout logic is set up on connection, so changing this value only + * affects new connections to the server, not any existing connections. + * @since v8.0.0 + */ + keepAliveTimeout: number; + /** + * An additional buffer time added to the + * `server.keepAliveTimeout` to extend the internal socket timeout. + * + * This buffer helps reduce connection reset (`ECONNRESET`) errors by increasing + * the socket timeout slightly beyond the advertised keep-alive timeout. + * + * This option applies only to new incoming connections. + * @since v24.6.0 + * @default 1000 + */ + keepAliveTimeoutBuffer: number; + /** + * Sets the timeout value in milliseconds for receiving the entire request from + * the client. + * + * If the timeout expires, the server responds with status 408 without + * forwarding the request to the request listener and then closes the connection. + * + * It must be set to a non-zero value (e.g. 120 seconds) to protect against + * potential Denial-of-Service attacks in case the server is deployed without a + * reverse proxy in front. + * @since v14.11.0 + */ + requestTimeout: number; + /** + * Closes all connections connected to this server. + * @since v18.2.0 + */ + closeAllConnections(): void; + /** + * Closes all connections connected to this server which are not sending a request + * or waiting for a response. + * @since v18.2.0 + */ + closeIdleConnections(): void; + // #region InternalEventEmitter + addListener( + eventName: E, + listener: (...args: ServerEventMap[E]) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: ServerEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: ServerEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners( + eventName: E, + ): ((...args: ServerEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off( + eventName: E, + listener: (...args: ServerEventMap[E]) => void, + ): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on( + eventName: E, + listener: (...args: ServerEventMap[E]) => void, + ): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: (...args: ServerEventMap[E]) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: ServerEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: ServerEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners( + eventName: E, + ): ((...args: ServerEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: ServerEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + interface OutgoingMessageEventMap extends stream.WritableEventMap { + "prefinish": []; + } + /** + * This class serves as the parent class of {@link ClientRequest} and {@link ServerResponse}. It is an abstract outgoing message from + * the perspective of the participants of an HTTP transaction. + * @since v0.1.17 + */ + class OutgoingMessage extends stream.Writable { + constructor(); + readonly req: Request; + chunkedEncoding: boolean; + shouldKeepAlive: boolean; + useChunkedEncodingByDefault: boolean; + sendDate: boolean; + /** + * @deprecated Use `writableEnded` instead. + */ + finished: boolean; + /** + * Read-only. `true` if the headers were sent, otherwise `false`. + * @since v0.9.3 + */ + readonly headersSent: boolean; + /** + * Alias of `outgoingMessage.socket`. + * @since v0.3.0 + * @deprecated Since v15.12.0,v14.17.1 - Use `socket` instead. + */ + readonly connection: net.Socket | null; + /** + * Reference to the underlying socket. Usually, users will not want to access + * this property. + * + * After calling `outgoingMessage.end()`, this property will be nulled. + * @since v0.3.0 + */ + readonly socket: net.Socket | null; + /** + * Once a socket is associated with the message and is connected, `socket.setTimeout()` will be called with `msecs` as the first parameter. + * @since v0.9.12 + * @param callback Optional function to be called when a timeout occurs. Same as binding to the `timeout` event. + */ + setTimeout(msecs: number, callback?: () => void): this; + /** + * Sets a single header value. If the header already exists in the to-be-sent + * headers, its value will be replaced. Use an array of strings to send multiple + * headers with the same name. + * @since v0.4.0 + * @param name Header name + * @param value Header value + */ + setHeader(name: string, value: number | string | readonly string[]): this; + /** + * Sets multiple header values for implicit headers. headers must be an instance of + * `Headers` or `Map`, if a header already exists in the to-be-sent headers, its + * value will be replaced. + * + * ```js + * const headers = new Headers({ foo: 'bar' }); + * outgoingMessage.setHeaders(headers); + * ``` + * + * or + * + * ```js + * const headers = new Map([['foo', 'bar']]); + * outgoingMessage.setHeaders(headers); + * ``` + * + * When headers have been set with `outgoingMessage.setHeaders()`, they will be + * merged with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http.createServer((req, res) => { + * const headers = new Headers({ 'Content-Type': 'text/html' }); + * res.setHeaders(headers); + * res.writeHead(200, { 'Content-Type': 'text/plain' }); + * res.end('ok'); + * }); + * ``` + * + * @since v19.6.0, v18.15.0 + * @param name Header name + * @param value Header value + */ + setHeaders(headers: Headers | Map): this; + /** + * Append a single header value to the header object. + * + * If the value is an array, this is equivalent to calling this method multiple + * times. + * + * If there were no previous values for the header, this is equivalent to calling `outgoingMessage.setHeader(name, value)`. + * + * Depending of the value of `options.uniqueHeaders` when the client request or the + * server were created, this will end up in the header being sent multiple times or + * a single time with values joined using `; `. + * @since v18.3.0, v16.17.0 + * @param name Header name + * @param value Header value + */ + appendHeader(name: string, value: string | readonly string[]): this; + /** + * Gets the value of the HTTP header with the given name. If that header is not + * set, the returned value will be `undefined`. + * @since v0.4.0 + * @param name Name of header + */ + getHeader(name: string): number | string | string[] | undefined; + /** + * Returns a shallow copy of the current outgoing headers. Since a shallow + * copy is used, array values may be mutated without additional calls to + * various header-related HTTP module methods. The keys of the returned + * object are the header names and the values are the respective header + * values. All header names are lowercase. + * + * The object returned by the `outgoingMessage.getHeaders()` method does + * not prototypically inherit from the JavaScript `Object`. This means that + * typical `Object` methods such as `obj.toString()`, `obj.hasOwnProperty()`, + * and others are not defined and will not work. + * + * ```js + * outgoingMessage.setHeader('Foo', 'bar'); + * outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headers = outgoingMessage.getHeaders(); + * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } + * ``` + * @since v7.7.0 + */ + getHeaders(): OutgoingHttpHeaders; + /** + * Returns an array containing the unique names of the current outgoing headers. + * All names are lowercase. + * @since v7.7.0 + */ + getHeaderNames(): string[]; + /** + * Returns `true` if the header identified by `name` is currently set in the + * outgoing headers. The header name is case-insensitive. + * + * ```js + * const hasContentType = outgoingMessage.hasHeader('content-type'); + * ``` + * @since v7.7.0 + */ + hasHeader(name: string): boolean; + /** + * Removes a header that is queued for implicit sending. + * + * ```js + * outgoingMessage.removeHeader('Content-Encoding'); + * ``` + * @since v0.4.0 + * @param name Header name + */ + removeHeader(name: string): void; + /** + * Adds HTTP trailers (headers but at the end of the message) to the message. + * + * Trailers will **only** be emitted if the message is chunked encoded. If not, + * the trailers will be silently discarded. + * + * HTTP requires the `Trailer` header to be sent to emit trailers, + * with a list of header field names in its value, e.g. + * + * ```js + * message.writeHead(200, { 'Content-Type': 'text/plain', + * 'Trailer': 'Content-MD5' }); + * message.write(fileData); + * message.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' }); + * message.end(); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v0.3.0 + */ + addTrailers(headers: OutgoingHttpHeaders | ReadonlyArray<[string, string]>): void; + /** + * Flushes the message headers. + * + * For efficiency reason, Node.js normally buffers the message headers + * until `outgoingMessage.end()` is called or the first chunk of message data + * is written. It then tries to pack the headers and data into a single TCP + * packet. + * + * It is usually desired (it saves a TCP round-trip), but not when the first + * data is not sent until possibly much later. `outgoingMessage.flushHeaders()` bypasses the optimization and kickstarts the message. + * @since v1.6.0 + */ + flushHeaders(): void; + // #region InternalEventEmitter + addListener( + eventName: E, + listener: (...args: OutgoingMessageEventMap[E]) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: OutgoingMessageEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: OutgoingMessageEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners( + eventName: E, + ): ((...args: OutgoingMessageEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off( + eventName: E, + listener: (...args: OutgoingMessageEventMap[E]) => void, + ): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on( + eventName: E, + listener: (...args: OutgoingMessageEventMap[E]) => void, + ): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: (...args: OutgoingMessageEventMap[E]) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: OutgoingMessageEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: OutgoingMessageEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners( + eventName: E, + ): ((...args: OutgoingMessageEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: OutgoingMessageEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + /** + * This object is created internally by an HTTP server, not by the user. It is + * passed as the second parameter to the `'request'` event. + * @since v0.1.17 + */ + class ServerResponse extends OutgoingMessage { + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status code that will be sent to the client when + * the headers get flushed. + * + * ```js + * response.statusCode = 404; + * ``` + * + * After response header was sent to the client, this property indicates the + * status code which was sent out. + * @since v0.4.0 + */ + statusCode: number; + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status message that will be sent to the client when + * the headers get flushed. If this is left as `undefined` then the standard + * message for the status code will be used. + * + * ```js + * response.statusMessage = 'Not found'; + * ``` + * + * After response header was sent to the client, this property indicates the + * status message which was sent out. + * @since v0.11.8 + */ + statusMessage: string; + /** + * If set to `true`, Node.js will check whether the `Content-Length` header value and the size of the body, in bytes, are equal. + * Mismatching the `Content-Length` header value will result + * in an `Error` being thrown, identified by `code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`. + * @since v18.10.0, v16.18.0 + */ + strictContentLength: boolean; + constructor(req: Request); + assignSocket(socket: net.Socket): void; + detachSocket(socket: net.Socket): void; + /** + * Sends an HTTP/1.1 100 Continue message to the client, indicating that + * the request body should be sent. See the `'checkContinue'` event on `Server`. + * @since v0.3.0 + */ + writeContinue(callback?: () => void): void; + /** + * Sends an HTTP/1.1 103 Early Hints message to the client with a Link header, + * indicating that the user agent can preload/preconnect the linked resources. + * The `hints` is an object containing the values of headers to be sent with + * early hints message. The optional `callback` argument will be called when + * the response message has been written. + * + * **Example** + * + * ```js + * const earlyHintsLink = '; rel=preload; as=style'; + * response.writeEarlyHints({ + * 'link': earlyHintsLink, + * }); + * + * const earlyHintsLinks = [ + * '; rel=preload; as=style', + * '; rel=preload; as=script', + * ]; + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * 'x-trace-id': 'id for diagnostics', + * }); + * + * const earlyHintsCallback = () => console.log('early hints message sent'); + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * }, earlyHintsCallback); + * ``` + * @since v18.11.0 + * @param hints An object containing the values of headers + * @param callback Will be called when the response message has been written + */ + writeEarlyHints(hints: Record, callback?: () => void): void; + /** + * Sends a response header to the request. The status code is a 3-digit HTTP + * status code, like `404`. The last argument, `headers`, are the response headers. + * Optionally one can give a human-readable `statusMessage` as the second + * argument. + * + * `headers` may be an `Array` where the keys and values are in the same list. + * It is _not_ a list of tuples. So, the even-numbered offsets are key values, + * and the odd-numbered offsets are the associated values. The array is in the same + * format as `request.rawHeaders`. + * + * Returns a reference to the `ServerResponse`, so that calls can be chained. + * + * ```js + * const body = 'hello world'; + * response + * .writeHead(200, { + * 'Content-Length': Buffer.byteLength(body), + * 'Content-Type': 'text/plain', + * }) + * .end(body); + * ``` + * + * This method must only be called once on a message and it must + * be called before `response.end()` is called. + * + * If `response.write()` or `response.end()` are called before calling + * this, the implicit/mutable headers will be calculated and call this function. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * If this method is called and `response.setHeader()` has not been called, + * it will directly write the supplied header values onto the network channel + * without caching internally, and the `response.getHeader()` on the header + * will not yield the expected result. If progressive population of headers is + * desired with potential future retrieval and modification, use `response.setHeader()` instead. + * + * ```js + * // Returns content-type = text/plain + * const server = http.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain' }); + * res.end('ok'); + * }); + * ``` + * + * `Content-Length` is read in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. Node.js + * will check whether `Content-Length` and the length of the body which has + * been transmitted are equal or not. + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a \[`Error`\]\[\] being thrown. + * @since v0.1.30 + */ + writeHead( + statusCode: number, + statusMessage?: string, + headers?: OutgoingHttpHeaders | OutgoingHttpHeader[], + ): this; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this; + /** + * Sends a HTTP/1.1 102 Processing message to the client, indicating that + * the request body should be sent. + * @since v10.0.0 + */ + writeProcessing(callback?: () => void): void; + } + interface InformationEvent { + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + statusCode: number; + statusMessage: string; + headers: IncomingHttpHeaders; + rawHeaders: string[]; + } + interface ClientRequestEventMap extends stream.WritableEventMap { + /** @deprecated Listen for the `'close'` event instead. */ + "abort": []; + "connect": [response: IncomingMessage, socket: net.Socket, head: NonSharedBuffer]; + "continue": []; + "information": [info: InformationEvent]; + "response": [response: IncomingMessage]; + "socket": [socket: net.Socket]; + "timeout": []; + "upgrade": [response: IncomingMessage, socket: net.Socket, head: NonSharedBuffer]; + } + /** + * This object is created internally and returned from {@link request}. It + * represents an _in-progress_ request whose header has already been queued. The + * header is still mutable using the `setHeader(name, value)`, `getHeader(name)`, `removeHeader(name)` API. The actual header will + * be sent along with the first data chunk or when calling `request.end()`. + * + * To get the response, add a listener for `'response'` to the request object. `'response'` will be emitted from the request object when the response + * headers have been received. The `'response'` event is executed with one + * argument which is an instance of {@link IncomingMessage}. + * + * During the `'response'` event, one can add listeners to the + * response object; particularly to listen for the `'data'` event. + * + * If no `'response'` handler is added, then the response will be + * entirely discarded. However, if a `'response'` event handler is added, + * then the data from the response object **must** be consumed, either by + * calling `response.read()` whenever there is a `'readable'` event, or + * by adding a `'data'` handler, or by calling the `.resume()` method. + * Until the data is consumed, the `'end'` event will not fire. Also, until + * the data is read it will consume memory that can eventually lead to a + * 'process out of memory' error. + * + * For backward compatibility, `res` will only emit `'error'` if there is an `'error'` listener registered. + * + * Set `Content-Length` header to limit the response body size. + * If `response.strictContentLength` is set to `true`, mismatching the `Content-Length` header value will result in an `Error` being thrown, + * identified by `code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`. + * + * `Content-Length` value should be in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. + * @since v0.1.17 + */ + class ClientRequest extends OutgoingMessage { + /** + * The `request.aborted` property will be `true` if the request has + * been aborted. + * @since v0.11.14 + * @deprecated Since v17.0.0, v16.12.0 - Check `destroyed` instead. + */ + aborted: boolean; + /** + * The request host. + * @since v14.5.0, v12.19.0 + */ + host: string; + /** + * The request protocol. + * @since v14.5.0, v12.19.0 + */ + protocol: string; + /** + * When sending request through a keep-alive enabled agent, the underlying socket + * might be reused. But if server closes connection at unfortunate time, client + * may run into a 'ECONNRESET' error. + * + * ```js + * import http from 'node:http'; + * + * // Server has a 5 seconds keep-alive timeout by default + * http + * .createServer((req, res) => { + * res.write('hello\n'); + * res.end(); + * }) + * .listen(3000); + * + * setInterval(() => { + * // Adapting a keep-alive agent + * http.get('http://localhost:3000', { agent }, (res) => { + * res.on('data', (data) => { + * // Do nothing + * }); + * }); + * }, 5000); // Sending request on 5s interval so it's easy to hit idle timeout + * ``` + * + * By marking a request whether it reused socket or not, we can do + * automatic error retry base on it. + * + * ```js + * import http from 'node:http'; + * const agent = new http.Agent({ keepAlive: true }); + * + * function retriableRequest() { + * const req = http + * .get('http://localhost:3000', { agent }, (res) => { + * // ... + * }) + * .on('error', (err) => { + * // Check if retry is needed + * if (req.reusedSocket && err.code === 'ECONNRESET') { + * retriableRequest(); + * } + * }); + * } + * + * retriableRequest(); + * ``` + * @since v13.0.0, v12.16.0 + */ + reusedSocket: boolean; + /** + * Limits maximum response headers count. If set to 0, no limit will be applied. + */ + maxHeadersCount: number; + constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); + /** + * The request method. + * @since v0.1.97 + */ + method: string; + /** + * The request path. + * @since v0.4.0 + */ + path: string; + /** + * Marks the request as aborting. Calling this will cause remaining data + * in the response to be dropped and the socket to be destroyed. + * @since v0.3.8 + * @deprecated Since v14.1.0,v13.14.0 - Use `destroy` instead. + */ + abort(): void; + onSocket(socket: net.Socket): void; + /** + * Once a socket is assigned to this request and is connected `socket.setTimeout()` will be called. + * @since v0.5.9 + * @param timeout Milliseconds before a request times out. + * @param callback Optional function to be called when a timeout occurs. Same as binding to the `'timeout'` event. + */ + setTimeout(timeout: number, callback?: () => void): this; + /** + * Once a socket is assigned to this request and is connected `socket.setNoDelay()` will be called. + * @since v0.5.9 + */ + setNoDelay(noDelay?: boolean): void; + /** + * Once a socket is assigned to this request and is connected `socket.setKeepAlive()` will be called. + * @since v0.5.9 + */ + setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + /** + * Returns an array containing the unique names of the current outgoing raw + * headers. Header names are returned with their exact casing being set. + * + * ```js + * request.setHeader('Foo', 'bar'); + * request.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headerNames = request.getRawHeaderNames(); + * // headerNames === ['Foo', 'Set-Cookie'] + * ``` + * @since v15.13.0, v14.17.0 + */ + getRawHeaderNames(): string[]; + // #region InternalEventEmitter + addListener( + eventName: E, + listener: (...args: ClientRequestEventMap[E]) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: ClientRequestEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: ClientRequestEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners(eventName: E): ((...args: ClientRequestEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off( + eventName: E, + listener: (...args: ClientRequestEventMap[E]) => void, + ): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on( + eventName: E, + listener: (...args: ClientRequestEventMap[E]) => void, + ): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: (...args: ClientRequestEventMap[E]) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: ClientRequestEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: ClientRequestEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners( + eventName: E, + ): ((...args: ClientRequestEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: ClientRequestEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + interface IncomingMessageEventMap extends stream.ReadableEventMap { + /** @deprecated Listen for `'close'` event instead. */ + "aborted": []; + } + /** + * An `IncomingMessage` object is created by {@link Server} or {@link ClientRequest} and passed as the first argument to the `'request'` and `'response'` event respectively. It may be used to + * access response + * status, headers, and data. + * + * Different from its `socket` value which is a subclass of `stream.Duplex`, the `IncomingMessage` itself extends `stream.Readable` and is created separately to + * parse and emit the incoming HTTP headers and payload, as the underlying socket + * may be reused multiple times in case of keep-alive. + * @since v0.1.17 + */ + class IncomingMessage extends stream.Readable { + constructor(socket: net.Socket); + /** + * The `message.aborted` property will be `true` if the request has + * been aborted. + * @since v10.1.0 + * @deprecated Since v17.0.0,v16.12.0 - Check `message.destroyed` from stream.Readable. + */ + aborted: boolean; + /** + * In case of server request, the HTTP version sent by the client. In the case of + * client response, the HTTP version of the connected-to server. + * Probably either `'1.1'` or `'1.0'`. + * + * Also `message.httpVersionMajor` is the first integer and `message.httpVersionMinor` is the second. + * @since v0.1.1 + */ + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + /** + * The `message.complete` property will be `true` if a complete HTTP message has + * been received and successfully parsed. + * + * This property is particularly useful as a means of determining if a client or + * server fully transmitted a message before a connection was terminated: + * + * ```js + * const req = http.request({ + * host: '127.0.0.1', + * port: 8080, + * method: 'POST', + * }, (res) => { + * res.resume(); + * res.on('end', () => { + * if (!res.complete) + * console.error( + * 'The connection was terminated while the message was still being sent'); + * }); + * }); + * ``` + * @since v0.3.0 + */ + complete: boolean; + /** + * Alias for `message.socket`. + * @since v0.1.90 + * @deprecated Since v16.0.0 - Use `socket`. + */ + connection: net.Socket; + /** + * The `net.Socket` object associated with the connection. + * + * With HTTPS support, use `request.socket.getPeerCertificate()` to obtain the + * client's authentication details. + * + * This property is guaranteed to be an instance of the `net.Socket` class, + * a subclass of `stream.Duplex`, unless the user specified a socket + * type other than `net.Socket` or internally nulled. + * @since v0.3.0 + */ + socket: net.Socket; + /** + * The request/response headers object. + * + * Key-value pairs of header names and values. Header names are lower-cased. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': 'curl/7.22.0', + * // host: '127.0.0.1:8000', + * // accept: '*' } + * console.log(request.headers); + * ``` + * + * Duplicates in raw headers are handled in the following ways, depending on the + * header name: + * + * * Duplicates of `age`, `authorization`, `content-length`, `content-type`, `etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`, `last-modified`, `location`, + * `max-forwards`, `proxy-authorization`, `referer`, `retry-after`, `server`, or `user-agent` are discarded. + * To allow duplicate values of the headers listed above to be joined, + * use the option `joinDuplicateHeaders` in {@link request} and {@link createServer}. See RFC 9110 Section 5.3 for more + * information. + * * `set-cookie` is always an array. Duplicates are added to the array. + * * For duplicate `cookie` headers, the values are joined together with `; `. + * * For all other headers, the values are joined together with `, `. + * @since v0.1.5 + */ + headers: IncomingHttpHeaders; + /** + * Similar to `message.headers`, but there is no join logic and the values are + * always arrays of strings, even for headers received just once. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': ['curl/7.22.0'], + * // host: ['127.0.0.1:8000'], + * // accept: ['*'] } + * console.log(request.headersDistinct); + * ``` + * @since v18.3.0, v16.17.0 + */ + headersDistinct: NodeJS.Dict; + /** + * The raw request/response headers list exactly as they were received. + * + * The keys and values are in the same list. It is _not_ a + * list of tuples. So, the even-numbered offsets are key values, and the + * odd-numbered offsets are the associated values. + * + * Header names are not lowercased, and duplicates are not merged. + * + * ```js + * // Prints something like: + * // + * // [ 'user-agent', + * // 'this is invalid because there can be only one', + * // 'User-Agent', + * // 'curl/7.22.0', + * // 'Host', + * // '127.0.0.1:8000', + * // 'ACCEPT', + * // '*' ] + * console.log(request.rawHeaders); + * ``` + * @since v0.11.6 + */ + rawHeaders: string[]; + /** + * The request/response trailers object. Only populated at the `'end'` event. + * @since v0.3.0 + */ + trailers: NodeJS.Dict; + /** + * Similar to `message.trailers`, but there is no join logic and the values are + * always arrays of strings, even for headers received just once. + * Only populated at the `'end'` event. + * @since v18.3.0, v16.17.0 + */ + trailersDistinct: NodeJS.Dict; + /** + * The raw request/response trailer keys and values exactly as they were + * received. Only populated at the `'end'` event. + * @since v0.11.6 + */ + rawTrailers: string[]; + /** + * Calls `message.socket.setTimeout(msecs, callback)`. + * @since v0.5.9 + */ + setTimeout(msecs: number, callback?: () => void): this; + /** + * **Only valid for request obtained from {@link Server}.** + * + * The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`. + * @since v0.1.1 + */ + method?: string | undefined; + /** + * **Only valid for request obtained from {@link Server}.** + * + * Request URL string. This contains only the URL that is present in the actual + * HTTP request. Take the following request: + * + * ```http + * GET /status?name=ryan HTTP/1.1 + * Accept: text/plain + * ``` + * + * To parse the URL into its parts: + * + * ```js + * new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`); + * ``` + * + * When `request.url` is `'/status?name=ryan'` and `process.env.HOST` is undefined: + * + * ```console + * $ node + * > new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`); + * URL { + * href: 'http://localhost/status?name=ryan', + * origin: 'http://localhost', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'localhost', + * hostname: 'localhost', + * port: '', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * + * Ensure that you set `process.env.HOST` to the server's host name, or consider replacing this part entirely. If using `req.headers.host`, ensure proper + * validation is used, as clients may specify a custom `Host` header. + * @since v0.1.90 + */ + url?: string | undefined; + /** + * **Only valid for response obtained from {@link ClientRequest}.** + * + * The 3-digit HTTP response status code. E.G. `404`. + * @since v0.1.1 + */ + statusCode?: number | undefined; + /** + * **Only valid for response obtained from {@link ClientRequest}.** + * + * The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`. + * @since v0.11.10 + */ + statusMessage?: string | undefined; + /** + * Calls `destroy()` on the socket that received the `IncomingMessage`. If `error` is provided, an `'error'` event is emitted on the socket and `error` is passed + * as an argument to any listeners on the event. + * @since v0.3.0 + */ + destroy(error?: Error): this; + // #region InternalEventEmitter + addListener( + eventName: E, + listener: (...args: IncomingMessageEventMap[E]) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: IncomingMessageEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: IncomingMessageEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners( + eventName: E, + ): ((...args: IncomingMessageEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off( + eventName: E, + listener: (...args: IncomingMessageEventMap[E]) => void, + ): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on( + eventName: E, + listener: (...args: IncomingMessageEventMap[E]) => void, + ): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: (...args: IncomingMessageEventMap[E]) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: IncomingMessageEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: IncomingMessageEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners( + eventName: E, + ): ((...args: IncomingMessageEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: IncomingMessageEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + interface ProxyEnv extends NodeJS.ProcessEnv { + HTTP_PROXY?: string | undefined; + HTTPS_PROXY?: string | undefined; + NO_PROXY?: string | undefined; + http_proxy?: string | undefined; + https_proxy?: string | undefined; + no_proxy?: string | undefined; + } + interface AgentOptions extends NodeJS.PartialOptions { + /** + * Keep sockets around in a pool to be used by other requests in the future. Default = false + */ + keepAlive?: boolean | undefined; + /** + * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. + * Only relevant if keepAlive is set to true. + */ + keepAliveMsecs?: number | undefined; + /** + * Milliseconds to subtract from + * the server-provided `keep-alive: timeout=...` hint when determining socket + * expiration time. This buffer helps ensure the agent closes the socket + * slightly before the server does, reducing the chance of sending a request + * on a socket that’s about to be closed by the server. + * @since v24.7.0 + * @default 1000 + */ + agentKeepAliveTimeoutBuffer?: number | undefined; + /** + * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity + */ + maxSockets?: number | undefined; + /** + * Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached. Default: Infinity. + */ + maxTotalSockets?: number | undefined; + /** + * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. + */ + maxFreeSockets?: number | undefined; + /** + * Socket timeout in milliseconds. This will set the timeout after the socket is connected. + */ + timeout?: number | undefined; + /** + * Scheduling strategy to apply when picking the next free socket to use. + * @default `lifo` + */ + scheduling?: "fifo" | "lifo" | undefined; + /** + * Environment variables for proxy configuration. See + * [Built-in Proxy Support](https://nodejs.org/docs/latest-v25.x/api/http.html#built-in-proxy-support) for details. + * @since v24.5.0 + */ + proxyEnv?: ProxyEnv | undefined; + /** + * Default port to use when the port is not specified in requests. + * @since v24.5.0 + */ + defaultPort?: number | undefined; + /** + * The protocol to use for the agent. + * @since v24.5.0 + */ + protocol?: string | undefined; + } + /** + * An `Agent` is responsible for managing connection persistence + * and reuse for HTTP clients. It maintains a queue of pending requests + * for a given host and port, reusing a single socket connection for each + * until the queue is empty, at which time the socket is either destroyed + * or put into a pool where it is kept to be used again for requests to the + * same host and port. Whether it is destroyed or pooled depends on the `keepAlive` `option`. + * + * Pooled connections have TCP Keep-Alive enabled for them, but servers may + * still close idle connections, in which case they will be removed from the + * pool and a new connection will be made when a new HTTP request is made for + * that host and port. Servers may also refuse to allow multiple requests + * over the same connection, in which case the connection will have to be + * remade for every request and cannot be pooled. The `Agent` will still make + * the requests to that server, but each one will occur over a new connection. + * + * When a connection is closed by the client or the server, it is removed + * from the pool. Any unused sockets in the pool will be unrefed so as not + * to keep the Node.js process running when there are no outstanding requests. + * (see `socket.unref()`). + * + * It is good practice, to `destroy()` an `Agent` instance when it is no + * longer in use, because unused sockets consume OS resources. + * + * Sockets are removed from an agent when the socket emits either + * a `'close'` event or an `'agentRemove'` event. When intending to keep one + * HTTP request open for a long time without keeping it in the agent, something + * like the following may be done: + * + * ```js + * http.get(options, (res) => { + * // Do stuff + * }).on('socket', (socket) => { + * socket.emit('agentRemove'); + * }); + * ``` + * + * An agent may also be used for an individual request. By providing `{agent: false}` as an option to the `http.get()` or `http.request()` functions, a one-time use `Agent` with default options + * will be used + * for the client connection. + * + * `agent:false`: + * + * ```js + * http.get({ + * hostname: 'localhost', + * port: 80, + * path: '/', + * agent: false, // Create a new agent just for this one request + * }, (res) => { + * // Do stuff with response + * }); + * ``` + * + * `options` in [`socket.connect()`](https://nodejs.org/docs/latest-v25.x/api/net.html#socketconnectoptions-connectlistener) are also supported. + * + * To configure any of them, a custom {@link Agent} instance must be created. + * + * ```js + * import http from 'node:http'; + * const keepAliveAgent = new http.Agent({ keepAlive: true }); + * options.agent = keepAliveAgent; + * http.request(options, onResponseCallback) + * ``` + * @since v0.3.4 + */ + class Agent extends EventEmitter { + /** + * By default set to 256. For agents with `keepAlive` enabled, this + * sets the maximum number of sockets that will be left open in the free + * state. + * @since v0.11.7 + */ + maxFreeSockets: number; + /** + * By default set to `Infinity`. Determines how many concurrent sockets the agent + * can have open per origin. Origin is the returned value of `agent.getName()`. + * @since v0.3.6 + */ + maxSockets: number; + /** + * By default set to `Infinity`. Determines how many concurrent sockets the agent + * can have open. Unlike `maxSockets`, this parameter applies across all origins. + * @since v14.5.0, v12.19.0 + */ + maxTotalSockets: number; + /** + * An object which contains arrays of sockets currently awaiting use by + * the agent when `keepAlive` is enabled. Do not modify. + * + * Sockets in the `freeSockets` list will be automatically destroyed and + * removed from the array on `'timeout'`. + * @since v0.11.4 + */ + readonly freeSockets: NodeJS.ReadOnlyDict; + /** + * An object which contains arrays of sockets currently in use by the + * agent. Do not modify. + * @since v0.3.6 + */ + readonly sockets: NodeJS.ReadOnlyDict; + /** + * An object which contains queues of requests that have not yet been assigned to + * sockets. Do not modify. + * @since v0.5.9 + */ + readonly requests: NodeJS.ReadOnlyDict; + constructor(opts?: AgentOptions); + /** + * Destroy any sockets that are currently in use by the agent. + * + * It is usually not necessary to do this. However, if using an + * agent with `keepAlive` enabled, then it is best to explicitly shut down + * the agent when it is no longer needed. Otherwise, + * sockets might stay open for quite a long time before the server + * terminates them. + * @since v0.11.4 + */ + destroy(): void; + /** + * Produces a socket/stream to be used for HTTP requests. + * + * By default, this function is the same as `net.createConnection()`. However, + * custom agents may override this method in case greater flexibility is desired. + * + * A socket/stream can be supplied in one of two ways: by returning the + * socket/stream from this function, or by passing the socket/stream to `callback`. + * + * This method is guaranteed to return an instance of the `net.Socket` class, + * a subclass of `stream.Duplex`, unless the user specifies a socket + * type other than `net.Socket`. + * + * `callback` has a signature of `(err, stream)`. + * @since v0.11.4 + * @param options Options containing connection details. Check `createConnection` for the format of the options + * @param callback Callback function that receives the created socket + */ + createConnection( + options: ClientRequestArgs, + callback?: (err: Error | null, stream: stream.Duplex) => void, + ): stream.Duplex | null | undefined; + /** + * Called when `socket` is detached from a request and could be persisted by the`Agent`. Default behavior is to: + * + * ```js + * socket.setKeepAlive(true, this.keepAliveMsecs); + * socket.unref(); + * return true; + * ``` + * + * This method can be overridden by a particular `Agent` subclass. If this + * method returns a falsy value, the socket will be destroyed instead of persisting + * it for use with the next request. + * + * The `socket` argument can be an instance of `net.Socket`, a subclass of `stream.Duplex`. + * @since v8.1.0 + */ + keepSocketAlive(socket: stream.Duplex): void; + /** + * Called when `socket` is attached to `request` after being persisted because of + * the keep-alive options. Default behavior is to: + * + * ```js + * socket.ref(); + * ``` + * + * This method can be overridden by a particular `Agent` subclass. + * + * The `socket` argument can be an instance of `net.Socket`, a subclass of `stream.Duplex`. + * @since v8.1.0 + */ + reuseSocket(socket: stream.Duplex, request: ClientRequest): void; + /** + * Get a unique name for a set of request options, to determine whether a + * connection can be reused. For an HTTP agent, this returns`host:port:localAddress` or `host:port:localAddress:family`. For an HTTPS agent, + * the name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options + * that determine socket reusability. + * @since v0.11.4 + * @param options A set of options providing information for name generation + */ + getName(options?: ClientRequestArgs): string; + } + const METHODS: string[]; + const STATUS_CODES: { + [errorCode: number]: string | undefined; + [errorCode: string]: string | undefined; + }; + /** + * Returns a new instance of {@link Server}. + * + * The `requestListener` is a function which is automatically + * added to the `'request'` event. + * + * ```js + * import http from 'node:http'; + * + * // Create a local server to receive data from + * const server = http.createServer((req, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!', + * })); + * }); + * + * server.listen(8000); + * ``` + * + * ```js + * import http from 'node:http'; + * + * // Create a local server to receive data from + * const server = http.createServer(); + * + * // Listen to the request event + * server.on('request', (request, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!', + * })); + * }); + * + * server.listen(8000); + * ``` + * @since v0.1.13 + */ + function createServer< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + >(requestListener?: RequestListener): Server; + function createServer< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + >( + options: ServerOptions, + requestListener?: RequestListener, + ): Server; + // although RequestOptions are passed as ClientRequestArgs to ClientRequest directly, + // create interface RequestOptions would make the naming more clear to developers + interface RequestOptions extends ClientRequestArgs {} + /** + * `options` in `socket.connect()` are also supported. + * + * Node.js maintains several connections per server to make HTTP requests. + * This function allows one to transparently issue requests. + * + * `url` can be a string or a `URL` object. If `url` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * If both `url` and `options` are specified, the objects are merged, with the `options` properties taking precedence. + * + * The optional `callback` parameter will be added as a one-time listener for + * the `'response'` event. + * + * `http.request()` returns an instance of the {@link ClientRequest} class. The `ClientRequest` instance is a writable stream. If one needs to + * upload a file with a POST request, then write to the `ClientRequest` object. + * + * ```js + * import http from 'node:http'; + * import { Buffer } from 'node:buffer'; + * + * const postData = JSON.stringify({ + * 'msg': 'Hello World!', + * }); + * + * const options = { + * hostname: 'www.google.com', + * port: 80, + * path: '/upload', + * method: 'POST', + * headers: { + * 'Content-Type': 'application/json', + * 'Content-Length': Buffer.byteLength(postData), + * }, + * }; + * + * const req = http.request(options, (res) => { + * console.log(`STATUS: ${res.statusCode}`); + * console.log(`HEADERS: ${JSON.stringify(res.headers)}`); + * res.setEncoding('utf8'); + * res.on('data', (chunk) => { + * console.log(`BODY: ${chunk}`); + * }); + * res.on('end', () => { + * console.log('No more data in response.'); + * }); + * }); + * + * req.on('error', (e) => { + * console.error(`problem with request: ${e.message}`); + * }); + * + * // Write data to request body + * req.write(postData); + * req.end(); + * ``` + * + * In the example `req.end()` was called. With `http.request()` one + * must always call `req.end()` to signify the end of the request - + * even if there is no data being written to the request body. + * + * If any error is encountered during the request (be that with DNS resolution, + * TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted + * on the returned request object. As with all `'error'` events, if no listeners + * are registered the error will be thrown. + * + * There are a few special headers that should be noted. + * + * * Sending a 'Connection: keep-alive' will notify Node.js that the connection to + * the server should be persisted until the next request. + * * Sending a 'Content-Length' header will disable the default chunked encoding. + * * Sending an 'Expect' header will immediately send the request headers. + * Usually, when sending 'Expect: 100-continue', both a timeout and a listener + * for the `'continue'` event should be set. See RFC 2616 Section 8.2.3 for more + * information. + * * Sending an Authorization header will override using the `auth` option + * to compute basic authentication. + * + * Example using a `URL` as `options`: + * + * ```js + * const options = new URL('http://abc:xyz@example.com'); + * + * const req = http.request(options, (res) => { + * // ... + * }); + * ``` + * + * In a successful request, the following events will be emitted in the following + * order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * (`'data'` will not be emitted at all if the response body is empty, for + * instance, in most redirects) + * * `'end'` on the `res` object + * * `'close'` + * + * In the case of a connection error, the following events will be emitted: + * + * * `'socket'` + * * `'error'` + * * `'close'` + * + * In the case of a premature connection close before the response is received, + * the following events will be emitted in the following order: + * + * * `'socket'` + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'` + * * `'close'` + * + * In the case of a premature connection close after the response is received, + * the following events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (connection closed here) + * * `'aborted'` on the `res` object + * * `'close'` + * * `'error'` on the `res` object with an error with message `'Error: aborted'` and code `'ECONNRESET'` + * * `'close'` on the `res` object + * + * If `req.destroy()` is called before a socket is assigned, the following + * events will be emitted in the following order: + * + * * (`req.destroy()` called here) + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'`, or the error with which `req.destroy()` was called + * * `'close'` + * + * If `req.destroy()` is called before the connection succeeds, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * (`req.destroy()` called here) + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'`, or the error with which `req.destroy()` was called + * * `'close'` + * + * If `req.destroy()` is called after the response is received, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (`req.destroy()` called here) + * * `'aborted'` on the `res` object + * * `'close'` + * * `'error'` on the `res` object with an error with message `'Error: aborted'` and code `'ECONNRESET'`, or the error with which `req.destroy()` was called + * * `'close'` on the `res` object + * + * If `req.abort()` is called before a socket is assigned, the following + * events will be emitted in the following order: + * + * * (`req.abort()` called here) + * * `'abort'` + * * `'close'` + * + * If `req.abort()` is called before the connection succeeds, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * (`req.abort()` called here) + * * `'abort'` + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'` + * * `'close'` + * + * If `req.abort()` is called after the response is received, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (`req.abort()` called here) + * * `'abort'` + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message `'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'close'` on the `res` object + * + * Setting the `timeout` option or using the `setTimeout()` function will + * not abort the request or do anything besides add a `'timeout'` event. + * + * Passing an `AbortSignal` and then calling `abort()` on the corresponding `AbortController` will behave the same way as calling `.destroy()` on the + * request. Specifically, the `'error'` event will be emitted with an error with + * the message `'AbortError: The operation was aborted'`, the code `'ABORT_ERR'` and the `cause`, if one was provided. + * @since v0.3.6 + */ + function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function request( + url: string | URL, + options: RequestOptions, + callback?: (res: IncomingMessage) => void, + ): ClientRequest; + /** + * Since most requests are GET requests without bodies, Node.js provides this + * convenience method. The only difference between this method and {@link request} is that it sets the method to GET by default and calls `req.end()` automatically. The callback must take care to + * consume the response + * data for reasons stated in {@link ClientRequest} section. + * + * The `callback` is invoked with a single argument that is an instance of {@link IncomingMessage}. + * + * JSON fetching example: + * + * ```js + * http.get('http://localhost:8000/', (res) => { + * const { statusCode } = res; + * const contentType = res.headers['content-type']; + * + * let error; + * // Any 2xx status code signals a successful response but + * // here we're only checking for 200. + * if (statusCode !== 200) { + * error = new Error('Request Failed.\n' + + * `Status Code: ${statusCode}`); + * } else if (!/^application\/json/.test(contentType)) { + * error = new Error('Invalid content-type.\n' + + * `Expected application/json but received ${contentType}`); + * } + * if (error) { + * console.error(error.message); + * // Consume response data to free up memory + * res.resume(); + * return; + * } + * + * res.setEncoding('utf8'); + * let rawData = ''; + * res.on('data', (chunk) => { rawData += chunk; }); + * res.on('end', () => { + * try { + * const parsedData = JSON.parse(rawData); + * console.log(parsedData); + * } catch (e) { + * console.error(e.message); + * } + * }); + * }).on('error', (e) => { + * console.error(`Got error: ${e.message}`); + * }); + * + * // Create a local server to receive data from + * const server = http.createServer((req, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!', + * })); + * }); + * + * server.listen(8000); + * ``` + * @since v0.3.6 + * @param options Accepts the same `options` as {@link request}, with the method set to GET by default. + */ + function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + /** + * Performs the low-level validations on the provided `name` that are done when `res.setHeader(name, value)` is called. + * + * Passing illegal value as `name` will result in a `TypeError` being thrown, + * identified by `code: 'ERR_INVALID_HTTP_TOKEN'`. + * + * It is not necessary to use this method before passing headers to an HTTP request + * or response. The HTTP module will automatically validate such headers. + * + * Example: + * + * ```js + * import { validateHeaderName } from 'node:http'; + * + * try { + * validateHeaderName(''); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code); // --> 'ERR_INVALID_HTTP_TOKEN' + * console.error(err.message); // --> 'Header name must be a valid HTTP token [""]' + * } + * ``` + * @since v14.3.0 + * @param [label='Header name'] Label for error message. + */ + function validateHeaderName(name: string): void; + /** + * Performs the low-level validations on the provided `value` that are done when `res.setHeader(name, value)` is called. + * + * Passing illegal value as `value` will result in a `TypeError` being thrown. + * + * * Undefined value error is identified by `code: 'ERR_HTTP_INVALID_HEADER_VALUE'`. + * * Invalid value character error is identified by `code: 'ERR_INVALID_CHAR'`. + * + * It is not necessary to use this method before passing headers to an HTTP request + * or response. The HTTP module will automatically validate such headers. + * + * Examples: + * + * ```js + * import { validateHeaderValue } from 'node:http'; + * + * try { + * validateHeaderValue('x-my-header', undefined); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'); // --> true + * console.error(err.message); // --> 'Invalid value "undefined" for header "x-my-header"' + * } + * + * try { + * validateHeaderValue('x-my-header', 'oʊmɪɡə'); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code === 'ERR_INVALID_CHAR'); // --> true + * console.error(err.message); // --> 'Invalid character in header content ["x-my-header"]' + * } + * ``` + * @since v14.3.0 + * @param name Header name + * @param value Header value + */ + function validateHeaderValue(name: string, value: string): void; + /** + * Set the maximum number of idle HTTP parsers. + * @since v18.8.0, v16.18.0 + * @param [max=1000] + */ + function setMaxIdleHTTPParsers(max: number): void; + /** + * Global instance of `Agent` which is used as the default for all HTTP client + * requests. Diverges from a default `Agent` configuration by having `keepAlive` + * enabled and a `timeout` of 5 seconds. + * @since v0.5.9 + */ + let globalAgent: Agent; + /** + * Read-only property specifying the maximum allowed size of HTTP headers in bytes. + * Defaults to 16KB. Configurable using the `--max-http-header-size` CLI option. + */ + const maxHeaderSize: number; + /** + * A browser-compatible implementation of `WebSocket`. + * @since v22.5.0 + */ + const WebSocket: typeof import("undici-types").WebSocket; + /** + * @since v22.5.0 + */ + const CloseEvent: typeof import("undici-types").CloseEvent; + /** + * @since v22.5.0 + */ + const MessageEvent: typeof import("undici-types").MessageEvent; +} +declare module "http" { + export * from "node:http"; +} diff --git a/backend/node_modules/@types/node/http2.d.ts b/backend/node_modules/@types/node/http2.d.ts new file mode 100644 index 0000000..4130bfe --- /dev/null +++ b/backend/node_modules/@types/node/http2.d.ts @@ -0,0 +1,2480 @@ +/** + * The `node:http2` module provides an implementation of the [HTTP/2](https://tools.ietf.org/html/rfc7540) protocol. + * It can be accessed using: + * + * ```js + * import http2 from 'node:http2'; + * ``` + * @since v8.4.0 + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/http2.js) + */ +declare module "node:http2" { + import { NonSharedBuffer } from "node:buffer"; + import { InternalEventEmitter } from "node:events"; + import * as fs from "node:fs"; + import * as net from "node:net"; + import * as stream from "node:stream"; + import * as tls from "node:tls"; + import * as url from "node:url"; + import { + IncomingHttpHeaders as Http1IncomingHttpHeaders, + IncomingMessage, + OutgoingHttpHeaders, + ServerResponse, + } from "node:http"; + interface IncomingHttpStatusHeader { + ":status"?: number | undefined; + } + interface IncomingHttpHeaders extends Http1IncomingHttpHeaders { + ":path"?: string | undefined; + ":method"?: string | undefined; + ":authority"?: string | undefined; + ":scheme"?: string | undefined; + } + // Http2Stream + interface StreamState { + localWindowSize?: number | undefined; + state?: number | undefined; + localClose?: number | undefined; + remoteClose?: number | undefined; + /** @deprecated */ + sumDependencyWeight?: number | undefined; + /** @deprecated */ + weight?: number | undefined; + } + interface ServerStreamResponseOptions { + endStream?: boolean | undefined; + waitForTrailers?: boolean | undefined; + } + interface StatOptions { + offset: number; + length: number; + } + interface ServerStreamFileResponseOptions { + statCheck?: + | ((stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions) => void) + | undefined; + waitForTrailers?: boolean | undefined; + offset?: number | undefined; + length?: number | undefined; + } + interface ServerStreamFileResponseOptionsWithError extends ServerStreamFileResponseOptions { + onError?: ((err: NodeJS.ErrnoException) => void) | undefined; + } + interface Http2StreamEventMap extends stream.DuplexEventMap { + "aborted": []; + "data": [chunk: string | NonSharedBuffer]; + "frameError": [type: number, code: number, id: number]; + "ready": []; + "streamClosed": [code: number]; + "timeout": []; + "trailers": [trailers: IncomingHttpHeaders, flags: number]; + "wantTrailers": []; + } + interface Http2Stream extends stream.Duplex { + /** + * Set to `true` if the `Http2Stream` instance was aborted abnormally. When set, + * the `'aborted'` event will have been emitted. + * @since v8.4.0 + */ + readonly aborted: boolean; + /** + * This property shows the number of characters currently buffered to be written. + * See `net.Socket.bufferSize` for details. + * @since v11.2.0, v10.16.0 + */ + readonly bufferSize: number; + /** + * Set to `true` if the `Http2Stream` instance has been closed. + * @since v9.4.0 + */ + readonly closed: boolean; + /** + * Set to `true` if the `Http2Stream` instance has been destroyed and is no longer + * usable. + * @since v8.4.0 + */ + readonly destroyed: boolean; + /** + * Set to `true` if the `END_STREAM` flag was set in the request or response + * HEADERS frame received, indicating that no additional data should be received + * and the readable side of the `Http2Stream` will be closed. + * @since v10.11.0 + */ + readonly endAfterHeaders: boolean; + /** + * The numeric stream identifier of this `Http2Stream` instance. Set to `undefined` if the stream identifier has not yet been assigned. + * @since v8.4.0 + */ + readonly id?: number | undefined; + /** + * Set to `true` if the `Http2Stream` instance has not yet been assigned a + * numeric stream identifier. + * @since v9.4.0 + */ + readonly pending: boolean; + /** + * Set to the `RST_STREAM` `error code` reported when the `Http2Stream` is + * destroyed after either receiving an `RST_STREAM` frame from the connected peer, + * calling `http2stream.close()`, or `http2stream.destroy()`. Will be `undefined` if the `Http2Stream` has not been closed. + * @since v8.4.0 + */ + readonly rstCode: number; + /** + * An object containing the outbound headers sent for this `Http2Stream`. + * @since v9.5.0 + */ + readonly sentHeaders: OutgoingHttpHeaders; + /** + * An array of objects containing the outbound informational (additional) headers + * sent for this `Http2Stream`. + * @since v9.5.0 + */ + readonly sentInfoHeaders?: OutgoingHttpHeaders[] | undefined; + /** + * An object containing the outbound trailers sent for this `HttpStream`. + * @since v9.5.0 + */ + readonly sentTrailers?: OutgoingHttpHeaders | undefined; + /** + * A reference to the `Http2Session` instance that owns this `Http2Stream`. The + * value will be `undefined` after the `Http2Stream` instance is destroyed. + * @since v8.4.0 + */ + readonly session: Http2Session | undefined; + /** + * Provides miscellaneous information about the current state of the `Http2Stream`. + * + * A current state of this `Http2Stream`. + * @since v8.4.0 + */ + readonly state: StreamState; + /** + * Closes the `Http2Stream` instance by sending an `RST_STREAM` frame to the + * connected HTTP/2 peer. + * @since v8.4.0 + * @param [code=http2.constants.NGHTTP2_NO_ERROR] Unsigned 32-bit integer identifying the error code. + * @param callback An optional function registered to listen for the `'close'` event. + */ + close(code?: number, callback?: () => void): void; + /** + * @deprecated Priority signaling is no longer supported in Node.js. + */ + priority(options: unknown): void; + /** + * ```js + * import http2 from 'node:http2'; + * const client = http2.connect('http://example.org:8000'); + * const { NGHTTP2_CANCEL } = http2.constants; + * const req = client.request({ ':path': '/' }); + * + * // Cancel the stream if there's no activity after 5 seconds + * req.setTimeout(5000, () => req.close(NGHTTP2_CANCEL)); + * ``` + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * Sends a trailing `HEADERS` frame to the connected HTTP/2 peer. This method + * will cause the `Http2Stream` to be immediately closed and must only be + * called after the `'wantTrailers'` event has been emitted. When sending a + * request or sending a response, the `options.waitForTrailers` option must be set + * in order to keep the `Http2Stream` open after the final `DATA` frame so that + * trailers can be sent. + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond(undefined, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ xyz: 'abc' }); + * }); + * stream.end('Hello World'); + * }); + * ``` + * + * The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header + * fields (e.g. `':method'`, `':path'`, etc). + * @since v10.0.0 + */ + sendTrailers(headers: OutgoingHttpHeaders): void; + // #region InternalEventEmitter + addListener( + eventName: E, + listener: (...args: Http2StreamEventMap[E]) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: Http2StreamEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: Http2StreamEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners(eventName: E): ((...args: Http2StreamEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off( + eventName: E, + listener: (...args: Http2StreamEventMap[E]) => void, + ): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on( + eventName: E, + listener: (...args: Http2StreamEventMap[E]) => void, + ): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: (...args: Http2StreamEventMap[E]) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: Http2StreamEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: Http2StreamEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners(eventName: E): ((...args: Http2StreamEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: Http2StreamEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + interface ClientHttp2StreamEventMap extends Http2StreamEventMap { + "continue": []; + "headers": [headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number, rawHeaders: string[]]; + "push": [headers: IncomingHttpHeaders, flags: number]; + "response": [headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number, rawHeaders: string[]]; + } + interface ClientHttp2Stream extends Http2Stream { + // #region InternalEventEmitter + addListener( + eventName: E, + listener: (...args: ClientHttp2StreamEventMap[E]) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: ClientHttp2StreamEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: ClientHttp2StreamEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners( + eventName: E, + ): ((...args: ClientHttp2StreamEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off( + eventName: E, + listener: (...args: ClientHttp2StreamEventMap[E]) => void, + ): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on( + eventName: E, + listener: (...args: ClientHttp2StreamEventMap[E]) => void, + ): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: (...args: ClientHttp2StreamEventMap[E]) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: ClientHttp2StreamEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: ClientHttp2StreamEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners( + eventName: E, + ): ((...args: ClientHttp2StreamEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: ClientHttp2StreamEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + interface ServerHttp2Stream extends Http2Stream { + /** + * True if headers were sent, false otherwise (read-only). + * @since v8.4.0 + */ + readonly headersSent: boolean; + /** + * Read-only property mapped to the `SETTINGS_ENABLE_PUSH` flag of the remote + * client's most recent `SETTINGS` frame. Will be `true` if the remote peer + * accepts push streams, `false` otherwise. Settings are the same for every `Http2Stream` in the same `Http2Session`. + * @since v8.4.0 + */ + readonly pushAllowed: boolean; + /** + * Sends an additional informational `HEADERS` frame to the connected HTTP/2 peer. + * @since v8.4.0 + */ + additionalHeaders(headers: OutgoingHttpHeaders): void; + /** + * Initiates a push stream. The callback is invoked with the new `Http2Stream` instance created for the push stream passed as the second argument, or an `Error` passed as the first argument. + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.pushStream({ ':path': '/' }, (err, pushStream, headers) => { + * if (err) throw err; + * pushStream.respond({ ':status': 200 }); + * pushStream.end('some pushed data'); + * }); + * stream.end('some data'); + * }); + * ``` + * + * Setting the weight of a push stream is not allowed in the `HEADERS` frame. Pass + * a `weight` value to `http2stream.priority` with the `silent` option set to `true` to enable server-side bandwidth balancing between concurrent streams. + * + * Calling `http2stream.pushStream()` from within a pushed stream is not permitted + * and will throw an error. + * @since v8.4.0 + * @param callback Callback that is called once the push stream has been initiated. + */ + pushStream( + headers: OutgoingHttpHeaders, + callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void, + ): void; + pushStream( + headers: OutgoingHttpHeaders, + options?: Pick, + callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void, + ): void; + /** + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.end('some data'); + * }); + * ``` + * + * Initiates a response. When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be sent. + * The `http2stream.sendTrailers()` method can then be used to send trailing header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either `http2stream.sendTrailers()` or `http2stream.close()` to close the `Http2Stream`. + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * stream.end('some data'); + * }); + * ``` + * @since v8.4.0 + */ + respond(headers?: OutgoingHttpHeaders | readonly string[], options?: ServerStreamResponseOptions): void; + /** + * Initiates a response whose data is read from the given file descriptor. No + * validation is performed on the given file descriptor. If an error occurs while + * attempting to read data using the file descriptor, the `Http2Stream` will be + * closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR` code. + * + * When used, the `Http2Stream` object's `Duplex` interface will be closed + * automatically. + * + * ```js + * import http2 from 'node:http2'; + * import fs from 'node:fs'; + * + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * const fd = fs.openSync('/some/file', 'r'); + * + * const stat = fs.fstatSync(fd); + * const headers = { + * 'content-length': stat.size, + * 'last-modified': stat.mtime.toUTCString(), + * 'content-type': 'text/plain; charset=utf-8', + * }; + * stream.respondWithFD(fd, headers); + * stream.on('close', () => fs.closeSync(fd)); + * }); + * ``` + * + * The optional `options.statCheck` function may be specified to give user code + * an opportunity to set additional content headers based on the `fs.Stat` details + * of the given fd. If the `statCheck` function is provided, the `http2stream.respondWithFD()` method will + * perform an `fs.fstat()` call to collect details on the provided file descriptor. + * + * The `offset` and `length` options may be used to limit the response to a + * specific range subset. This can be used, for instance, to support HTTP Range + * requests. + * + * The file descriptor or `FileHandle` is not closed when the stream is closed, + * so it will need to be closed manually once it is no longer needed. + * Using the same file descriptor concurrently for multiple streams + * is not supported and may result in data loss. Re-using a file descriptor + * after a stream has finished is supported. + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code _must_ call either `http2stream.sendTrailers()` + * or `http2stream.close()` to close the `Http2Stream`. + * + * ```js + * import http2 from 'node:http2'; + * import fs from 'node:fs'; + * + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * const fd = fs.openSync('/some/file', 'r'); + * + * const stat = fs.fstatSync(fd); + * const headers = { + * 'content-length': stat.size, + * 'last-modified': stat.mtime.toUTCString(), + * 'content-type': 'text/plain; charset=utf-8', + * }; + * stream.respondWithFD(fd, headers, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * + * stream.on('close', () => fs.closeSync(fd)); + * }); + * ``` + * @since v8.4.0 + * @param fd A readable file descriptor. + */ + respondWithFD( + fd: number | fs.promises.FileHandle, + headers?: OutgoingHttpHeaders, + options?: ServerStreamFileResponseOptions, + ): void; + /** + * Sends a regular file as the response. The `path` must specify a regular file + * or an `'error'` event will be emitted on the `Http2Stream` object. + * + * When used, the `Http2Stream` object's `Duplex` interface will be closed + * automatically. + * + * The optional `options.statCheck` function may be specified to give user code + * an opportunity to set additional content headers based on the `fs.Stat` details + * of the given file: + * + * If an error occurs while attempting to read the file data, the `Http2Stream` will be closed using an + * `RST_STREAM` frame using the standard `INTERNAL_ERROR` code. + * If the `onError` callback is defined, then it will be called. Otherwise, the stream will be destroyed. + * + * Example using a file path: + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * function statCheck(stat, headers) { + * headers['last-modified'] = stat.mtime.toUTCString(); + * } + * + * function onError(err) { + * // stream.respond() can throw if the stream has been destroyed by + * // the other side. + * try { + * if (err.code === 'ENOENT') { + * stream.respond({ ':status': 404 }); + * } else { + * stream.respond({ ':status': 500 }); + * } + * } catch (err) { + * // Perform actual error handling. + * console.error(err); + * } + * stream.end(); + * } + * + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { statCheck, onError }); + * }); + * ``` + * + * The `options.statCheck` function may also be used to cancel the send operation + * by returning `false`. For instance, a conditional request may check the stat + * results to determine if the file has been modified to return an appropriate `304` response: + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * function statCheck(stat, headers) { + * // Check the stat here... + * stream.respond({ ':status': 304 }); + * return false; // Cancel the send operation + * } + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { statCheck }); + * }); + * ``` + * + * The `content-length` header field will be automatically set. + * + * The `offset` and `length` options may be used to limit the response to a + * specific range subset. This can be used, for instance, to support HTTP Range + * requests. + * + * The `options.onError` function may also be used to handle all the errors + * that could happen before the delivery of the file is initiated. The + * default behavior is to destroy the stream. + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * }); + * ``` + * @since v8.4.0 + */ + respondWithFile( + path: string, + headers?: OutgoingHttpHeaders, + options?: ServerStreamFileResponseOptionsWithError, + ): void; + } + // Http2Session + interface Settings { + headerTableSize?: number | undefined; + enablePush?: boolean | undefined; + initialWindowSize?: number | undefined; + maxFrameSize?: number | undefined; + maxConcurrentStreams?: number | undefined; + maxHeaderListSize?: number | undefined; + enableConnectProtocol?: boolean | undefined; + } + interface ClientSessionRequestOptions { + endStream?: boolean | undefined; + exclusive?: boolean | undefined; + parent?: number | undefined; + waitForTrailers?: boolean | undefined; + signal?: AbortSignal | undefined; + } + interface SessionState { + effectiveLocalWindowSize?: number | undefined; + effectiveRecvDataLength?: number | undefined; + nextStreamID?: number | undefined; + localWindowSize?: number | undefined; + lastProcStreamID?: number | undefined; + remoteWindowSize?: number | undefined; + outboundQueueSize?: number | undefined; + deflateDynamicTableSize?: number | undefined; + inflateDynamicTableSize?: number | undefined; + } + interface Http2SessionEventMap { + "close": []; + "connect": [session: Http2Session, socket: net.Socket | tls.TLSSocket]; + "error": [err: Error]; + "frameError": [type: number, code: number, id: number]; + "goaway": [errorCode: number, lastStreamID: number, opaqueData?: NonSharedBuffer]; + "localSettings": [settings: Settings]; + "ping": [payload: Buffer]; + "remoteSettings": [settings: Settings]; + "stream": [ + stream: Http2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + rawHeaders: string[], + ]; + "timeout": []; + } + interface Http2Session extends InternalEventEmitter { + /** + * Value will be `undefined` if the `Http2Session` is not yet connected to a + * socket, `h2c` if the `Http2Session` is not connected to a `TLSSocket`, or + * will return the value of the connected `TLSSocket`'s own `alpnProtocol` property. + * @since v9.4.0 + */ + readonly alpnProtocol?: string | undefined; + /** + * Will be `true` if this `Http2Session` instance has been closed, otherwise `false`. + * @since v9.4.0 + */ + readonly closed: boolean; + /** + * Will be `true` if this `Http2Session` instance is still connecting, will be set + * to `false` before emitting `connect` event and/or calling the `http2.connect` callback. + * @since v10.0.0 + */ + readonly connecting: boolean; + /** + * Will be `true` if this `Http2Session` instance has been destroyed and must no + * longer be used, otherwise `false`. + * @since v8.4.0 + */ + readonly destroyed: boolean; + /** + * Value is `undefined` if the `Http2Session` session socket has not yet been + * connected, `true` if the `Http2Session` is connected with a `TLSSocket`, + * and `false` if the `Http2Session` is connected to any other kind of socket + * or stream. + * @since v9.4.0 + */ + readonly encrypted?: boolean | undefined; + /** + * A prototype-less object describing the current local settings of this `Http2Session`. + * The local settings are local to _this_`Http2Session` instance. + * @since v8.4.0 + */ + readonly localSettings: Settings; + /** + * If the `Http2Session` is connected to a `TLSSocket`, the `originSet` property + * will return an `Array` of origins for which the `Http2Session` may be + * considered authoritative. + * + * The `originSet` property is only available when using a secure TLS connection. + * @since v9.4.0 + */ + readonly originSet?: string[] | undefined; + /** + * Indicates whether the `Http2Session` is currently waiting for acknowledgment of + * a sent `SETTINGS` frame. Will be `true` after calling the `http2session.settings()` method. + * Will be `false` once all sent `SETTINGS` frames have been acknowledged. + * @since v8.4.0 + */ + readonly pendingSettingsAck: boolean; + /** + * A prototype-less object describing the current remote settings of this`Http2Session`. + * The remote settings are set by the _connected_ HTTP/2 peer. + * @since v8.4.0 + */ + readonly remoteSettings: Settings; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * limits available methods to ones safe to use with HTTP/2. + * + * `destroy`, `emit`, `end`, `pause`, `read`, `resume`, and `write` will throw + * an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for more information. + * + * `setTimeout` method will be called on this `Http2Session`. + * + * All other interactions will be routed directly to the socket. + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * Provides miscellaneous information about the current state of the`Http2Session`. + * + * An object describing the current status of this `Http2Session`. + * @since v8.4.0 + */ + readonly state: SessionState; + /** + * The `http2session.type` will be equal to `http2.constants.NGHTTP2_SESSION_SERVER` if this `Http2Session` instance is a + * server, and `http2.constants.NGHTTP2_SESSION_CLIENT` if the instance is a + * client. + * @since v8.4.0 + */ + readonly type: number; + /** + * Gracefully closes the `Http2Session`, allowing any existing streams to + * complete on their own and preventing new `Http2Stream` instances from being + * created. Once closed, `http2session.destroy()`_might_ be called if there + * are no open `Http2Stream` instances. + * + * If specified, the `callback` function is registered as a handler for the`'close'` event. + * @since v9.4.0 + */ + close(callback?: () => void): void; + /** + * Immediately terminates the `Http2Session` and the associated `net.Socket` or `tls.TLSSocket`. + * + * Once destroyed, the `Http2Session` will emit the `'close'` event. If `error` is not undefined, an `'error'` event will be emitted immediately before the `'close'` event. + * + * If there are any remaining open `Http2Streams` associated with the `Http2Session`, those will also be destroyed. + * @since v8.4.0 + * @param error An `Error` object if the `Http2Session` is being destroyed due to an error. + * @param code The HTTP/2 error code to send in the final `GOAWAY` frame. If unspecified, and `error` is not undefined, the default is `INTERNAL_ERROR`, otherwise defaults to `NO_ERROR`. + */ + destroy(error?: Error, code?: number): void; + /** + * Transmits a `GOAWAY` frame to the connected peer _without_ shutting down the`Http2Session`. + * @since v9.4.0 + * @param code An HTTP/2 error code + * @param lastStreamID The numeric ID of the last processed `Http2Stream` + * @param opaqueData A `TypedArray` or `DataView` instance containing additional data to be carried within the `GOAWAY` frame. + */ + goaway(code?: number, lastStreamID?: number, opaqueData?: NodeJS.ArrayBufferView): void; + /** + * Sends a `PING` frame to the connected HTTP/2 peer. A `callback` function must + * be provided. The method will return `true` if the `PING` was sent, `false` otherwise. + * + * The maximum number of outstanding (unacknowledged) pings is determined by the `maxOutstandingPings` configuration option. The default maximum is 10. + * + * If provided, the `payload` must be a `Buffer`, `TypedArray`, or `DataView` containing 8 bytes of data that will be transmitted with the `PING` and + * returned with the ping acknowledgment. + * + * The callback will be invoked with three arguments: an error argument that will + * be `null` if the `PING` was successfully acknowledged, a `duration` argument + * that reports the number of milliseconds elapsed since the ping was sent and the + * acknowledgment was received, and a `Buffer` containing the 8-byte `PING` payload. + * + * ```js + * session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => { + * if (!err) { + * console.log(`Ping acknowledged in ${duration} milliseconds`); + * console.log(`With payload '${payload.toString()}'`); + * } + * }); + * ``` + * + * If the `payload` argument is not specified, the default payload will be the + * 64-bit timestamp (little endian) marking the start of the `PING` duration. + * @since v8.9.3 + * @param payload Optional ping payload. + */ + ping(callback: (err: Error | null, duration: number, payload: NonSharedBuffer) => void): boolean; + ping( + payload: NodeJS.ArrayBufferView, + callback: (err: Error | null, duration: number, payload: NonSharedBuffer) => void, + ): boolean; + /** + * Calls `ref()` on this `Http2Session` instance's underlying `net.Socket`. + * @since v9.4.0 + */ + ref(): void; + /** + * Sets the local endpoint's window size. + * The `windowSize` is the total window size to set, not + * the delta. + * + * ```js + * import http2 from 'node:http2'; + * + * const server = http2.createServer(); + * const expectedWindowSize = 2 ** 20; + * server.on('connect', (session) => { + * + * // Set local window size to be 2 ** 20 + * session.setLocalWindowSize(expectedWindowSize); + * }); + * ``` + * @since v15.3.0, v14.18.0 + */ + setLocalWindowSize(windowSize: number): void; + /** + * Used to set a callback function that is called when there is no activity on + * the `Http2Session` after `msecs` milliseconds. The given `callback` is + * registered as a listener on the `'timeout'` event. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * Updates the current local settings for this `Http2Session` and sends a new `SETTINGS` frame to the connected HTTP/2 peer. + * + * Once called, the `http2session.pendingSettingsAck` property will be `true` while the session is waiting for the remote peer to acknowledge the new + * settings. + * + * The new settings will not become effective until the `SETTINGS` acknowledgment + * is received and the `'localSettings'` event is emitted. It is possible to send + * multiple `SETTINGS` frames while acknowledgment is still pending. + * @since v8.4.0 + * @param callback Callback that is called once the session is connected or right away if the session is already connected. + */ + settings( + settings: Settings, + callback?: (err: Error | null, settings: Settings, duration: number) => void, + ): void; + /** + * Calls `unref()` on this `Http2Session`instance's underlying `net.Socket`. + * @since v9.4.0 + */ + unref(): void; + } + interface ClientHttp2SessionEventMap extends Http2SessionEventMap { + "altsvc": [alt: string, origin: string, streamId: number]; + "connect": [session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket]; + "origin": [origins: string[]]; + "stream": [ + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + rawHeaders: string[], + ]; + } + interface ClientHttp2Session extends Http2Session { + /** + * For HTTP/2 Client `Http2Session` instances only, the `http2session.request()` creates and returns an `Http2Stream` instance that can be used to send an + * HTTP/2 request to the connected server. + * + * When a `ClientHttp2Session` is first created, the socket may not yet be + * connected. if `clienthttp2session.request()` is called during this time, the + * actual request will be deferred until the socket is ready to go. + * If the `session` is closed before the actual request be executed, an `ERR_HTTP2_GOAWAY_SESSION` is thrown. + * + * This method is only available if `http2session.type` is equal to `http2.constants.NGHTTP2_SESSION_CLIENT`. + * + * ```js + * import http2 from 'node:http2'; + * const clientSession = http2.connect('https://localhost:1234'); + * const { + * HTTP2_HEADER_PATH, + * HTTP2_HEADER_STATUS, + * } = http2.constants; + * + * const req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' }); + * req.on('response', (headers) => { + * console.log(headers[HTTP2_HEADER_STATUS]); + * req.on('data', (chunk) => { // .. }); + * req.on('end', () => { // .. }); + * }); + * ``` + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * is emitted immediately after queuing the last chunk of payload data to be sent. + * The `http2stream.sendTrailers()` method can then be called to send trailing + * headers to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * When `options.signal` is set with an `AbortSignal` and then `abort` on the + * corresponding `AbortController` is called, the request will emit an `'error'`event with an `AbortError` error. + * + * The `:method` and `:path` pseudo-headers are not specified within `headers`, + * they respectively default to: + * + * * `:method` \= `'GET'` + * * `:path` \= `/` + * @since v8.4.0 + */ + request( + headers?: OutgoingHttpHeaders | readonly string[], + options?: ClientSessionRequestOptions, + ): ClientHttp2Stream; + // #region InternalEventEmitter + addListener( + eventName: E, + listener: (...args: ClientHttp2StreamEventMap[E]) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: ClientHttp2StreamEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: ClientHttp2StreamEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners( + eventName: E, + ): ((...args: ClientHttp2StreamEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off( + eventName: E, + listener: (...args: ClientHttp2StreamEventMap[E]) => void, + ): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on( + eventName: E, + listener: (...args: ClientHttp2StreamEventMap[E]) => void, + ): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: (...args: ClientHttp2StreamEventMap[E]) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: ClientHttp2StreamEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: ClientHttp2StreamEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners( + eventName: E, + ): ((...args: ClientHttp2StreamEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: ClientHttp2StreamEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + interface AlternativeServiceOptions { + origin: number | string | url.URL; + } + interface ServerHttp2SessionEventMap< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends Http2SessionEventMap { + "connect": [ + session: ServerHttp2Session, + socket: net.Socket | tls.TLSSocket, + ]; + "stream": [stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number, rawHeaders: string[]]; + } + interface ServerHttp2Session< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends Http2Session { + readonly server: + | Http2Server + | Http2SecureServer; + /** + * Submits an `ALTSVC` frame (as defined by [RFC 7838](https://tools.ietf.org/html/rfc7838)) to the connected client. + * + * ```js + * import http2 from 'node:http2'; + * + * const server = http2.createServer(); + * server.on('session', (session) => { + * // Set altsvc for origin https://example.org:80 + * session.altsvc('h2=":8000"', 'https://example.org:80'); + * }); + * + * server.on('stream', (stream) => { + * // Set altsvc for a specific stream + * stream.session.altsvc('h2=":8000"', stream.id); + * }); + * ``` + * + * Sending an `ALTSVC` frame with a specific stream ID indicates that the alternate + * service is associated with the origin of the given `Http2Stream`. + * + * The `alt` and origin string _must_ contain only ASCII bytes and are + * strictly interpreted as a sequence of ASCII bytes. The special value `'clear'`may be passed to clear any previously set alternative service for a given + * domain. + * + * When a string is passed for the `originOrStream` argument, it will be parsed as + * a URL and the origin will be derived. For instance, the origin for the + * HTTP URL `'https://example.org/foo/bar'` is the ASCII string`'https://example.org'`. An error will be thrown if either the given string + * cannot be parsed as a URL or if a valid origin cannot be derived. + * + * A `URL` object, or any object with an `origin` property, may be passed as`originOrStream`, in which case the value of the `origin` property will be + * used. The value of the `origin` property _must_ be a properly serialized + * ASCII origin. + * @since v9.4.0 + * @param alt A description of the alternative service configuration as defined by `RFC 7838`. + * @param originOrStream Either a URL string specifying the origin (or an `Object` with an `origin` property) or the numeric identifier of an active `Http2Stream` as given by the + * `http2stream.id` property. + */ + altsvc(alt: string, originOrStream: number | string | url.URL | AlternativeServiceOptions): void; + /** + * Submits an `ORIGIN` frame (as defined by [RFC 8336](https://tools.ietf.org/html/rfc8336)) to the connected client + * to advertise the set of origins for which the server is capable of providing + * authoritative responses. + * + * ```js + * import http2 from 'node:http2'; + * const options = getSecureOptionsSomehow(); + * const server = http2.createSecureServer(options); + * server.on('stream', (stream) => { + * stream.respond(); + * stream.end('ok'); + * }); + * server.on('session', (session) => { + * session.origin('https://example.com', 'https://example.org'); + * }); + * ``` + * + * When a string is passed as an `origin`, it will be parsed as a URL and the + * origin will be derived. For instance, the origin for the HTTP URL `'https://example.org/foo/bar'` is the ASCII string` 'https://example.org'`. An error will be thrown if either the given + * string + * cannot be parsed as a URL or if a valid origin cannot be derived. + * + * A `URL` object, or any object with an `origin` property, may be passed as + * an `origin`, in which case the value of the `origin` property will be + * used. The value of the `origin` property _must_ be a properly serialized + * ASCII origin. + * + * Alternatively, the `origins` option may be used when creating a new HTTP/2 + * server using the `http2.createSecureServer()` method: + * + * ```js + * import http2 from 'node:http2'; + * const options = getSecureOptionsSomehow(); + * options.origins = ['https://example.com', 'https://example.org']; + * const server = http2.createSecureServer(options); + * server.on('stream', (stream) => { + * stream.respond(); + * stream.end('ok'); + * }); + * ``` + * @since v10.12.0 + * @param origins One or more URL Strings passed as separate arguments. + */ + origin( + ...origins: Array< + | string + | url.URL + | { + origin: string; + } + > + ): void; + // #region InternalEventEmitter + addListener( + eventName: E, + listener: ( + ...args: ServerHttp2SessionEventMap[E] + ) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit( + eventName: E, + ...args: ServerHttp2SessionEventMap[E] + ): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: ( + ...args: ServerHttp2SessionEventMap[E] + ) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners( + eventName: E, + ): (( + ...args: ServerHttp2SessionEventMap[E] + ) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off( + eventName: E, + listener: ( + ...args: ServerHttp2SessionEventMap[E] + ) => void, + ): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on( + eventName: E, + listener: ( + ...args: ServerHttp2SessionEventMap[E] + ) => void, + ): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: ( + ...args: ServerHttp2SessionEventMap[E] + ) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: ( + ...args: ServerHttp2SessionEventMap[E] + ) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: ( + ...args: ServerHttp2SessionEventMap[E] + ) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners( + eventName: E, + ): (( + ...args: ServerHttp2SessionEventMap[E] + ) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: ( + ...args: ServerHttp2SessionEventMap[E] + ) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + // Http2Server + interface SessionOptions { + /** + * Sets the maximum dynamic table size for deflating header fields. + * @default 4Kib + */ + maxDeflateDynamicTableSize?: number | undefined; + /** + * Sets the maximum number of settings entries per `SETTINGS` frame. + * The minimum value allowed is `1`. + * @default 32 + */ + maxSettings?: number | undefined; + /** + * Sets the maximum memory that the `Http2Session` is permitted to use. + * The value is expressed in terms of number of megabytes, e.g. `1` equal 1 megabyte. + * The minimum value allowed is `1`. + * This is a credit based limit, existing `Http2Stream`s may cause this limit to be exceeded, + * but new `Http2Stream` instances will be rejected while this limit is exceeded. + * The current number of `Http2Stream` sessions, the current memory use of the header compression tables, + * current data queued to be sent, and unacknowledged `PING` and `SETTINGS` frames are all counted towards the current limit. + * @default 10 + */ + maxSessionMemory?: number | undefined; + /** + * Sets the maximum number of header entries. + * This is similar to `server.maxHeadersCount` or `request.maxHeadersCount` in the `node:http` module. + * The minimum value is `1`. + * @default 128 + */ + maxHeaderListPairs?: number | undefined; + /** + * Sets the maximum number of outstanding, unacknowledged pings. + * @default 10 + */ + maxOutstandingPings?: number | undefined; + /** + * Sets the maximum allowed size for a serialized, compressed block of headers. + * Attempts to send headers that exceed this limit will result in + * a `'frameError'` event being emitted and the stream being closed and destroyed. + */ + maxSendHeaderBlockLength?: number | undefined; + /** + * Strategy used for determining the amount of padding to use for `HEADERS` and `DATA` frames. + * @default http2.constants.PADDING_STRATEGY_NONE + */ + paddingStrategy?: number | undefined; + /** + * Sets the maximum number of concurrent streams for the remote peer as if a `SETTINGS` frame had been received. + * Will be overridden if the remote peer sets its own value for `maxConcurrentStreams`. + * @default 100 + */ + peerMaxConcurrentStreams?: number | undefined; + /** + * The initial settings to send to the remote peer upon connection. + */ + settings?: Settings | undefined; + /** + * The array of integer values determines the settings types, + * which are included in the `CustomSettings`-property of the received remoteSettings. + * Please see the `CustomSettings`-property of the `Http2Settings` object for more information, on the allowed setting types. + */ + remoteCustomSettings?: number[] | undefined; + /** + * Specifies a timeout in milliseconds that + * a server should wait when an [`'unknownProtocol'`][] is emitted. If the + * socket has not been destroyed by that time the server will destroy it. + * @default 100000 + */ + unknownProtocolTimeout?: number | undefined; + /** + * If `true`, it turns on strict leading + * and trailing whitespace validation for HTTP/2 header field names and values + * as per [RFC-9113](https://www.rfc-editor.org/rfc/rfc9113.html#section-8.2.1). + * @since v24.2.0 + * @default true + */ + strictFieldWhitespaceValidation?: boolean | undefined; + } + interface ClientSessionOptions extends SessionOptions { + /** + * Sets the maximum number of reserved push streams the client will accept at any given time. + * Once the current number of currently reserved push streams exceeds reaches this limit, + * new push streams sent by the server will be automatically rejected. + * The minimum allowed value is 0. The maximum allowed value is 232-1. + * A negative value sets this option to the maximum allowed value. + * @default 200 + */ + maxReservedRemoteStreams?: number | undefined; + /** + * An optional callback that receives the `URL` instance passed to `connect` and the `options` object, + * and returns any `Duplex` stream that is to be used as the connection for this session. + */ + createConnection?: ((authority: url.URL, option: SessionOptions) => stream.Duplex) | undefined; + /** + * The protocol to connect with, if not set in the `authority`. + * Value may be either `'http:'` or `'https:'`. + * @default 'https:' + */ + protocol?: "http:" | "https:" | undefined; + } + interface ServerSessionOptions< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends SessionOptions { + streamResetBurst?: number | undefined; + streamResetRate?: number | undefined; + Http1IncomingMessage?: Http1Request | undefined; + Http1ServerResponse?: Http1Response | undefined; + Http2ServerRequest?: Http2Request | undefined; + Http2ServerResponse?: Http2Response | undefined; + } + interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions {} + interface SecureServerSessionOptions< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends ServerSessionOptions, tls.TlsOptions {} + interface ServerOptions< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends ServerSessionOptions {} + interface SecureServerOptions< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends SecureServerSessionOptions { + allowHTTP1?: boolean | undefined; + origins?: string[] | undefined; + } + interface Http2ServerCommon { + setTimeout(msec?: number, callback?: () => void): this; + /** + * Throws ERR_HTTP2_INVALID_SETTING_VALUE for invalid settings values. + * Throws ERR_INVALID_ARG_TYPE for invalid settings argument. + */ + updateSettings(settings: Settings): void; + } + interface Http2ServerEventMap< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends net.ServerEventMap, Pick { + "checkContinue": [request: InstanceType, response: InstanceType]; + "request": [request: InstanceType, response: InstanceType]; + "session": [session: ServerHttp2Session]; + "sessionError": [err: Error]; + } + interface Http2Server< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends net.Server, Http2ServerCommon { + // #region InternalEventEmitter + addListener( + eventName: E, + listener: ( + ...args: Http2ServerEventMap[E] + ) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit( + eventName: E, + ...args: Http2ServerEventMap[E] + ): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: ( + ...args: Http2ServerEventMap[E] + ) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners( + eventName: E, + ): ((...args: Http2ServerEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off( + eventName: E, + listener: ( + ...args: Http2ServerEventMap[E] + ) => void, + ): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on( + eventName: E, + listener: ( + ...args: Http2ServerEventMap[E] + ) => void, + ): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: ( + ...args: Http2ServerEventMap[E] + ) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: ( + ...args: Http2ServerEventMap[E] + ) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: ( + ...args: Http2ServerEventMap[E] + ) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners( + eventName: E, + ): ((...args: Http2ServerEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: ( + ...args: Http2ServerEventMap[E] + ) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + interface Http2SecureServerEventMap< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends tls.ServerEventMap, Http2ServerEventMap { + "unknownProtocol": [socket: tls.TLSSocket]; + } + interface Http2SecureServer< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends tls.Server, Http2ServerCommon { + // #region InternalEventEmitter + addListener( + eventName: E, + listener: ( + ...args: Http2SecureServerEventMap[E] + ) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit( + eventName: E, + ...args: Http2SecureServerEventMap[E] + ): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: ( + ...args: Http2SecureServerEventMap[E] + ) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners( + eventName: E, + ): (( + ...args: Http2SecureServerEventMap[E] + ) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off( + eventName: E, + listener: ( + ...args: Http2SecureServerEventMap[E] + ) => void, + ): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on( + eventName: E, + listener: ( + ...args: Http2SecureServerEventMap[E] + ) => void, + ): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: ( + ...args: Http2SecureServerEventMap[E] + ) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: ( + ...args: Http2SecureServerEventMap[E] + ) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: ( + ...args: Http2SecureServerEventMap[E] + ) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners( + eventName: E, + ): (( + ...args: Http2SecureServerEventMap[E] + ) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: ( + ...args: Http2SecureServerEventMap[E] + ) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + interface Http2ServerRequestEventMap extends stream.ReadableEventMap { + "aborted": [hadError: boolean, code: number]; + "data": [chunk: string | NonSharedBuffer]; + } + /** + * A `Http2ServerRequest` object is created by {@link Server} or {@link SecureServer} and passed as the first argument to the `'request'` event. It may be used to access a request status, + * headers, and + * data. + * @since v8.4.0 + */ + class Http2ServerRequest extends stream.Readable { + constructor( + stream: ServerHttp2Stream, + headers: IncomingHttpHeaders, + options: stream.ReadableOptions, + rawHeaders: readonly string[], + ); + /** + * The `request.aborted` property will be `true` if the request has + * been aborted. + * @since v10.1.0 + */ + readonly aborted: boolean; + /** + * The request authority pseudo header field. Because HTTP/2 allows requests + * to set either `:authority` or `host`, this value is derived from `req.headers[':authority']` if present. Otherwise, it is derived from `req.headers['host']`. + * @since v8.4.0 + */ + readonly authority: string; + /** + * See `request.socket`. + * @since v8.4.0 + * @deprecated Since v13.0.0 - Use `socket`. + */ + readonly connection: net.Socket | tls.TLSSocket; + /** + * The `request.complete` property will be `true` if the request has + * been completed, aborted, or destroyed. + * @since v12.10.0 + */ + readonly complete: boolean; + /** + * The request/response headers object. + * + * Key-value pairs of header names and values. Header names are lower-cased. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': 'curl/7.22.0', + * // host: '127.0.0.1:8000', + * // accept: '*' } + * console.log(request.headers); + * ``` + * + * See `HTTP/2 Headers Object`. + * + * In HTTP/2, the request path, host name, protocol, and method are represented as + * special headers prefixed with the `:` character (e.g. `':path'`). These special + * headers will be included in the `request.headers` object. Care must be taken not + * to inadvertently modify these special headers or errors may occur. For instance, + * removing all headers from the request will cause errors to occur: + * + * ```js + * removeAllHeaders(request.headers); + * assert(request.url); // Fails because the :path header has been removed + * ``` + * @since v8.4.0 + */ + readonly headers: IncomingHttpHeaders; + /** + * In case of server request, the HTTP version sent by the client. In the case of + * client response, the HTTP version of the connected-to server. Returns `'2.0'`. + * + * Also `message.httpVersionMajor` is the first integer and `message.httpVersionMinor` is the second. + * @since v8.4.0 + */ + readonly httpVersion: string; + readonly httpVersionMinor: number; + readonly httpVersionMajor: number; + /** + * The request method as a string. Read-only. Examples: `'GET'`, `'DELETE'`. + * @since v8.4.0 + */ + readonly method: string; + /** + * The raw request/response headers list exactly as they were received. + * + * The keys and values are in the same list. It is _not_ a + * list of tuples. So, the even-numbered offsets are key values, and the + * odd-numbered offsets are the associated values. + * + * Header names are not lowercased, and duplicates are not merged. + * + * ```js + * // Prints something like: + * // + * // [ 'user-agent', + * // 'this is invalid because there can be only one', + * // 'User-Agent', + * // 'curl/7.22.0', + * // 'Host', + * // '127.0.0.1:8000', + * // 'ACCEPT', + * // '*' ] + * console.log(request.rawHeaders); + * ``` + * @since v8.4.0 + */ + readonly rawHeaders: string[]; + /** + * The raw request/response trailer keys and values exactly as they were + * received. Only populated at the `'end'` event. + * @since v8.4.0 + */ + readonly rawTrailers: string[]; + /** + * The request scheme pseudo header field indicating the scheme + * portion of the target URL. + * @since v8.4.0 + */ + readonly scheme: string; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * applies getters, setters, and methods based on HTTP/2 logic. + * + * `destroyed`, `readable`, and `writable` properties will be retrieved from and + * set on `request.stream`. + * + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on `request.stream`. + * + * `setTimeout` method will be called on `request.stream.session`. + * + * `pause`, `read`, `resume`, and `write` will throw an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * more information. + * + * All other interactions will be routed directly to the socket. With TLS support, + * use `request.socket.getPeerCertificate()` to obtain the client's + * authentication details. + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * The `Http2Stream` object backing the request. + * @since v8.4.0 + */ + readonly stream: ServerHttp2Stream; + /** + * The request/response trailers object. Only populated at the `'end'` event. + * @since v8.4.0 + */ + readonly trailers: IncomingHttpHeaders; + /** + * Request URL string. This contains only the URL that is present in the actual + * HTTP request. If the request is: + * + * ```http + * GET /status?name=ryan HTTP/1.1 + * Accept: text/plain + * ``` + * + * Then `request.url` will be: + * + * ```js + * '/status?name=ryan' + * ``` + * + * To parse the url into its parts, `new URL()` can be used: + * + * ```console + * $ node + * > new URL('/status?name=ryan', 'http://example.com') + * URL { + * href: 'http://example.com/status?name=ryan', + * origin: 'http://example.com', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'example.com', + * hostname: 'example.com', + * port: '', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * @since v8.4.0 + */ + url: string; + /** + * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is + * provided, then it is added as a listener on the `'timeout'` event on + * the response object. + * + * If no `'timeout'` listener is added to the request, the response, or + * the server, then `Http2Stream`s are destroyed when they time out. If a + * handler is assigned to the request, the response, or the server's `'timeout'`events, timed out sockets must be handled explicitly. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + read(size?: number): Buffer | string | null; + // #region InternalEventEmitter + addListener( + eventName: E, + listener: (...args: Http2ServerRequestEventMap[E]) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: Http2ServerRequestEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: Http2ServerRequestEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners( + eventName: E, + ): ((...args: Http2ServerRequestEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off( + eventName: E, + listener: (...args: Http2ServerRequestEventMap[E]) => void, + ): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on( + eventName: E, + listener: (...args: Http2ServerRequestEventMap[E]) => void, + ): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: (...args: Http2ServerRequestEventMap[E]) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: Http2ServerRequestEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: Http2ServerRequestEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners( + eventName: E, + ): ((...args: Http2ServerRequestEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: Http2ServerRequestEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + /** + * This object is created internally by an HTTP server, not by the user. It is + * passed as the second parameter to the `'request'` event. + * @since v8.4.0 + */ + class Http2ServerResponse extends stream.Writable { + constructor(stream: ServerHttp2Stream); + /** + * See `response.socket`. + * @since v8.4.0 + * @deprecated Since v13.0.0 - Use `socket`. + */ + readonly connection: net.Socket | tls.TLSSocket; + /** + * Append a single header value to the header object. + * + * If the value is an array, this is equivalent to calling this method multiple times. + * + * If there were no previous values for the header, this is equivalent to calling {@link setHeader}. + * + * Attempting to set a header field name or value that contains invalid characters will result in a + * [TypeError](https://nodejs.org/docs/latest-v25.x/api/errors.html#class-typeerror) being thrown. + * + * ```js + * // Returns headers including "set-cookie: a" and "set-cookie: b" + * const server = http2.createServer((req, res) => { + * res.setHeader('set-cookie', 'a'); + * res.appendHeader('set-cookie', 'b'); + * res.writeHead(200); + * res.end('ok'); + * }); + * ``` + * @since v20.12.0 + */ + appendHeader(name: string, value: string | string[]): void; + /** + * Boolean value that indicates whether the response has completed. Starts + * as `false`. After `response.end()` executes, the value will be `true`. + * @since v8.4.0 + * @deprecated Since v13.4.0,v12.16.0 - Use `writableEnded`. + */ + readonly finished: boolean; + /** + * True if headers were sent, false otherwise (read-only). + * @since v8.4.0 + */ + readonly headersSent: boolean; + /** + * A reference to the original HTTP2 `request` object. + * @since v15.7.0 + */ + readonly req: Request; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * applies getters, setters, and methods based on HTTP/2 logic. + * + * `destroyed`, `readable`, and `writable` properties will be retrieved from and + * set on `response.stream`. + * + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on `response.stream`. + * + * `setTimeout` method will be called on `response.stream.session`. + * + * `pause`, `read`, `resume`, and `write` will throw an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * more information. + * + * All other interactions will be routed directly to the socket. + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer((req, res) => { + * const ip = req.socket.remoteAddress; + * const port = req.socket.remotePort; + * res.end(`Your IP address is ${ip} and your source port is ${port}.`); + * }).listen(3000); + * ``` + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * The `Http2Stream` object backing the response. + * @since v8.4.0 + */ + readonly stream: ServerHttp2Stream; + /** + * When true, the Date header will be automatically generated and sent in + * the response if it is not already present in the headers. Defaults to true. + * + * This should only be disabled for testing; HTTP requires the Date header + * in responses. + * @since v8.4.0 + */ + sendDate: boolean; + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status code that will be sent to the client when + * the headers get flushed. + * + * ```js + * response.statusCode = 404; + * ``` + * + * After response header was sent to the client, this property indicates the + * status code which was sent out. + * @since v8.4.0 + */ + statusCode: number; + /** + * Status message is not supported by HTTP/2 (RFC 7540 8.1.2.4). It returns + * an empty string. + * @since v8.4.0 + */ + statusMessage: ""; + /** + * This method adds HTTP trailing headers (a header but at the end of the + * message) to the response. + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v8.4.0 + */ + addTrailers(trailers: OutgoingHttpHeaders): void; + /** + * This method signals to the server that all of the response headers and body + * have been sent; that server should consider this message complete. + * The method, `response.end()`, MUST be called on each response. + * + * If `data` is specified, it is equivalent to calling `response.write(data, encoding)` followed by `response.end(callback)`. + * + * If `callback` is specified, it will be called when the response stream + * is finished. + * @since v8.4.0 + */ + end(callback?: () => void): this; + end(data: string | Uint8Array, callback?: () => void): this; + end(data: string | Uint8Array, encoding: BufferEncoding, callback?: () => void): this; + /** + * Reads out a header that has already been queued but not sent to the client. + * The name is case-insensitive. + * + * ```js + * const contentType = response.getHeader('content-type'); + * ``` + * @since v8.4.0 + */ + getHeader(name: string): string; + /** + * Returns an array containing the unique names of the current outgoing headers. + * All header names are lowercase. + * + * ```js + * response.setHeader('Foo', 'bar'); + * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headerNames = response.getHeaderNames(); + * // headerNames === ['foo', 'set-cookie'] + * ``` + * @since v8.4.0 + */ + getHeaderNames(): string[]; + /** + * Returns a shallow copy of the current outgoing headers. Since a shallow copy + * is used, array values may be mutated without additional calls to various + * header-related http module methods. The keys of the returned object are the + * header names and the values are the respective header values. All header names + * are lowercase. + * + * The object returned by the `response.getHeaders()` method _does not_ prototypically inherit from the JavaScript `Object`. This means that typical `Object` methods such as `obj.toString()`, + * `obj.hasOwnProperty()`, and others + * are not defined and _will not work_. + * + * ```js + * response.setHeader('Foo', 'bar'); + * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headers = response.getHeaders(); + * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } + * ``` + * @since v8.4.0 + */ + getHeaders(): OutgoingHttpHeaders; + /** + * Returns `true` if the header identified by `name` is currently set in the + * outgoing headers. The header name matching is case-insensitive. + * + * ```js + * const hasContentType = response.hasHeader('content-type'); + * ``` + * @since v8.4.0 + */ + hasHeader(name: string): boolean; + /** + * Removes a header that has been queued for implicit sending. + * + * ```js + * response.removeHeader('Content-Encoding'); + * ``` + * @since v8.4.0 + */ + removeHeader(name: string): void; + /** + * Sets a single header value for implicit headers. If this header already exists + * in the to-be-sent headers, its value will be replaced. Use an array of strings + * here to send multiple headers with the same name. + * + * ```js + * response.setHeader('Content-Type', 'text/html; charset=utf-8'); + * ``` + * + * or + * + * ```js + * response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http2.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html; charset=utf-8'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); + * res.end('ok'); + * }); + * ``` + * @since v8.4.0 + */ + setHeader(name: string, value: number | string | readonly string[]): void; + /** + * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is + * provided, then it is added as a listener on the `'timeout'` event on + * the response object. + * + * If no `'timeout'` listener is added to the request, the response, or + * the server, then `Http2Stream` s are destroyed when they time out. If a + * handler is assigned to the request, the response, or the server's `'timeout'` events, timed out sockets must be handled explicitly. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * If this method is called and `response.writeHead()` has not been called, + * it will switch to implicit header mode and flush the implicit headers. + * + * This sends a chunk of the response body. This method may + * be called multiple times to provide successive parts of the body. + * + * In the `node:http` module, the response body is omitted when the + * request is a HEAD request. Similarly, the `204` and `304` responses _must not_ include a message body. + * + * `chunk` can be a string or a buffer. If `chunk` is a string, + * the second parameter specifies how to encode it into a byte stream. + * By default the `encoding` is `'utf8'`. `callback` will be called when this chunk + * of data is flushed. + * + * This is the raw HTTP body and has nothing to do with higher-level multi-part + * body encodings that may be used. + * + * The first time `response.write()` is called, it will send the buffered + * header information and the first chunk of the body to the client. The second + * time `response.write()` is called, Node.js assumes data will be streamed, + * and sends the new data separately. That is, the response is buffered up to the + * first chunk of the body. + * + * Returns `true` if the entire data was flushed successfully to the kernel + * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is free again. + * @since v8.4.0 + */ + write(chunk: string | Uint8Array, callback?: (err: Error) => void): boolean; + write(chunk: string | Uint8Array, encoding: BufferEncoding, callback?: (err: Error) => void): boolean; + /** + * Sends a status `100 Continue` to the client, indicating that the request body + * should be sent. See the `'checkContinue'` event on `Http2Server` and `Http2SecureServer`. + * @since v8.4.0 + */ + writeContinue(): void; + /** + * Sends a status `103 Early Hints` to the client with a Link header, + * indicating that the user agent can preload/preconnect the linked resources. + * The `hints` is an object containing the values of headers to be sent with + * early hints message. + * + * **Example** + * + * ```js + * const earlyHintsLink = '; rel=preload; as=style'; + * response.writeEarlyHints({ + * 'link': earlyHintsLink, + * }); + * + * const earlyHintsLinks = [ + * '; rel=preload; as=style', + * '; rel=preload; as=script', + * ]; + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * }); + * ``` + * @since v18.11.0 + */ + writeEarlyHints(hints: Record): void; + /** + * Sends a response header to the request. The status code is a 3-digit HTTP + * status code, like `404`. The last argument, `headers`, are the response headers. + * + * Returns a reference to the `Http2ServerResponse`, so that calls can be chained. + * + * For compatibility with `HTTP/1`, a human-readable `statusMessage` may be + * passed as the second argument. However, because the `statusMessage` has no + * meaning within HTTP/2, the argument will have no effect and a process warning + * will be emitted. + * + * ```js + * const body = 'hello world'; + * response.writeHead(200, { + * 'Content-Length': Buffer.byteLength(body), + * 'Content-Type': 'text/plain; charset=utf-8', + * }); + * ``` + * + * `Content-Length` is given in bytes not characters. The`Buffer.byteLength()` API may be used to determine the number of bytes in a + * given encoding. On outbound messages, Node.js does not check if Content-Length + * and the length of the body being transmitted are equal or not. However, when + * receiving messages, Node.js will automatically reject messages when the `Content-Length` does not match the actual payload size. + * + * This method may be called at most one time on a message before `response.end()` is called. + * + * If `response.write()` or `response.end()` are called before calling + * this, the implicit/mutable headers will be calculated and call this function. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http2.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html; charset=utf-8'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); + * res.end('ok'); + * }); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v8.4.0 + */ + writeHead(statusCode: number, headers?: OutgoingHttpHeaders | readonly string[]): this; + writeHead(statusCode: number, statusMessage: string, headers?: OutgoingHttpHeaders | readonly string[]): this; + /** + * Call `http2stream.pushStream()` with the given headers, and wrap the + * given `Http2Stream` on a newly created `Http2ServerResponse` as the callback + * parameter if successful. When `Http2ServerRequest` is closed, the callback is + * called with an error `ERR_HTTP2_INVALID_STREAM`. + * @since v8.4.0 + * @param headers An object describing the headers + * @param callback Called once `http2stream.pushStream()` is finished, or either when the attempt to create the pushed `Http2Stream` has failed or has been rejected, or the state of + * `Http2ServerRequest` is closed prior to calling the `http2stream.pushStream()` method + */ + createPushResponse( + headers: OutgoingHttpHeaders, + callback: (err: Error | null, res: Http2ServerResponse) => void, + ): void; + } + namespace constants { + const NGHTTP2_SESSION_SERVER: number; + const NGHTTP2_SESSION_CLIENT: number; + const NGHTTP2_STREAM_STATE_IDLE: number; + const NGHTTP2_STREAM_STATE_OPEN: number; + const NGHTTP2_STREAM_STATE_RESERVED_LOCAL: number; + const NGHTTP2_STREAM_STATE_RESERVED_REMOTE: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: number; + const NGHTTP2_STREAM_STATE_CLOSED: number; + const NGHTTP2_NO_ERROR: number; + const NGHTTP2_PROTOCOL_ERROR: number; + const NGHTTP2_INTERNAL_ERROR: number; + const NGHTTP2_FLOW_CONTROL_ERROR: number; + const NGHTTP2_SETTINGS_TIMEOUT: number; + const NGHTTP2_STREAM_CLOSED: number; + const NGHTTP2_FRAME_SIZE_ERROR: number; + const NGHTTP2_REFUSED_STREAM: number; + const NGHTTP2_CANCEL: number; + const NGHTTP2_COMPRESSION_ERROR: number; + const NGHTTP2_CONNECT_ERROR: number; + const NGHTTP2_ENHANCE_YOUR_CALM: number; + const NGHTTP2_INADEQUATE_SECURITY: number; + const NGHTTP2_HTTP_1_1_REQUIRED: number; + const NGHTTP2_ERR_FRAME_SIZE_ERROR: number; + const NGHTTP2_FLAG_NONE: number; + const NGHTTP2_FLAG_END_STREAM: number; + const NGHTTP2_FLAG_END_HEADERS: number; + const NGHTTP2_FLAG_ACK: number; + const NGHTTP2_FLAG_PADDED: number; + const NGHTTP2_FLAG_PRIORITY: number; + const DEFAULT_SETTINGS_HEADER_TABLE_SIZE: number; + const DEFAULT_SETTINGS_ENABLE_PUSH: number; + const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: number; + const DEFAULT_SETTINGS_MAX_FRAME_SIZE: number; + const MAX_MAX_FRAME_SIZE: number; + const MIN_MAX_FRAME_SIZE: number; + const MAX_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_DEFAULT_WEIGHT: number; + const NGHTTP2_SETTINGS_HEADER_TABLE_SIZE: number; + const NGHTTP2_SETTINGS_ENABLE_PUSH: number; + const NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: number; + const NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_SETTINGS_MAX_FRAME_SIZE: number; + const NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: number; + const PADDING_STRATEGY_NONE: number; + const PADDING_STRATEGY_MAX: number; + const PADDING_STRATEGY_CALLBACK: number; + const HTTP2_HEADER_STATUS: string; + const HTTP2_HEADER_METHOD: string; + const HTTP2_HEADER_AUTHORITY: string; + const HTTP2_HEADER_SCHEME: string; + const HTTP2_HEADER_PATH: string; + const HTTP2_HEADER_ACCEPT_CHARSET: string; + const HTTP2_HEADER_ACCEPT_ENCODING: string; + const HTTP2_HEADER_ACCEPT_LANGUAGE: string; + const HTTP2_HEADER_ACCEPT_RANGES: string; + const HTTP2_HEADER_ACCEPT: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_HEADERS: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_METHODS: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string; + const HTTP2_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS: string; + const HTTP2_HEADER_ACCESS_CONTROL_REQUEST_HEADERS: string; + const HTTP2_HEADER_ACCESS_CONTROL_REQUEST_METHOD: string; + const HTTP2_HEADER_AGE: string; + const HTTP2_HEADER_ALLOW: string; + const HTTP2_HEADER_AUTHORIZATION: string; + const HTTP2_HEADER_CACHE_CONTROL: string; + const HTTP2_HEADER_CONNECTION: string; + const HTTP2_HEADER_CONTENT_DISPOSITION: string; + const HTTP2_HEADER_CONTENT_ENCODING: string; + const HTTP2_HEADER_CONTENT_LANGUAGE: string; + const HTTP2_HEADER_CONTENT_LENGTH: string; + const HTTP2_HEADER_CONTENT_LOCATION: string; + const HTTP2_HEADER_CONTENT_MD5: string; + const HTTP2_HEADER_CONTENT_RANGE: string; + const HTTP2_HEADER_CONTENT_TYPE: string; + const HTTP2_HEADER_COOKIE: string; + const HTTP2_HEADER_DATE: string; + const HTTP2_HEADER_ETAG: string; + const HTTP2_HEADER_EXPECT: string; + const HTTP2_HEADER_EXPIRES: string; + const HTTP2_HEADER_FROM: string; + const HTTP2_HEADER_HOST: string; + const HTTP2_HEADER_IF_MATCH: string; + const HTTP2_HEADER_IF_MODIFIED_SINCE: string; + const HTTP2_HEADER_IF_NONE_MATCH: string; + const HTTP2_HEADER_IF_RANGE: string; + const HTTP2_HEADER_IF_UNMODIFIED_SINCE: string; + const HTTP2_HEADER_LAST_MODIFIED: string; + const HTTP2_HEADER_LINK: string; + const HTTP2_HEADER_LOCATION: string; + const HTTP2_HEADER_MAX_FORWARDS: string; + const HTTP2_HEADER_PREFER: string; + const HTTP2_HEADER_PROXY_AUTHENTICATE: string; + const HTTP2_HEADER_PROXY_AUTHORIZATION: string; + const HTTP2_HEADER_RANGE: string; + const HTTP2_HEADER_REFERER: string; + const HTTP2_HEADER_REFRESH: string; + const HTTP2_HEADER_RETRY_AFTER: string; + const HTTP2_HEADER_SERVER: string; + const HTTP2_HEADER_SET_COOKIE: string; + const HTTP2_HEADER_STRICT_TRANSPORT_SECURITY: string; + const HTTP2_HEADER_TRANSFER_ENCODING: string; + const HTTP2_HEADER_TE: string; + const HTTP2_HEADER_UPGRADE: string; + const HTTP2_HEADER_USER_AGENT: string; + const HTTP2_HEADER_VARY: string; + const HTTP2_HEADER_VIA: string; + const HTTP2_HEADER_WWW_AUTHENTICATE: string; + const HTTP2_HEADER_HTTP2_SETTINGS: string; + const HTTP2_HEADER_KEEP_ALIVE: string; + const HTTP2_HEADER_PROXY_CONNECTION: string; + const HTTP2_METHOD_ACL: string; + const HTTP2_METHOD_BASELINE_CONTROL: string; + const HTTP2_METHOD_BIND: string; + const HTTP2_METHOD_CHECKIN: string; + const HTTP2_METHOD_CHECKOUT: string; + const HTTP2_METHOD_CONNECT: string; + const HTTP2_METHOD_COPY: string; + const HTTP2_METHOD_DELETE: string; + const HTTP2_METHOD_GET: string; + const HTTP2_METHOD_HEAD: string; + const HTTP2_METHOD_LABEL: string; + const HTTP2_METHOD_LINK: string; + const HTTP2_METHOD_LOCK: string; + const HTTP2_METHOD_MERGE: string; + const HTTP2_METHOD_MKACTIVITY: string; + const HTTP2_METHOD_MKCALENDAR: string; + const HTTP2_METHOD_MKCOL: string; + const HTTP2_METHOD_MKREDIRECTREF: string; + const HTTP2_METHOD_MKWORKSPACE: string; + const HTTP2_METHOD_MOVE: string; + const HTTP2_METHOD_OPTIONS: string; + const HTTP2_METHOD_ORDERPATCH: string; + const HTTP2_METHOD_PATCH: string; + const HTTP2_METHOD_POST: string; + const HTTP2_METHOD_PRI: string; + const HTTP2_METHOD_PROPFIND: string; + const HTTP2_METHOD_PROPPATCH: string; + const HTTP2_METHOD_PUT: string; + const HTTP2_METHOD_REBIND: string; + const HTTP2_METHOD_REPORT: string; + const HTTP2_METHOD_SEARCH: string; + const HTTP2_METHOD_TRACE: string; + const HTTP2_METHOD_UNBIND: string; + const HTTP2_METHOD_UNCHECKOUT: string; + const HTTP2_METHOD_UNLINK: string; + const HTTP2_METHOD_UNLOCK: string; + const HTTP2_METHOD_UPDATE: string; + const HTTP2_METHOD_UPDATEREDIRECTREF: string; + const HTTP2_METHOD_VERSION_CONTROL: string; + const HTTP_STATUS_CONTINUE: number; + const HTTP_STATUS_SWITCHING_PROTOCOLS: number; + const HTTP_STATUS_PROCESSING: number; + const HTTP_STATUS_OK: number; + const HTTP_STATUS_CREATED: number; + const HTTP_STATUS_ACCEPTED: number; + const HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: number; + const HTTP_STATUS_NO_CONTENT: number; + const HTTP_STATUS_RESET_CONTENT: number; + const HTTP_STATUS_PARTIAL_CONTENT: number; + const HTTP_STATUS_MULTI_STATUS: number; + const HTTP_STATUS_ALREADY_REPORTED: number; + const HTTP_STATUS_IM_USED: number; + const HTTP_STATUS_MULTIPLE_CHOICES: number; + const HTTP_STATUS_MOVED_PERMANENTLY: number; + const HTTP_STATUS_FOUND: number; + const HTTP_STATUS_SEE_OTHER: number; + const HTTP_STATUS_NOT_MODIFIED: number; + const HTTP_STATUS_USE_PROXY: number; + const HTTP_STATUS_TEMPORARY_REDIRECT: number; + const HTTP_STATUS_PERMANENT_REDIRECT: number; + const HTTP_STATUS_BAD_REQUEST: number; + const HTTP_STATUS_UNAUTHORIZED: number; + const HTTP_STATUS_PAYMENT_REQUIRED: number; + const HTTP_STATUS_FORBIDDEN: number; + const HTTP_STATUS_NOT_FOUND: number; + const HTTP_STATUS_METHOD_NOT_ALLOWED: number; + const HTTP_STATUS_NOT_ACCEPTABLE: number; + const HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: number; + const HTTP_STATUS_REQUEST_TIMEOUT: number; + const HTTP_STATUS_CONFLICT: number; + const HTTP_STATUS_GONE: number; + const HTTP_STATUS_LENGTH_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_FAILED: number; + const HTTP_STATUS_PAYLOAD_TOO_LARGE: number; + const HTTP_STATUS_URI_TOO_LONG: number; + const HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: number; + const HTTP_STATUS_RANGE_NOT_SATISFIABLE: number; + const HTTP_STATUS_EXPECTATION_FAILED: number; + const HTTP_STATUS_TEAPOT: number; + const HTTP_STATUS_MISDIRECTED_REQUEST: number; + const HTTP_STATUS_UNPROCESSABLE_ENTITY: number; + const HTTP_STATUS_LOCKED: number; + const HTTP_STATUS_FAILED_DEPENDENCY: number; + const HTTP_STATUS_UNORDERED_COLLECTION: number; + const HTTP_STATUS_UPGRADE_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_REQUIRED: number; + const HTTP_STATUS_TOO_MANY_REQUESTS: number; + const HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: number; + const HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: number; + const HTTP_STATUS_INTERNAL_SERVER_ERROR: number; + const HTTP_STATUS_NOT_IMPLEMENTED: number; + const HTTP_STATUS_BAD_GATEWAY: number; + const HTTP_STATUS_SERVICE_UNAVAILABLE: number; + const HTTP_STATUS_GATEWAY_TIMEOUT: number; + const HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: number; + const HTTP_STATUS_VARIANT_ALSO_NEGOTIATES: number; + const HTTP_STATUS_INSUFFICIENT_STORAGE: number; + const HTTP_STATUS_LOOP_DETECTED: number; + const HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: number; + const HTTP_STATUS_NOT_EXTENDED: number; + const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: number; + } + /** + * This symbol can be set as a property on the HTTP/2 headers object with + * an array value in order to provide a list of headers considered sensitive. + */ + const sensitiveHeaders: symbol; + /** + * Returns an object containing the default settings for an `Http2Session` instance. This method returns a new object instance every time it is called + * so instances returned may be safely modified for use. + * @since v8.4.0 + */ + function getDefaultSettings(): Settings; + /** + * Returns a `Buffer` instance containing serialized representation of the given + * HTTP/2 settings as specified in the [HTTP/2](https://tools.ietf.org/html/rfc7540) specification. This is intended + * for use with the `HTTP2-Settings` header field. + * + * ```js + * import http2 from 'node:http2'; + * + * const packed = http2.getPackedSettings({ enablePush: false }); + * + * console.log(packed.toString('base64')); + * // Prints: AAIAAAAA + * ``` + * @since v8.4.0 + */ + function getPackedSettings(settings: Settings): NonSharedBuffer; + /** + * Returns a `HTTP/2 Settings Object` containing the deserialized settings from + * the given `Buffer` as generated by `http2.getPackedSettings()`. + * @since v8.4.0 + * @param buf The packed settings. + */ + function getUnpackedSettings(buf: Uint8Array): Settings; + /** + * Returns a `net.Server` instance that creates and manages `Http2Session` instances. + * + * Since there are no browsers known that support [unencrypted HTTP/2](https://http2.github.io/faq/#does-http2-require-encryption), the use of {@link createSecureServer} is necessary when + * communicating + * with browser clients. + * + * ```js + * import http2 from 'node:http2'; + * + * // Create an unencrypted HTTP/2 server. + * // Since there are no browsers known that support + * // unencrypted HTTP/2, the use of `http2.createSecureServer()` + * // is necessary when communicating with browser clients. + * const server = http2.createServer(); + * + * server.on('stream', (stream, headers) => { + * stream.respond({ + * 'content-type': 'text/html; charset=utf-8', + * ':status': 200, + * }); + * stream.end('

Hello World

'); + * }); + * + * server.listen(8000); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + function createServer( + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2Server; + function createServer< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + >( + options: ServerOptions, + onRequestHandler?: (request: InstanceType, response: InstanceType) => void, + ): Http2Server; + /** + * Returns a `tls.Server` instance that creates and manages `Http2Session` instances. + * + * ```js + * import http2 from 'node:http2'; + * import fs from 'node:fs'; + * + * const options = { + * key: fs.readFileSync('server-key.pem'), + * cert: fs.readFileSync('server-cert.pem'), + * }; + * + * // Create a secure HTTP/2 server + * const server = http2.createSecureServer(options); + * + * server.on('stream', (stream, headers) => { + * stream.respond({ + * 'content-type': 'text/html; charset=utf-8', + * ':status': 200, + * }); + * stream.end('

Hello World

'); + * }); + * + * server.listen(8443); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + function createSecureServer( + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2SecureServer; + function createSecureServer< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + >( + options: SecureServerOptions, + onRequestHandler?: (request: InstanceType, response: InstanceType) => void, + ): Http2SecureServer; + /** + * Returns a `ClientHttp2Session` instance. + * + * ```js + * import http2 from 'node:http2'; + * const client = http2.connect('https://localhost:1234'); + * + * // Use the client + * + * client.close(); + * ``` + * @since v8.4.0 + * @param authority The remote HTTP/2 server to connect to. This must be in the form of a minimal, valid URL with the `http://` or `https://` prefix, host name, and IP port (if a non-default port + * is used). Userinfo (user ID and password), path, querystring, and fragment details in the URL will be ignored. + * @param listener Will be registered as a one-time listener of the {@link 'connect'} event. + */ + function connect( + authority: string | url.URL, + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): ClientHttp2Session; + function connect( + authority: string | url.URL, + options?: ClientSessionOptions | SecureClientSessionOptions, + listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): ClientHttp2Session; + /** + * Create an HTTP/2 server session from an existing socket. + * @param socket A Duplex Stream + * @param options Any `{@link createServer}` options can be provided. + * @since v20.12.0 + */ + function performServerHandshake< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + >( + socket: stream.Duplex, + options?: ServerOptions, + ): ServerHttp2Session; +} +declare module "node:http2" { + export { OutgoingHttpHeaders } from "node:http"; +} +declare module "http2" { + export * from "node:http2"; +} diff --git a/backend/node_modules/@types/node/https.d.ts b/backend/node_modules/@types/node/https.d.ts new file mode 100644 index 0000000..c4fbe8c --- /dev/null +++ b/backend/node_modules/@types/node/https.d.ts @@ -0,0 +1,399 @@ +/** + * HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a + * separate module. + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/https.js) + */ +declare module "node:https" { + import * as http from "node:http"; + import { Duplex } from "node:stream"; + import * as tls from "node:tls"; + import { URL } from "node:url"; + interface ServerOptions< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse> = typeof http.ServerResponse, + > extends http.ServerOptions, tls.TlsOptions {} + interface RequestOptions extends http.RequestOptions, tls.SecureContextOptions { + checkServerIdentity?: + | ((hostname: string, cert: tls.DetailedPeerCertificate) => Error | undefined) + | undefined; + rejectUnauthorized?: boolean | undefined; // Defaults to true + servername?: string | undefined; // SNI TLS Extension + } + interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions { + maxCachedSessions?: number | undefined; + } + /** + * An `Agent` object for HTTPS similar to `http.Agent`. See {@link request} for more information. + * @since v0.4.5 + */ + class Agent extends http.Agent { + constructor(options?: AgentOptions); + options: AgentOptions; + createConnection( + options: RequestOptions, + callback?: (err: Error | null, stream: Duplex) => void, + ): Duplex | null | undefined; + getName(options?: RequestOptions): string; + } + interface ServerEventMap< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse> = typeof http.ServerResponse, + > extends http.ServerEventMap, tls.ServerEventMap {} + /** + * See `http.Server` for more information. + * @since v0.3.4 + */ + class Server< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse> = typeof http.ServerResponse, + > extends tls.Server { + constructor(requestListener?: http.RequestListener); + constructor( + options: ServerOptions, + requestListener?: http.RequestListener, + ); + /** + * Closes all connections connected to this server. + * @since v18.2.0 + */ + closeAllConnections(): void; + /** + * Closes all connections connected to this server which are not sending a request or waiting for a response. + * @since v18.2.0 + */ + closeIdleConnections(): void; + // #region InternalEventEmitter + addListener( + eventName: E, + listener: (...args: ServerEventMap[E]) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: ServerEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: ServerEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners( + eventName: E, + ): ((...args: ServerEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off( + eventName: E, + listener: (...args: ServerEventMap[E]) => void, + ): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on( + eventName: E, + listener: (...args: ServerEventMap[E]) => void, + ): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: (...args: ServerEventMap[E]) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: ServerEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: ServerEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners( + eventName: E, + ): ((...args: ServerEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: ServerEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + interface Server< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse> = typeof http.ServerResponse, + > extends http.Server {} + /** + * ```js + * // curl -k https://localhost:8000/ + * import https from 'node:https'; + * import fs from 'node:fs'; + * + * const options = { + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * }; + * + * https.createServer(options, (req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * ``` + * + * Or + * + * ```js + * import https from 'node:https'; + * import fs from 'node:fs'; + * + * const options = { + * pfx: fs.readFileSync('test/fixtures/test_cert.pfx'), + * passphrase: 'sample', + * }; + * + * https.createServer(options, (req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * ``` + * @since v0.3.4 + * @param options Accepts `options` from `createServer`, `createSecureContext` and `createServer`. + * @param requestListener A listener to be added to the `'request'` event. + */ + function createServer< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse> = typeof http.ServerResponse, + >(requestListener?: http.RequestListener): Server; + function createServer< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse> = typeof http.ServerResponse, + >( + options: ServerOptions, + requestListener?: http.RequestListener, + ): Server; + /** + * Makes a request to a secure web server. + * + * The following additional `options` from `tls.connect()` are also accepted: `ca`, `cert`, `ciphers`, `clientCertEngine`, `crl`, `dhparam`, `ecdhCurve`, `honorCipherOrder`, `key`, `passphrase`, + * `pfx`, `rejectUnauthorized`, `secureOptions`, `secureProtocol`, `servername`, `sessionIdContext`, `highWaterMark`. + * + * `options` can be an object, a string, or a `URL` object. If `options` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * `https.request()` returns an instance of the `http.ClientRequest` class. The `ClientRequest` instance is a writable stream. If one needs to + * upload a file with a POST request, then write to the `ClientRequest` object. + * + * ```js + * import https from 'node:https'; + * + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * }; + * + * const req = https.request(options, (res) => { + * console.log('statusCode:', res.statusCode); + * console.log('headers:', res.headers); + * + * res.on('data', (d) => { + * process.stdout.write(d); + * }); + * }); + * + * req.on('error', (e) => { + * console.error(e); + * }); + * req.end(); + * ``` + * + * Example using options from `tls.connect()`: + * + * ```js + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * }; + * options.agent = new https.Agent(options); + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Alternatively, opt out of connection pooling by not using an `Agent`. + * + * ```js + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * agent: false, + * }; + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Example using a `URL` as `options`: + * + * ```js + * const options = new URL('https://abc:xyz@example.com'); + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Example pinning on certificate fingerprint, or the public key (similar to`pin-sha256`): + * + * ```js + * import tls from 'node:tls'; + * import https from 'node:https'; + * import crypto from 'node:crypto'; + * + * function sha256(s) { + * return crypto.createHash('sha256').update(s).digest('base64'); + * } + * const options = { + * hostname: 'github.com', + * port: 443, + * path: '/', + * method: 'GET', + * checkServerIdentity: function(host, cert) { + * // Make sure the certificate is issued to the host we are connected to + * const err = tls.checkServerIdentity(host, cert); + * if (err) { + * return err; + * } + * + * // Pin the public key, similar to HPKP pin-sha256 pinning + * const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU='; + * if (sha256(cert.pubkey) !== pubkey256) { + * const msg = 'Certificate verification error: ' + + * `The public key of '${cert.subject.CN}' ` + + * 'does not match our pinned fingerprint'; + * return new Error(msg); + * } + * + * // Pin the exact certificate, rather than the pub key + * const cert256 = '25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:' + + * 'D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16'; + * if (cert.fingerprint256 !== cert256) { + * const msg = 'Certificate verification error: ' + + * `The certificate of '${cert.subject.CN}' ` + + * 'does not match our pinned fingerprint'; + * return new Error(msg); + * } + * + * // This loop is informational only. + * // Print the certificate and public key fingerprints of all certs in the + * // chain. Its common to pin the public key of the issuer on the public + * // internet, while pinning the public key of the service in sensitive + * // environments. + * do { + * console.log('Subject Common Name:', cert.subject.CN); + * console.log(' Certificate SHA256 fingerprint:', cert.fingerprint256); + * + * hash = crypto.createHash('sha256'); + * console.log(' Public key ping-sha256:', sha256(cert.pubkey)); + * + * lastprint256 = cert.fingerprint256; + * cert = cert.issuerCertificate; + * } while (cert.fingerprint256 !== lastprint256); + * + * }, + * }; + * + * options.agent = new https.Agent(options); + * const req = https.request(options, (res) => { + * console.log('All OK. Server matched our pinned cert or public key'); + * console.log('statusCode:', res.statusCode); + * // Print the HPKP values + * console.log('headers:', res.headers['public-key-pins']); + * + * res.on('data', (d) => {}); + * }); + * + * req.on('error', (e) => { + * console.error(e.message); + * }); + * req.end(); + * ``` + * + * Outputs for example: + * + * ```text + * Subject Common Name: github.com + * Certificate SHA256 fingerprint: 25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16 + * Public key ping-sha256: pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU= + * Subject Common Name: DigiCert SHA2 Extended Validation Server CA + * Certificate SHA256 fingerprint: 40:3E:06:2A:26:53:05:91:13:28:5B:AF:80:A0:D4:AE:42:2C:84:8C:9F:78:FA:D0:1F:C9:4B:C5:B8:7F:EF:1A + * Public key ping-sha256: RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho= + * Subject Common Name: DigiCert High Assurance EV Root CA + * Certificate SHA256 fingerprint: 74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF + * Public key ping-sha256: WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18= + * All OK. Server matched our pinned cert or public key + * statusCode: 200 + * headers: max-age=0; pin-sha256="WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18="; pin-sha256="RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho="; + * pin-sha256="k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws="; pin-sha256="K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q="; pin-sha256="IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4="; + * pin-sha256="iie1VXtL7HzAMF+/PVPR9xzT80kQxdZeJ+zduCB3uj0="; pin-sha256="LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A="; includeSubDomains + * ``` + * @since v0.3.6 + * @param options Accepts all `options` from `request`, with some differences in default values: + */ + function request( + options: RequestOptions | string | URL, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + function request( + url: string | URL, + options: RequestOptions, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + /** + * Like `http.get()` but for HTTPS. + * + * `options` can be an object, a string, or a `URL` object. If `options` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * ```js + * import https from 'node:https'; + * + * https.get('https://encrypted.google.com/', (res) => { + * console.log('statusCode:', res.statusCode); + * console.log('headers:', res.headers); + * + * res.on('data', (d) => { + * process.stdout.write(d); + * }); + * + * }).on('error', (e) => { + * console.error(e); + * }); + * ``` + * @since v0.3.6 + * @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`. + */ + function get( + options: RequestOptions | string | URL, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + function get( + url: string | URL, + options: RequestOptions, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + let globalAgent: Agent; +} +declare module "https" { + export * from "node:https"; +} diff --git a/backend/node_modules/@types/node/index.d.ts b/backend/node_modules/@types/node/index.d.ts new file mode 100644 index 0000000..08ab4f0 --- /dev/null +++ b/backend/node_modules/@types/node/index.d.ts @@ -0,0 +1,115 @@ +/** + * License for programmatically and manually incorporated + * documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc + * + * Copyright Node.js 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. + */ + +// NOTE: These definitions support Node.js and TypeScript 5.8+. + +// Reference required TypeScript libraries: +/// +/// +/// + +// Iterator definitions required for compatibility with TypeScript <5.6: +/// + +// Definitions for Node.js modules specific to TypeScript 5.7+: +/// +/// + +// Definitions for Node.js modules that are not specific to any version of TypeScript: +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/backend/node_modules/@types/node/inspector.d.ts b/backend/node_modules/@types/node/inspector.d.ts new file mode 100644 index 0000000..c3a7785 --- /dev/null +++ b/backend/node_modules/@types/node/inspector.d.ts @@ -0,0 +1,224 @@ +/** + * The `node:inspector` module provides an API for interacting with the V8 + * inspector. + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/inspector.js) + */ +declare module "node:inspector" { + import { EventEmitter } from "node:events"; + /** + * The `inspector.Session` is used for dispatching messages to the V8 inspector + * back-end and receiving message responses and notifications. + */ + class Session extends EventEmitter { + /** + * Create a new instance of the inspector.Session class. + * The inspector session needs to be connected through `session.connect()` before the messages can be dispatched to the inspector backend. + */ + constructor(); + /** + * Connects a session to the inspector back-end. + */ + connect(): void; + /** + * Connects a session to the inspector back-end. + * An exception will be thrown if this API was not called on a Worker thread. + * @since v12.11.0 + */ + connectToMainThread(): void; + /** + * Immediately close the session. All pending message callbacks will be called with an error. + * `session.connect()` will need to be called to be able to send messages again. + * Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints. + */ + disconnect(): void; + } + /** + * Activate inspector on host and port. Equivalent to `node --inspect=[[host:]port]`, but can be done programmatically after node has + * started. + * + * If wait is `true`, will block until a client has connected to the inspect port + * and flow control has been passed to the debugger client. + * + * See the [security warning](https://nodejs.org/docs/latest-v25.x/api/cli.html#warning-binding-inspector-to-a-public-ipport-combination-is-insecure) + * regarding the `host` parameter usage. + * @param port Port to listen on for inspector connections. Defaults to what was specified on the CLI. + * @param host Host to listen on for inspector connections. Defaults to what was specified on the CLI. + * @param wait Block until a client has connected. Defaults to what was specified on the CLI. + * @returns Disposable that calls `inspector.close()`. + */ + function open(port?: number, host?: string, wait?: boolean): Disposable; + /** + * Deactivate the inspector. Blocks until there are no active connections. + */ + function close(): void; + /** + * Return the URL of the active inspector, or `undefined` if there is none. + * + * ```console + * $ node --inspect -p 'inspector.url()' + * Debugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * For help, see: https://nodejs.org/en/docs/inspector + * ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * + * $ node --inspect=localhost:3000 -p 'inspector.url()' + * Debugger listening on ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * For help, see: https://nodejs.org/en/docs/inspector + * ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * + * $ node -p 'inspector.url()' + * undefined + * ``` + */ + function url(): string | undefined; + /** + * Blocks until a client (existing or connected later) has sent `Runtime.runIfWaitingForDebugger` command. + * + * An exception will be thrown if there is no active inspector. + * @since v12.7.0 + */ + function waitForDebugger(): void; + // These methods are exposed by the V8 inspector console API (inspector/v8-console.h). + // The method signatures differ from those of the Node.js console, and are deliberately + // typed permissively. + interface InspectorConsole { + debug(...data: any[]): void; + error(...data: any[]): void; + info(...data: any[]): void; + log(...data: any[]): void; + warn(...data: any[]): void; + dir(...data: any[]): void; + dirxml(...data: any[]): void; + table(...data: any[]): void; + trace(...data: any[]): void; + group(...data: any[]): void; + groupCollapsed(...data: any[]): void; + groupEnd(...data: any[]): void; + clear(...data: any[]): void; + count(label?: any): void; + countReset(label?: any): void; + assert(value?: any, ...data: any[]): void; + profile(label?: any): void; + profileEnd(label?: any): void; + time(label?: any): void; + timeLog(label?: any): void; + timeStamp(label?: any): void; + } + /** + * An object to send messages to the remote inspector console. + * @since v11.0.0 + */ + const console: InspectorConsole; + // DevTools protocol event broadcast methods + namespace Network { + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.requestWillBeSent` event to connected frontends. This event indicates that + * the application is about to send an HTTP request. + * @since v22.6.0 + */ + function requestWillBeSent(params: RequestWillBeSentEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.dataReceived` event to connected frontends, or buffers the data if + * `Network.streamResourceContent` command was not invoked for the given request yet. + * + * Also enables `Network.getResponseBody` command to retrieve the response data. + * @since v24.2.0 + */ + function dataReceived(params: DataReceivedEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Enables `Network.getRequestPostData` command to retrieve the request data. + * @since v24.3.0 + */ + function dataSent(params: unknown): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.responseReceived` event to connected frontends. This event indicates that + * HTTP response is available. + * @since v22.6.0 + */ + function responseReceived(params: ResponseReceivedEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.loadingFinished` event to connected frontends. This event indicates that + * HTTP request has finished loading. + * @since v22.6.0 + */ + function loadingFinished(params: LoadingFinishedEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.loadingFailed` event to connected frontends. This event indicates that + * HTTP request has failed to load. + * @since v22.7.0 + */ + function loadingFailed(params: LoadingFailedEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.webSocketCreated` event to connected frontends. This event indicates that + * a WebSocket connection has been initiated. + * @since v24.7.0 + */ + function webSocketCreated(params: WebSocketCreatedEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.webSocketHandshakeResponseReceived` event to connected frontends. + * This event indicates that the WebSocket handshake response has been received. + * @since v24.7.0 + */ + function webSocketHandshakeResponseReceived(params: WebSocketHandshakeResponseReceivedEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.webSocketClosed` event to connected frontends. + * This event indicates that a WebSocket connection has been closed. + * @since v24.7.0 + */ + function webSocketClosed(params: WebSocketClosedEventDataType): void; + } + namespace NetworkResources { + /** + * This feature is only available with the `--experimental-inspector-network-resource` flag enabled. + * + * The inspector.NetworkResources.put method is used to provide a response for a loadNetworkResource + * request issued via the Chrome DevTools Protocol (CDP). + * This is typically triggered when a source map is specified by URL, and a DevTools frontend—such as + * Chrome—requests the resource to retrieve the source map. + * + * This method allows developers to predefine the resource content to be served in response to such CDP requests. + * + * ```js + * const inspector = require('node:inspector'); + * // By preemptively calling put to register the resource, a source map can be resolved when + * // a loadNetworkResource request is made from the frontend. + * async function setNetworkResources() { + * const mapUrl = 'http://localhost:3000/dist/app.js.map'; + * const tsUrl = 'http://localhost:3000/src/app.ts'; + * const distAppJsMap = await fetch(mapUrl).then((res) => res.text()); + * const srcAppTs = await fetch(tsUrl).then((res) => res.text()); + * inspector.NetworkResources.put(mapUrl, distAppJsMap); + * inspector.NetworkResources.put(tsUrl, srcAppTs); + * }; + * setNetworkResources().then(() => { + * require('./dist/app'); + * }); + * ``` + * + * For more details, see the official CDP documentation: [Network.loadNetworkResource](https://chromedevtools.github.io/devtools-protocol/tot/Network/#method-loadNetworkResource) + * @since v24.5.0 + * @experimental + */ + function put(url: string, data: string): void; + } +} +declare module "inspector" { + export * from "node:inspector"; +} diff --git a/backend/node_modules/@types/node/inspector.generated.d.ts b/backend/node_modules/@types/node/inspector.generated.d.ts new file mode 100644 index 0000000..84c482d --- /dev/null +++ b/backend/node_modules/@types/node/inspector.generated.d.ts @@ -0,0 +1,4226 @@ +// These definitions are automatically generated by the generate-inspector script. +// Do not edit this file directly. +// See scripts/generate-inspector/README.md for information on how to update the protocol definitions. +// Changes to the module itself should be added to the generator template (scripts/generate-inspector/inspector.d.ts.template). + +declare module "node:inspector" { + interface InspectorNotification { + method: string; + params: T; + } + namespace Schema { + /** + * Description of the protocol domain. + */ + interface Domain { + /** + * Domain name. + */ + name: string; + /** + * Domain version. + */ + version: string; + } + interface GetDomainsReturnType { + /** + * List of supported domains. + */ + domains: Domain[]; + } + } + namespace Runtime { + /** + * Unique script identifier. + */ + type ScriptId = string; + /** + * Unique object identifier. + */ + type RemoteObjectId = string; + /** + * Primitive value which cannot be JSON-stringified. + */ + type UnserializableValue = string; + /** + * Mirror object referencing original JavaScript object. + */ + interface RemoteObject { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * Object class (constructor) name. Specified for object type values only. + */ + className?: string | undefined; + /** + * Remote object value in case of primitive values or JSON values (if it was requested). + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified does not have value, but gets this property. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * Unique object identifier (for non-primitive values). + */ + objectId?: RemoteObjectId | undefined; + /** + * Preview containing abbreviated property values. Specified for object type values only. + * @experimental + */ + preview?: ObjectPreview | undefined; + /** + * @experimental + */ + customPreview?: CustomPreview | undefined; + } + /** + * @experimental + */ + interface CustomPreview { + header: string; + hasBody: boolean; + formatterObjectId: RemoteObjectId; + bindRemoteObjectFunctionId: RemoteObjectId; + configObjectId?: RemoteObjectId | undefined; + } + /** + * Object containing abbreviated remote object value. + * @experimental + */ + interface ObjectPreview { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * True iff some of the properties or entries of the original object did not fit. + */ + overflow: boolean; + /** + * List of the properties. + */ + properties: PropertyPreview[]; + /** + * List of the entries. Specified for map and set subtype values only. + */ + entries?: EntryPreview[] | undefined; + } + /** + * @experimental + */ + interface PropertyPreview { + /** + * Property name. + */ + name: string; + /** + * Object type. Accessor means that the property itself is an accessor property. + */ + type: string; + /** + * User-friendly property value string. + */ + value?: string | undefined; + /** + * Nested value preview. + */ + valuePreview?: ObjectPreview | undefined; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + } + /** + * @experimental + */ + interface EntryPreview { + /** + * Preview of the key. Specified for map-like collection entries. + */ + key?: ObjectPreview | undefined; + /** + * Preview of the value. + */ + value: ObjectPreview; + } + /** + * Object property descriptor. + */ + interface PropertyDescriptor { + /** + * Property name or symbol description. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + /** + * True if the value associated with the property may be changed (data descriptors only). + */ + writable?: boolean | undefined; + /** + * A function which serves as a getter for the property, or undefined if there is no getter (accessor descriptors only). + */ + get?: RemoteObject | undefined; + /** + * A function which serves as a setter for the property, or undefined if there is no setter (accessor descriptors only). + */ + set?: RemoteObject | undefined; + /** + * True if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. + */ + configurable: boolean; + /** + * True if this property shows up during enumeration of the properties on the corresponding object. + */ + enumerable: boolean; + /** + * True if the result was thrown during the evaluation. + */ + wasThrown?: boolean | undefined; + /** + * True if the property is owned for the object. + */ + isOwn?: boolean | undefined; + /** + * Property symbol object, if the property is of the symbol type. + */ + symbol?: RemoteObject | undefined; + } + /** + * Object internal property descriptor. This property isn't normally visible in JavaScript code. + */ + interface InternalPropertyDescriptor { + /** + * Conventional property name. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + } + /** + * Represents function call argument. Either remote object id objectId, primitive value, unserializable primitive value or neither of (for undefined) them should be specified. + */ + interface CallArgument { + /** + * Primitive value or serializable javascript object. + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * Remote object handle. + */ + objectId?: RemoteObjectId | undefined; + } + /** + * Id of an execution context. + */ + type ExecutionContextId = number; + /** + * Description of an isolated world. + */ + interface ExecutionContextDescription { + /** + * Unique id of the execution context. It can be used to specify in which execution context script evaluation should be performed. + */ + id: ExecutionContextId; + /** + * Execution context origin. + */ + origin: string; + /** + * Human readable name describing given context. + */ + name: string; + /** + * Embedder-specific auxiliary data. + */ + auxData?: object | undefined; + } + /** + * Detailed information about exception (or error) that was thrown during script compilation or execution. + */ + interface ExceptionDetails { + /** + * Exception id. + */ + exceptionId: number; + /** + * Exception text, which should be used together with exception object when available. + */ + text: string; + /** + * Line number of the exception location (0-based). + */ + lineNumber: number; + /** + * Column number of the exception location (0-based). + */ + columnNumber: number; + /** + * Script ID of the exception location. + */ + scriptId?: ScriptId | undefined; + /** + * URL of the exception location, to be used when the script was not reported. + */ + url?: string | undefined; + /** + * JavaScript stack trace if available. + */ + stackTrace?: StackTrace | undefined; + /** + * Exception object if available. + */ + exception?: RemoteObject | undefined; + /** + * Identifier of the context where exception happened. + */ + executionContextId?: ExecutionContextId | undefined; + } + /** + * Number of milliseconds since epoch. + */ + type Timestamp = number; + /** + * Stack entry for runtime errors and assertions. + */ + interface CallFrame { + /** + * JavaScript function name. + */ + functionName: string; + /** + * JavaScript script id. + */ + scriptId: ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * JavaScript script line number (0-based). + */ + lineNumber: number; + /** + * JavaScript script column number (0-based). + */ + columnNumber: number; + } + /** + * Call frames for assertions or error messages. + */ + interface StackTrace { + /** + * String label of this stack trace. For async traces this may be a name of the function that initiated the async call. + */ + description?: string | undefined; + /** + * JavaScript function name. + */ + callFrames: CallFrame[]; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + */ + parent?: StackTrace | undefined; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + * @experimental + */ + parentId?: StackTraceId | undefined; + } + /** + * Unique identifier of current debugger. + * @experimental + */ + type UniqueDebuggerId = string; + /** + * If debuggerId is set stack trace comes from another debugger and can be resolved there. This allows to track cross-debugger calls. See Runtime.StackTrace and Debugger.paused for usages. + * @experimental + */ + interface StackTraceId { + id: string; + debuggerId?: UniqueDebuggerId | undefined; + } + interface EvaluateParameterType { + /** + * Expression to evaluate. + */ + expression: string; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Specifies in which execution context to perform evaluation. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + contextId?: ExecutionContextId | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface AwaitPromiseParameterType { + /** + * Identifier of the promise. + */ + promiseObjectId: RemoteObjectId; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + } + interface CallFunctionOnParameterType { + /** + * Declaration of the function to call. + */ + functionDeclaration: string; + /** + * Identifier of the object to call function on. Either objectId or executionContextId should be specified. + */ + objectId?: RemoteObjectId | undefined; + /** + * Call arguments. All call arguments must belong to the same JavaScript world as the target object. + */ + arguments?: CallArgument[] | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + /** + * Specifies execution context which global object will be used to call function on. Either executionContextId or objectId should be specified. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. If objectGroup is not specified and objectId is, objectGroup will be inherited from object. + */ + objectGroup?: string | undefined; + } + interface GetPropertiesParameterType { + /** + * Identifier of the object to return properties for. + */ + objectId: RemoteObjectId; + /** + * If true, returns properties belonging only to the element itself, not to its prototype chain. + */ + ownProperties?: boolean | undefined; + /** + * If true, returns accessor properties (with getter/setter) only; internal properties are not returned either. + * @experimental + */ + accessorPropertiesOnly?: boolean | undefined; + /** + * Whether preview should be generated for the results. + * @experimental + */ + generatePreview?: boolean | undefined; + } + interface ReleaseObjectParameterType { + /** + * Identifier of the object to release. + */ + objectId: RemoteObjectId; + } + interface ReleaseObjectGroupParameterType { + /** + * Symbolic object group name. + */ + objectGroup: string; + } + interface SetCustomObjectFormatterEnabledParameterType { + enabled: boolean; + } + interface CompileScriptParameterType { + /** + * Expression to compile. + */ + expression: string; + /** + * Source url to be set for the script. + */ + sourceURL: string; + /** + * Specifies whether the compiled script should be persisted. + */ + persistScript: boolean; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface RunScriptParameterType { + /** + * Id of the script to run. + */ + scriptId: ScriptId; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface QueryObjectsParameterType { + /** + * Identifier of the prototype to return objects for. + */ + prototypeObjectId: RemoteObjectId; + } + interface GlobalLexicalScopeNamesParameterType { + /** + * Specifies in which execution context to lookup global scope variables. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface EvaluateReturnType { + /** + * Evaluation result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface AwaitPromiseReturnType { + /** + * Promise result. Will contain rejected value if promise was rejected. + */ + result: RemoteObject; + /** + * Exception details if stack strace is available. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CallFunctionOnReturnType { + /** + * Call result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface GetPropertiesReturnType { + /** + * Object properties. + */ + result: PropertyDescriptor[]; + /** + * Internal object properties (only of the element itself). + */ + internalProperties?: InternalPropertyDescriptor[] | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CompileScriptReturnType { + /** + * Id of the script. + */ + scriptId?: ScriptId | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface RunScriptReturnType { + /** + * Run result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface QueryObjectsReturnType { + /** + * Array with objects. + */ + objects: RemoteObject; + } + interface GlobalLexicalScopeNamesReturnType { + names: string[]; + } + interface ExecutionContextCreatedEventDataType { + /** + * A newly created execution context. + */ + context: ExecutionContextDescription; + } + interface ExecutionContextDestroyedEventDataType { + /** + * Id of the destroyed context + */ + executionContextId: ExecutionContextId; + } + interface ExceptionThrownEventDataType { + /** + * Timestamp of the exception. + */ + timestamp: Timestamp; + exceptionDetails: ExceptionDetails; + } + interface ExceptionRevokedEventDataType { + /** + * Reason describing why exception was revoked. + */ + reason: string; + /** + * The id of revoked exception, as reported in exceptionThrown. + */ + exceptionId: number; + } + interface ConsoleAPICalledEventDataType { + /** + * Type of the call. + */ + type: string; + /** + * Call arguments. + */ + args: RemoteObject[]; + /** + * Identifier of the context where the call was made. + */ + executionContextId: ExecutionContextId; + /** + * Call timestamp. + */ + timestamp: Timestamp; + /** + * Stack trace captured when the call was made. + */ + stackTrace?: StackTrace | undefined; + /** + * Console context descriptor for calls on non-default console context (not console.*): 'anonymous#unique-logger-id' for call on unnamed context, 'name#unique-logger-id' for call on named context. + * @experimental + */ + context?: string | undefined; + } + interface InspectRequestedEventDataType { + object: RemoteObject; + hints: object; + } + } + namespace Debugger { + /** + * Breakpoint identifier. + */ + type BreakpointId = string; + /** + * Call frame identifier. + */ + type CallFrameId = string; + /** + * Location in the source code. + */ + interface Location { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + } + /** + * Location in the source code. + * @experimental + */ + interface ScriptPosition { + lineNumber: number; + columnNumber: number; + } + /** + * JavaScript call frame. Array of call frames form the call stack. + */ + interface CallFrame { + /** + * Call frame identifier. This identifier is only valid while the virtual machine is paused. + */ + callFrameId: CallFrameId; + /** + * Name of the JavaScript function called on this call frame. + */ + functionName: string; + /** + * Location in the source code. + */ + functionLocation?: Location | undefined; + /** + * Location in the source code. + */ + location: Location; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Scope chain for this call frame. + */ + scopeChain: Scope[]; + /** + * this object for this call frame. + */ + this: Runtime.RemoteObject; + /** + * The value being returned, if the function is at return point. + */ + returnValue?: Runtime.RemoteObject | undefined; + } + /** + * Scope description. + */ + interface Scope { + /** + * Scope type. + */ + type: string; + /** + * Object representing the scope. For global and with scopes it represents the actual object; for the rest of the scopes, it is artificial transient object enumerating scope variables as its properties. + */ + object: Runtime.RemoteObject; + name?: string | undefined; + /** + * Location in the source code where scope starts + */ + startLocation?: Location | undefined; + /** + * Location in the source code where scope ends + */ + endLocation?: Location | undefined; + } + /** + * Search match for resource. + */ + interface SearchMatch { + /** + * Line number in resource content. + */ + lineNumber: number; + /** + * Line with match content. + */ + lineContent: string; + } + interface BreakLocation { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + type?: string | undefined; + } + interface SetBreakpointsActiveParameterType { + /** + * New value for breakpoints active state. + */ + active: boolean; + } + interface SetSkipAllPausesParameterType { + /** + * New value for skip pauses state. + */ + skip: boolean; + } + interface SetBreakpointByUrlParameterType { + /** + * Line number to set breakpoint at. + */ + lineNumber: number; + /** + * URL of the resources to set breakpoint on. + */ + url?: string | undefined; + /** + * Regex pattern for the URLs of the resources to set breakpoints on. Either url or urlRegex must be specified. + */ + urlRegex?: string | undefined; + /** + * Script hash of the resources to set breakpoint on. + */ + scriptHash?: string | undefined; + /** + * Offset in the line to set breakpoint at. + */ + columnNumber?: number | undefined; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + } + interface SetBreakpointParameterType { + /** + * Location to set breakpoint in. + */ + location: Location; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + } + interface RemoveBreakpointParameterType { + breakpointId: BreakpointId; + } + interface GetPossibleBreakpointsParameterType { + /** + * Start of range to search possible breakpoint locations in. + */ + start: Location; + /** + * End of range to search possible breakpoint locations in (excluding). When not specified, end of scripts is used as end of range. + */ + end?: Location | undefined; + /** + * Only consider locations which are in the same (non-nested) function as start. + */ + restrictToFunction?: boolean | undefined; + } + interface ContinueToLocationParameterType { + /** + * Location to continue to. + */ + location: Location; + targetCallFrames?: string | undefined; + } + interface PauseOnAsyncCallParameterType { + /** + * Debugger will pause when async call with given stack trace is started. + */ + parentStackTraceId: Runtime.StackTraceId; + } + interface StepIntoParameterType { + /** + * Debugger will issue additional Debugger.paused notification if any async task is scheduled before next pause. + * @experimental + */ + breakOnAsyncCall?: boolean | undefined; + } + interface GetStackTraceParameterType { + stackTraceId: Runtime.StackTraceId; + } + interface SearchInContentParameterType { + /** + * Id of the script to search in. + */ + scriptId: Runtime.ScriptId; + /** + * String to search for. + */ + query: string; + /** + * If true, search is case sensitive. + */ + caseSensitive?: boolean | undefined; + /** + * If true, treats string parameter as regex. + */ + isRegex?: boolean | undefined; + } + interface SetScriptSourceParameterType { + /** + * Id of the script to edit. + */ + scriptId: Runtime.ScriptId; + /** + * New content of the script. + */ + scriptSource: string; + /** + * If true the change will not actually be applied. Dry run may be used to get result description without actually modifying the code. + */ + dryRun?: boolean | undefined; + } + interface RestartFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + } + interface GetScriptSourceParameterType { + /** + * Id of the script to get source for. + */ + scriptId: Runtime.ScriptId; + } + interface SetPauseOnExceptionsParameterType { + /** + * Pause on exceptions mode. + */ + state: string; + } + interface EvaluateOnCallFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + /** + * Expression to evaluate. + */ + expression: string; + /** + * String object group name to put result into (allows rapid releasing resulting object handles using releaseObjectGroup). + */ + objectGroup?: string | undefined; + /** + * Specifies whether command line API should be available to the evaluated expression, defaults to false. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether to throw an exception if side effect cannot be ruled out during evaluation. + */ + throwOnSideEffect?: boolean | undefined; + } + interface SetVariableValueParameterType { + /** + * 0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' scope types are allowed. Other scopes could be manipulated manually. + */ + scopeNumber: number; + /** + * Variable name. + */ + variableName: string; + /** + * New variable value. + */ + newValue: Runtime.CallArgument; + /** + * Id of callframe that holds variable. + */ + callFrameId: CallFrameId; + } + interface SetReturnValueParameterType { + /** + * New return value. + */ + newValue: Runtime.CallArgument; + } + interface SetAsyncCallStackDepthParameterType { + /** + * Maximum depth of async call stacks. Setting to 0 will effectively disable collecting async call stacks (default). + */ + maxDepth: number; + } + interface SetBlackboxPatternsParameterType { + /** + * Array of regexps that will be used to check script url for blackbox state. + */ + patterns: string[]; + } + interface SetBlackboxedRangesParameterType { + /** + * Id of the script. + */ + scriptId: Runtime.ScriptId; + positions: ScriptPosition[]; + } + interface EnableReturnType { + /** + * Unique identifier of the debugger. + * @experimental + */ + debuggerId: Runtime.UniqueDebuggerId; + } + interface SetBreakpointByUrlReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * List of the locations this breakpoint resolved into upon addition. + */ + locations: Location[]; + } + interface SetBreakpointReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * Location this breakpoint resolved into. + */ + actualLocation: Location; + } + interface GetPossibleBreakpointsReturnType { + /** + * List of the possible breakpoint locations. + */ + locations: BreakLocation[]; + } + interface GetStackTraceReturnType { + stackTrace: Runtime.StackTrace; + } + interface SearchInContentReturnType { + /** + * List of search matches. + */ + result: SearchMatch[]; + } + interface SetScriptSourceReturnType { + /** + * New stack trace in case editing has happened while VM was stopped. + */ + callFrames?: CallFrame[] | undefined; + /** + * Whether current call stack was modified after applying the changes. + */ + stackChanged?: boolean | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Exception details if any. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface RestartFrameReturnType { + /** + * New stack trace. + */ + callFrames: CallFrame[]; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + } + interface GetScriptSourceReturnType { + /** + * Script source. + */ + scriptSource: string; + } + interface EvaluateOnCallFrameReturnType { + /** + * Object wrapper for the evaluation result. + */ + result: Runtime.RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface ScriptParsedEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: object | undefined; + /** + * True, if this script is generated as a result of the live edit operation. + * @experimental + */ + isLiveEdit?: boolean | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface ScriptFailedToParseEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: object | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface BreakpointResolvedEventDataType { + /** + * Breakpoint unique identifier. + */ + breakpointId: BreakpointId; + /** + * Actual breakpoint location. + */ + location: Location; + } + interface PausedEventDataType { + /** + * Call stack the virtual machine stopped on. + */ + callFrames: CallFrame[]; + /** + * Pause reason. + */ + reason: string; + /** + * Object containing break-specific auxiliary properties. + */ + data?: object | undefined; + /** + * Hit breakpoints IDs + */ + hitBreakpoints?: string[] | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Just scheduled async call will have this stack trace as parent stack during async execution. This field is available only after Debugger.stepInto call with breakOnAsynCall flag. + * @experimental + */ + asyncCallStackTraceId?: Runtime.StackTraceId | undefined; + } + } + namespace Console { + /** + * Console message. + */ + interface ConsoleMessage { + /** + * Message source. + */ + source: string; + /** + * Message severity. + */ + level: string; + /** + * Message text. + */ + text: string; + /** + * URL of the message origin. + */ + url?: string | undefined; + /** + * Line number in the resource that generated this message (1-based). + */ + line?: number | undefined; + /** + * Column number in the resource that generated this message (1-based). + */ + column?: number | undefined; + } + interface MessageAddedEventDataType { + /** + * Console message that has been added. + */ + message: ConsoleMessage; + } + } + namespace Profiler { + /** + * Profile node. Holds callsite information, execution statistics and child nodes. + */ + interface ProfileNode { + /** + * Unique id of the node. + */ + id: number; + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Number of samples where this node was on top of the call stack. + */ + hitCount?: number | undefined; + /** + * Child node ids. + */ + children?: number[] | undefined; + /** + * The reason of being not optimized. The function may be deoptimized or marked as don't optimize. + */ + deoptReason?: string | undefined; + /** + * An array of source position ticks. + */ + positionTicks?: PositionTickInfo[] | undefined; + } + /** + * Profile. + */ + interface Profile { + /** + * The list of profile nodes. First item is the root node. + */ + nodes: ProfileNode[]; + /** + * Profiling start timestamp in microseconds. + */ + startTime: number; + /** + * Profiling end timestamp in microseconds. + */ + endTime: number; + /** + * Ids of samples top nodes. + */ + samples?: number[] | undefined; + /** + * Time intervals between adjacent samples in microseconds. The first delta is relative to the profile startTime. + */ + timeDeltas?: number[] | undefined; + } + /** + * Specifies a number of samples attributed to a certain source position. + */ + interface PositionTickInfo { + /** + * Source line number (1-based). + */ + line: number; + /** + * Number of samples attributed to the source line. + */ + ticks: number; + } + /** + * Coverage data for a source range. + */ + interface CoverageRange { + /** + * JavaScript script source offset for the range start. + */ + startOffset: number; + /** + * JavaScript script source offset for the range end. + */ + endOffset: number; + /** + * Collected execution count of the source range. + */ + count: number; + } + /** + * Coverage data for a JavaScript function. + */ + interface FunctionCoverage { + /** + * JavaScript function name. + */ + functionName: string; + /** + * Source ranges inside the function with coverage data. + */ + ranges: CoverageRange[]; + /** + * Whether coverage data for this function has block granularity. + */ + isBlockCoverage: boolean; + } + /** + * Coverage data for a JavaScript script. + */ + interface ScriptCoverage { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Functions contained in the script that has coverage data. + */ + functions: FunctionCoverage[]; + } + interface SetSamplingIntervalParameterType { + /** + * New sampling interval in microseconds. + */ + interval: number; + } + interface StartPreciseCoverageParameterType { + /** + * Collect accurate call counts beyond simple 'covered' or 'not covered'. + */ + callCount?: boolean | undefined; + /** + * Collect block-based coverage. + */ + detailed?: boolean | undefined; + } + interface StopReturnType { + /** + * Recorded profile. + */ + profile: Profile; + } + interface TakePreciseCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface GetBestEffortCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface ConsoleProfileStartedEventDataType { + id: string; + /** + * Location of console.profile(). + */ + location: Debugger.Location; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + interface ConsoleProfileFinishedEventDataType { + id: string; + /** + * Location of console.profileEnd(). + */ + location: Debugger.Location; + profile: Profile; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + } + namespace HeapProfiler { + /** + * Heap snapshot object id. + */ + type HeapSnapshotObjectId = string; + /** + * Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes. + */ + interface SamplingHeapProfileNode { + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Allocations size in bytes for the node excluding children. + */ + selfSize: number; + /** + * Child nodes. + */ + children: SamplingHeapProfileNode[]; + } + /** + * Profile. + */ + interface SamplingHeapProfile { + head: SamplingHeapProfileNode; + } + interface StartTrackingHeapObjectsParameterType { + trackAllocations?: boolean | undefined; + } + interface StopTrackingHeapObjectsParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken when the tracking is stopped. + */ + reportProgress?: boolean | undefined; + } + interface TakeHeapSnapshotParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken. + */ + reportProgress?: boolean | undefined; + } + interface GetObjectByHeapObjectIdParameterType { + objectId: HeapSnapshotObjectId; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + } + interface AddInspectedHeapObjectParameterType { + /** + * Heap snapshot object id to be accessible by means of $x command line API. + */ + heapObjectId: HeapSnapshotObjectId; + } + interface GetHeapObjectIdParameterType { + /** + * Identifier of the object to get heap object id for. + */ + objectId: Runtime.RemoteObjectId; + } + interface StartSamplingParameterType { + /** + * Average sample interval in bytes. Poisson distribution is used for the intervals. The default value is 32768 bytes. + */ + samplingInterval?: number | undefined; + } + interface GetObjectByHeapObjectIdReturnType { + /** + * Evaluation result. + */ + result: Runtime.RemoteObject; + } + interface GetHeapObjectIdReturnType { + /** + * Id of the heap snapshot object corresponding to the passed remote object id. + */ + heapSnapshotObjectId: HeapSnapshotObjectId; + } + interface StopSamplingReturnType { + /** + * Recorded sampling heap profile. + */ + profile: SamplingHeapProfile; + } + interface GetSamplingProfileReturnType { + /** + * Return the sampling profile being collected. + */ + profile: SamplingHeapProfile; + } + interface AddHeapSnapshotChunkEventDataType { + chunk: string; + } + interface ReportHeapSnapshotProgressEventDataType { + done: number; + total: number; + finished?: boolean | undefined; + } + interface LastSeenObjectIdEventDataType { + lastSeenObjectId: number; + timestamp: number; + } + interface HeapStatsUpdateEventDataType { + /** + * An array of triplets. Each triplet describes a fragment. The first integer is the fragment index, the second integer is a total count of objects for the fragment, the third integer is a total size of the objects for the fragment. + */ + statsUpdate: number[]; + } + } + namespace NodeTracing { + interface TraceConfig { + /** + * Controls how the trace buffer stores data. + */ + recordMode?: string | undefined; + /** + * Included category filters. + */ + includedCategories: string[]; + } + interface StartParameterType { + traceConfig: TraceConfig; + } + interface GetCategoriesReturnType { + /** + * A list of supported tracing categories. + */ + categories: string[]; + } + interface DataCollectedEventDataType { + value: object[]; + } + } + namespace NodeWorker { + type WorkerID = string; + /** + * Unique identifier of attached debugging session. + */ + type SessionID = string; + interface WorkerInfo { + workerId: WorkerID; + type: string; + title: string; + url: string; + } + interface SendMessageToWorkerParameterType { + message: string; + /** + * Identifier of the session. + */ + sessionId: SessionID; + } + interface EnableParameterType { + /** + * Whether to new workers should be paused until the frontend sends `Runtime.runIfWaitingForDebugger` + * message to run them. + */ + waitForDebuggerOnStart: boolean; + } + interface DetachParameterType { + sessionId: SessionID; + } + interface AttachedToWorkerEventDataType { + /** + * Identifier assigned to the session used to send/receive messages. + */ + sessionId: SessionID; + workerInfo: WorkerInfo; + waitingForDebugger: boolean; + } + interface DetachedFromWorkerEventDataType { + /** + * Detached session identifier. + */ + sessionId: SessionID; + } + interface ReceivedMessageFromWorkerEventDataType { + /** + * Identifier of a session which sends a message. + */ + sessionId: SessionID; + message: string; + } + } + namespace Network { + /** + * Resource type as it was perceived by the rendering engine. + */ + type ResourceType = string; + /** + * Unique request identifier. + */ + type RequestId = string; + /** + * UTC time in seconds, counted from January 1, 1970. + */ + type TimeSinceEpoch = number; + /** + * Monotonically increasing time in seconds since an arbitrary point in the past. + */ + type MonotonicTime = number; + /** + * Information about the request initiator. + */ + interface Initiator { + /** + * Type of this initiator. + */ + type: string; + /** + * Initiator JavaScript stack trace, set for Script only. + * Requires the Debugger domain to be enabled. + */ + stack?: Runtime.StackTrace | undefined; + /** + * Initiator URL, set for Parser type or for Script type (when script is importing module) or for SignedExchange type. + */ + url?: string | undefined; + /** + * Initiator line number, set for Parser type or for Script type (when script is importing + * module) (0-based). + */ + lineNumber?: number | undefined; + /** + * Initiator column number, set for Parser type or for Script type (when script is importing + * module) (0-based). + */ + columnNumber?: number | undefined; + /** + * Set if another request triggered this request (e.g. preflight). + */ + requestId?: RequestId | undefined; + } + /** + * HTTP request data. + */ + interface Request { + url: string; + method: string; + headers: Headers; + hasPostData: boolean; + } + /** + * HTTP response data. + */ + interface Response { + url: string; + status: number; + statusText: string; + headers: Headers; + mimeType: string; + charset: string; + } + /** + * Request / response headers as keys / values of JSON object. + */ + interface Headers { + } + interface LoadNetworkResourcePageResult { + success: boolean; + stream?: IO.StreamHandle | undefined; + } + /** + * WebSocket response data. + */ + interface WebSocketResponse { + /** + * HTTP response status code. + */ + status: number; + /** + * HTTP response status text. + */ + statusText: string; + /** + * HTTP response headers. + */ + headers: Headers; + } + interface GetRequestPostDataParameterType { + /** + * Identifier of the network request to get content for. + */ + requestId: RequestId; + } + interface GetResponseBodyParameterType { + /** + * Identifier of the network request to get content for. + */ + requestId: RequestId; + } + interface StreamResourceContentParameterType { + /** + * Identifier of the request to stream. + */ + requestId: RequestId; + } + interface LoadNetworkResourceParameterType { + /** + * URL of the resource to get content for. + */ + url: string; + } + interface GetRequestPostDataReturnType { + /** + * Request body string, omitting files from multipart requests + */ + postData: string; + } + interface GetResponseBodyReturnType { + /** + * Response body. + */ + body: string; + /** + * True, if content was sent as base64. + */ + base64Encoded: boolean; + } + interface StreamResourceContentReturnType { + /** + * Data that has been buffered until streaming is enabled. + */ + bufferedData: string; + } + interface LoadNetworkResourceReturnType { + resource: LoadNetworkResourcePageResult; + } + interface RequestWillBeSentEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Request data. + */ + request: Request; + /** + * Request initiator. + */ + initiator: Initiator; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + /** + * Timestamp. + */ + wallTime: TimeSinceEpoch; + } + interface ResponseReceivedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + /** + * Resource type. + */ + type: ResourceType; + /** + * Response data. + */ + response: Response; + } + interface LoadingFailedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + /** + * Resource type. + */ + type: ResourceType; + /** + * Error message. + */ + errorText: string; + } + interface LoadingFinishedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + } + interface DataReceivedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + /** + * Data chunk length. + */ + dataLength: number; + /** + * Actual bytes received (might be less than dataLength for compressed encodings). + */ + encodedDataLength: number; + /** + * Data that was received. + * @experimental + */ + data?: string | undefined; + } + interface WebSocketCreatedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * WebSocket request URL. + */ + url: string; + /** + * Request initiator. + */ + initiator: Initiator; + } + interface WebSocketClosedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + } + interface WebSocketHandshakeResponseReceivedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + /** + * WebSocket response data. + */ + response: WebSocketResponse; + } + } + namespace NodeRuntime { + interface NotifyWhenWaitingForDisconnectParameterType { + enabled: boolean; + } + } + namespace Target { + type SessionID = string; + type TargetID = string; + interface TargetInfo { + targetId: TargetID; + type: string; + title: string; + url: string; + attached: boolean; + canAccessOpener: boolean; + } + interface SetAutoAttachParameterType { + autoAttach: boolean; + waitForDebuggerOnStart: boolean; + } + interface TargetCreatedEventDataType { + targetInfo: TargetInfo; + } + interface AttachedToTargetEventDataType { + sessionId: SessionID; + targetInfo: TargetInfo; + waitingForDebugger: boolean; + } + } + namespace IO { + type StreamHandle = string; + interface ReadParameterType { + /** + * Handle of the stream to read. + */ + handle: StreamHandle; + /** + * Seek to the specified offset before reading (if not specified, proceed with offset + * following the last read). Some types of streams may only support sequential reads. + */ + offset?: number | undefined; + /** + * Maximum number of bytes to read (left upon the agent discretion if not specified). + */ + size?: number | undefined; + } + interface CloseParameterType { + /** + * Handle of the stream to close. + */ + handle: StreamHandle; + } + interface ReadReturnType { + /** + * Data that were read. + */ + data: string; + /** + * Set if the end-of-file condition occurred while reading. + */ + eof: boolean; + } + } + interface Session { + /** + * Posts a message to the inspector back-end. `callback` will be notified when + * a response is received. `callback` is a function that accepts two optional + * arguments: error and message-specific result. + * + * ```js + * session.post('Runtime.evaluate', { expression: '2 + 2' }, + * (error, { result }) => console.log(result)); + * // Output: { type: 'number', value: 4, description: '4' } + * ``` + * + * The latest version of the V8 inspector protocol is published on the + * [Chrome DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/v8/). + * + * Node.js inspector supports all the Chrome DevTools Protocol domains declared + * by V8. Chrome DevTools Protocol domain provides an interface for interacting + * with one of the runtime agents used to inspect the application state and listen + * to the run-time events. + */ + post(method: string, callback?: (err: Error | null, params?: object) => void): void; + post(method: string, params?: object, callback?: (err: Error | null, params?: object) => void): void; + /** + * Returns supported domains. + */ + post(method: "Schema.getDomains", callback?: (err: Error | null, params: Schema.GetDomainsReturnType) => void): void; + /** + * Evaluates expression on global object. + */ + post(method: "Runtime.evaluate", params?: Runtime.EvaluateParameterType, callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + post(method: "Runtime.evaluate", callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + /** + * Add handler to promise with given promise object id. + */ + post(method: "Runtime.awaitPromise", params?: Runtime.AwaitPromiseParameterType, callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + post(method: "Runtime.awaitPromise", callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + /** + * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. + */ + post(method: "Runtime.callFunctionOn", params?: Runtime.CallFunctionOnParameterType, callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + post(method: "Runtime.callFunctionOn", callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + /** + * Returns properties of a given object. Object group of the result is inherited from the target object. + */ + post(method: "Runtime.getProperties", params?: Runtime.GetPropertiesParameterType, callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + post(method: "Runtime.getProperties", callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + /** + * Releases remote object with given id. + */ + post(method: "Runtime.releaseObject", params?: Runtime.ReleaseObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.releaseObject", callback?: (err: Error | null) => void): void; + /** + * Releases all remote objects that belong to a given group. + */ + post(method: "Runtime.releaseObjectGroup", params?: Runtime.ReleaseObjectGroupParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.releaseObjectGroup", callback?: (err: Error | null) => void): void; + /** + * Tells inspected instance to run if it was waiting for debugger to attach. + */ + post(method: "Runtime.runIfWaitingForDebugger", callback?: (err: Error | null) => void): void; + /** + * Enables reporting of execution contexts creation by means of executionContextCreated event. When the reporting gets enabled the event will be sent immediately for each existing execution context. + */ + post(method: "Runtime.enable", callback?: (err: Error | null) => void): void; + /** + * Disables reporting of execution contexts creation. + */ + post(method: "Runtime.disable", callback?: (err: Error | null) => void): void; + /** + * Discards collected exceptions and console API calls. + */ + post(method: "Runtime.discardConsoleEntries", callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: "Runtime.setCustomObjectFormatterEnabled", params?: Runtime.SetCustomObjectFormatterEnabledParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.setCustomObjectFormatterEnabled", callback?: (err: Error | null) => void): void; + /** + * Compiles expression. + */ + post(method: "Runtime.compileScript", params?: Runtime.CompileScriptParameterType, callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + post(method: "Runtime.compileScript", callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + /** + * Runs script with given id in a given context. + */ + post(method: "Runtime.runScript", params?: Runtime.RunScriptParameterType, callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: "Runtime.runScript", callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: "Runtime.queryObjects", params?: Runtime.QueryObjectsParameterType, callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + post(method: "Runtime.queryObjects", callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + /** + * Returns all let, const and class variables from global scope. + */ + post( + method: "Runtime.globalLexicalScopeNames", + params?: Runtime.GlobalLexicalScopeNamesParameterType, + callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void + ): void; + post(method: "Runtime.globalLexicalScopeNames", callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void): void; + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received. + */ + post(method: "Debugger.enable", callback?: (err: Error | null, params: Debugger.EnableReturnType) => void): void; + /** + * Disables debugger for given page. + */ + post(method: "Debugger.disable", callback?: (err: Error | null) => void): void; + /** + * Activates / deactivates all breakpoints on the page. + */ + post(method: "Debugger.setBreakpointsActive", params?: Debugger.SetBreakpointsActiveParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setBreakpointsActive", callback?: (err: Error | null) => void): void; + /** + * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). + */ + post(method: "Debugger.setSkipAllPauses", params?: Debugger.SetSkipAllPausesParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setSkipAllPauses", callback?: (err: Error | null) => void): void; + /** + * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in locations property. Further matching script parsing will result in subsequent breakpointResolved events issued. This logical breakpoint will survive page reloads. + */ + post(method: "Debugger.setBreakpointByUrl", params?: Debugger.SetBreakpointByUrlParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + post(method: "Debugger.setBreakpointByUrl", callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + /** + * Sets JavaScript breakpoint at a given location. + */ + post(method: "Debugger.setBreakpoint", params?: Debugger.SetBreakpointParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + post(method: "Debugger.setBreakpoint", callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + /** + * Removes JavaScript breakpoint. + */ + post(method: "Debugger.removeBreakpoint", params?: Debugger.RemoveBreakpointParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.removeBreakpoint", callback?: (err: Error | null) => void): void; + /** + * Returns possible locations for breakpoint. scriptId in start and end range locations should be the same. + */ + post( + method: "Debugger.getPossibleBreakpoints", + params?: Debugger.GetPossibleBreakpointsParameterType, + callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void + ): void; + post(method: "Debugger.getPossibleBreakpoints", callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void): void; + /** + * Continues execution until specific location is reached. + */ + post(method: "Debugger.continueToLocation", params?: Debugger.ContinueToLocationParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.continueToLocation", callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: "Debugger.pauseOnAsyncCall", params?: Debugger.PauseOnAsyncCallParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.pauseOnAsyncCall", callback?: (err: Error | null) => void): void; + /** + * Steps over the statement. + */ + post(method: "Debugger.stepOver", callback?: (err: Error | null) => void): void; + /** + * Steps into the function call. + */ + post(method: "Debugger.stepInto", params?: Debugger.StepIntoParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.stepInto", callback?: (err: Error | null) => void): void; + /** + * Steps out of the function call. + */ + post(method: "Debugger.stepOut", callback?: (err: Error | null) => void): void; + /** + * Stops on the next JavaScript statement. + */ + post(method: "Debugger.pause", callback?: (err: Error | null) => void): void; + /** + * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and Debugger.pauseOnAsyncTask instead. Steps into next scheduled async task if any is scheduled before next pause. Returns success when async task is actually scheduled, returns error if no task were scheduled or another scheduleStepIntoAsync was called. + * @experimental + */ + post(method: "Debugger.scheduleStepIntoAsync", callback?: (err: Error | null) => void): void; + /** + * Resumes JavaScript execution. + */ + post(method: "Debugger.resume", callback?: (err: Error | null) => void): void; + /** + * Returns stack trace with given stackTraceId. + * @experimental + */ + post(method: "Debugger.getStackTrace", params?: Debugger.GetStackTraceParameterType, callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + post(method: "Debugger.getStackTrace", callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + /** + * Searches for given string in script content. + */ + post(method: "Debugger.searchInContent", params?: Debugger.SearchInContentParameterType, callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + post(method: "Debugger.searchInContent", callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + /** + * Edits JavaScript source live. + */ + post(method: "Debugger.setScriptSource", params?: Debugger.SetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + post(method: "Debugger.setScriptSource", callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + /** + * Restarts particular call frame from the beginning. + */ + post(method: "Debugger.restartFrame", params?: Debugger.RestartFrameParameterType, callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + post(method: "Debugger.restartFrame", callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + /** + * Returns source for the script with given id. + */ + post(method: "Debugger.getScriptSource", params?: Debugger.GetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + post(method: "Debugger.getScriptSource", callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is none. + */ + post(method: "Debugger.setPauseOnExceptions", params?: Debugger.SetPauseOnExceptionsParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setPauseOnExceptions", callback?: (err: Error | null) => void): void; + /** + * Evaluates expression on a given call frame. + */ + post(method: "Debugger.evaluateOnCallFrame", params?: Debugger.EvaluateOnCallFrameParameterType, callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + post(method: "Debugger.evaluateOnCallFrame", callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + /** + * Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually. + */ + post(method: "Debugger.setVariableValue", params?: Debugger.SetVariableValueParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setVariableValue", callback?: (err: Error | null) => void): void; + /** + * Changes return value in top frame. Available only at return break position. + * @experimental + */ + post(method: "Debugger.setReturnValue", params?: Debugger.SetReturnValueParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setReturnValue", callback?: (err: Error | null) => void): void; + /** + * Enables or disables async call stacks tracking. + */ + post(method: "Debugger.setAsyncCallStackDepth", params?: Debugger.SetAsyncCallStackDepthParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setAsyncCallStackDepth", callback?: (err: Error | null) => void): void; + /** + * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * @experimental + */ + post(method: "Debugger.setBlackboxPatterns", params?: Debugger.SetBlackboxPatternsParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setBlackboxPatterns", callback?: (err: Error | null) => void): void; + /** + * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted. + * @experimental + */ + post(method: "Debugger.setBlackboxedRanges", params?: Debugger.SetBlackboxedRangesParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setBlackboxedRanges", callback?: (err: Error | null) => void): void; + /** + * Enables console domain, sends the messages collected so far to the client by means of the messageAdded notification. + */ + post(method: "Console.enable", callback?: (err: Error | null) => void): void; + /** + * Disables console domain, prevents further console messages from being reported to the client. + */ + post(method: "Console.disable", callback?: (err: Error | null) => void): void; + /** + * Does nothing. + */ + post(method: "Console.clearMessages", callback?: (err: Error | null) => void): void; + post(method: "Profiler.enable", callback?: (err: Error | null) => void): void; + post(method: "Profiler.disable", callback?: (err: Error | null) => void): void; + /** + * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. + */ + post(method: "Profiler.setSamplingInterval", params?: Profiler.SetSamplingIntervalParameterType, callback?: (err: Error | null) => void): void; + post(method: "Profiler.setSamplingInterval", callback?: (err: Error | null) => void): void; + post(method: "Profiler.start", callback?: (err: Error | null) => void): void; + post(method: "Profiler.stop", callback?: (err: Error | null, params: Profiler.StopReturnType) => void): void; + /** + * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code coverage may be incomplete. Enabling prevents running optimized code and resets execution counters. + */ + post(method: "Profiler.startPreciseCoverage", params?: Profiler.StartPreciseCoverageParameterType, callback?: (err: Error | null) => void): void; + post(method: "Profiler.startPreciseCoverage", callback?: (err: Error | null) => void): void; + /** + * Disable precise code coverage. Disabling releases unnecessary execution count records and allows executing optimized code. + */ + post(method: "Profiler.stopPreciseCoverage", callback?: (err: Error | null) => void): void; + /** + * Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started. + */ + post(method: "Profiler.takePreciseCoverage", callback?: (err: Error | null, params: Profiler.TakePreciseCoverageReturnType) => void): void; + /** + * Collect coverage data for the current isolate. The coverage data may be incomplete due to garbage collection. + */ + post(method: "Profiler.getBestEffortCoverage", callback?: (err: Error | null, params: Profiler.GetBestEffortCoverageReturnType) => void): void; + post(method: "HeapProfiler.enable", callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.disable", callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.startTrackingHeapObjects", params?: HeapProfiler.StartTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.startTrackingHeapObjects", callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.stopTrackingHeapObjects", params?: HeapProfiler.StopTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.stopTrackingHeapObjects", callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.takeHeapSnapshot", params?: HeapProfiler.TakeHeapSnapshotParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.takeHeapSnapshot", callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.collectGarbage", callback?: (err: Error | null) => void): void; + post( + method: "HeapProfiler.getObjectByHeapObjectId", + params?: HeapProfiler.GetObjectByHeapObjectIdParameterType, + callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void + ): void; + post(method: "HeapProfiler.getObjectByHeapObjectId", callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void): void; + /** + * Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions). + */ + post(method: "HeapProfiler.addInspectedHeapObject", params?: HeapProfiler.AddInspectedHeapObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.addInspectedHeapObject", callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.getHeapObjectId", params?: HeapProfiler.GetHeapObjectIdParameterType, callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: "HeapProfiler.getHeapObjectId", callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: "HeapProfiler.startSampling", params?: HeapProfiler.StartSamplingParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.startSampling", callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.stopSampling", callback?: (err: Error | null, params: HeapProfiler.StopSamplingReturnType) => void): void; + post(method: "HeapProfiler.getSamplingProfile", callback?: (err: Error | null, params: HeapProfiler.GetSamplingProfileReturnType) => void): void; + /** + * Gets supported tracing categories. + */ + post(method: "NodeTracing.getCategories", callback?: (err: Error | null, params: NodeTracing.GetCategoriesReturnType) => void): void; + /** + * Start trace events collection. + */ + post(method: "NodeTracing.start", params?: NodeTracing.StartParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeTracing.start", callback?: (err: Error | null) => void): void; + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: "NodeTracing.stop", callback?: (err: Error | null) => void): void; + /** + * Sends protocol message over session with given id. + */ + post(method: "NodeWorker.sendMessageToWorker", params?: NodeWorker.SendMessageToWorkerParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeWorker.sendMessageToWorker", callback?: (err: Error | null) => void): void; + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post(method: "NodeWorker.enable", params?: NodeWorker.EnableParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeWorker.enable", callback?: (err: Error | null) => void): void; + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: "NodeWorker.disable", callback?: (err: Error | null) => void): void; + /** + * Detached from the worker with given sessionId. + */ + post(method: "NodeWorker.detach", params?: NodeWorker.DetachParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeWorker.detach", callback?: (err: Error | null) => void): void; + /** + * Disables network tracking, prevents network events from being sent to the client. + */ + post(method: "Network.disable", callback?: (err: Error | null) => void): void; + /** + * Enables network tracking, network events will now be delivered to the client. + */ + post(method: "Network.enable", callback?: (err: Error | null) => void): void; + /** + * Returns post data sent with the request. Returns an error when no data was sent with the request. + */ + post(method: "Network.getRequestPostData", params?: Network.GetRequestPostDataParameterType, callback?: (err: Error | null, params: Network.GetRequestPostDataReturnType) => void): void; + post(method: "Network.getRequestPostData", callback?: (err: Error | null, params: Network.GetRequestPostDataReturnType) => void): void; + /** + * Returns content served for the given request. + */ + post(method: "Network.getResponseBody", params?: Network.GetResponseBodyParameterType, callback?: (err: Error | null, params: Network.GetResponseBodyReturnType) => void): void; + post(method: "Network.getResponseBody", callback?: (err: Error | null, params: Network.GetResponseBodyReturnType) => void): void; + /** + * Enables streaming of the response for the given requestId. + * If enabled, the dataReceived event contains the data that was received during streaming. + * @experimental + */ + post( + method: "Network.streamResourceContent", + params?: Network.StreamResourceContentParameterType, + callback?: (err: Error | null, params: Network.StreamResourceContentReturnType) => void + ): void; + post(method: "Network.streamResourceContent", callback?: (err: Error | null, params: Network.StreamResourceContentReturnType) => void): void; + /** + * Fetches the resource and returns the content. + */ + post(method: "Network.loadNetworkResource", params?: Network.LoadNetworkResourceParameterType, callback?: (err: Error | null, params: Network.LoadNetworkResourceReturnType) => void): void; + post(method: "Network.loadNetworkResource", callback?: (err: Error | null, params: Network.LoadNetworkResourceReturnType) => void): void; + /** + * Enable the NodeRuntime events except by `NodeRuntime.waitingForDisconnect`. + */ + post(method: "NodeRuntime.enable", callback?: (err: Error | null) => void): void; + /** + * Disable NodeRuntime events + */ + post(method: "NodeRuntime.disable", callback?: (err: Error | null) => void): void; + /** + * Enable the `NodeRuntime.waitingForDisconnect`. + */ + post(method: "NodeRuntime.notifyWhenWaitingForDisconnect", params?: NodeRuntime.NotifyWhenWaitingForDisconnectParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeRuntime.notifyWhenWaitingForDisconnect", callback?: (err: Error | null) => void): void; + post(method: "Target.setAutoAttach", params?: Target.SetAutoAttachParameterType, callback?: (err: Error | null) => void): void; + post(method: "Target.setAutoAttach", callback?: (err: Error | null) => void): void; + /** + * Read a chunk of the stream + */ + post(method: "IO.read", params?: IO.ReadParameterType, callback?: (err: Error | null, params: IO.ReadReturnType) => void): void; + post(method: "IO.read", callback?: (err: Error | null, params: IO.ReadReturnType) => void): void; + post(method: "IO.close", params?: IO.CloseParameterType, callback?: (err: Error | null) => void): void; + post(method: "IO.close", callback?: (err: Error | null) => void): void; + addListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + addListener(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + addListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + addListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + addListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + addListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + addListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + addListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + addListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + addListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + addListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + addListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + addListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + addListener(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + addListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + addListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + addListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + addListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + addListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + addListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + addListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + addListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + addListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + addListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + addListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + addListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + addListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + addListener(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + addListener(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + addListener(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + addListener(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + addListener(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * Fired upon WebSocket creation. + */ + addListener(event: "Network.webSocketCreated", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket is closed. + */ + addListener(event: "Network.webSocketClosed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket handshake response becomes available. + */ + addListener(event: "Network.webSocketHandshakeResponseReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + addListener(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + addListener(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + addListener(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + addListener(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "inspectorNotification", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextCreated", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextDestroyed", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextsCleared"): boolean; + emit(event: "Runtime.exceptionThrown", message: InspectorNotification): boolean; + emit(event: "Runtime.exceptionRevoked", message: InspectorNotification): boolean; + emit(event: "Runtime.consoleAPICalled", message: InspectorNotification): boolean; + emit(event: "Runtime.inspectRequested", message: InspectorNotification): boolean; + emit(event: "Debugger.scriptParsed", message: InspectorNotification): boolean; + emit(event: "Debugger.scriptFailedToParse", message: InspectorNotification): boolean; + emit(event: "Debugger.breakpointResolved", message: InspectorNotification): boolean; + emit(event: "Debugger.paused", message: InspectorNotification): boolean; + emit(event: "Debugger.resumed"): boolean; + emit(event: "Console.messageAdded", message: InspectorNotification): boolean; + emit(event: "Profiler.consoleProfileStarted", message: InspectorNotification): boolean; + emit(event: "Profiler.consoleProfileFinished", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.addHeapSnapshotChunk", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.resetProfiles"): boolean; + emit(event: "HeapProfiler.reportHeapSnapshotProgress", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.lastSeenObjectId", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.heapStatsUpdate", message: InspectorNotification): boolean; + emit(event: "NodeTracing.dataCollected", message: InspectorNotification): boolean; + emit(event: "NodeTracing.tracingComplete"): boolean; + emit(event: "NodeWorker.attachedToWorker", message: InspectorNotification): boolean; + emit(event: "NodeWorker.detachedFromWorker", message: InspectorNotification): boolean; + emit(event: "NodeWorker.receivedMessageFromWorker", message: InspectorNotification): boolean; + emit(event: "Network.requestWillBeSent", message: InspectorNotification): boolean; + emit(event: "Network.responseReceived", message: InspectorNotification): boolean; + emit(event: "Network.loadingFailed", message: InspectorNotification): boolean; + emit(event: "Network.loadingFinished", message: InspectorNotification): boolean; + emit(event: "Network.dataReceived", message: InspectorNotification): boolean; + emit(event: "Network.webSocketCreated", message: InspectorNotification): boolean; + emit(event: "Network.webSocketClosed", message: InspectorNotification): boolean; + emit(event: "Network.webSocketHandshakeResponseReceived", message: InspectorNotification): boolean; + emit(event: "NodeRuntime.waitingForDisconnect"): boolean; + emit(event: "NodeRuntime.waitingForDebugger"): boolean; + emit(event: "Target.targetCreated", message: InspectorNotification): boolean; + emit(event: "Target.attachedToTarget", message: InspectorNotification): boolean; + on(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + on(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + on(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + on(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + on(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + on(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + on(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + on(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + on(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + on(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + on(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + on(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + on(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + on(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + on(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + on(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + on(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + on(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + on(event: "HeapProfiler.resetProfiles", listener: () => void): this; + on(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + on(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + on(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + on(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + on(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + on(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + on(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + on(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + on(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + on(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + on(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + on(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + on(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * Fired upon WebSocket creation. + */ + on(event: "Network.webSocketCreated", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket is closed. + */ + on(event: "Network.webSocketClosed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket handshake response becomes available. + */ + on(event: "Network.webSocketHandshakeResponseReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + on(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + on(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + on(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + on(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + once(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + once(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + once(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + once(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + once(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + once(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + once(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + once(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + once(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + once(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + once(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + once(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + once(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + once(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + once(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + once(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + once(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + once(event: "HeapProfiler.resetProfiles", listener: () => void): this; + once(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + once(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + once(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + once(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + once(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + once(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + once(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + once(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + once(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + once(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + once(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + once(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + once(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * Fired upon WebSocket creation. + */ + once(event: "Network.webSocketCreated", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket is closed. + */ + once(event: "Network.webSocketClosed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket handshake response becomes available. + */ + once(event: "Network.webSocketHandshakeResponseReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + once(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + once(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + once(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + once(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependListener(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependListener(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + prependListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + prependListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + prependListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + prependListener(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + prependListener(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + prependListener(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * Fired upon WebSocket creation. + */ + prependListener(event: "Network.webSocketCreated", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket is closed. + */ + prependListener(event: "Network.webSocketClosed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket handshake response becomes available. + */ + prependListener(event: "Network.webSocketHandshakeResponseReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependListener(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependListener(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + prependListener(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependOnceListener(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependOnceListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependOnceListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependOnceListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependOnceListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependOnceListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependOnceListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependOnceListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependOnceListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependOnceListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependOnceListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependOnceListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependOnceListener(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependOnceListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependOnceListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + prependOnceListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependOnceListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependOnceListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependOnceListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependOnceListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependOnceListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependOnceListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + prependOnceListener(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + prependOnceListener(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + prependOnceListener(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * Fired upon WebSocket creation. + */ + prependOnceListener(event: "Network.webSocketCreated", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket is closed. + */ + prependOnceListener(event: "Network.webSocketClosed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket handshake response becomes available. + */ + prependOnceListener(event: "Network.webSocketHandshakeResponseReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependOnceListener(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependOnceListener(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + prependOnceListener(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + } +} +declare module "node:inspector/promises" { + export { + Schema, + Runtime, + Debugger, + Console, + Profiler, + HeapProfiler, + NodeTracing, + NodeWorker, + Network, + NodeRuntime, + Target, + IO, + } from 'inspector'; +} +declare module "node:inspector/promises" { + import { + InspectorNotification, + Schema, + Runtime, + Debugger, + Console, + Profiler, + HeapProfiler, + NodeTracing, + NodeWorker, + Network, + NodeRuntime, + Target, + IO, + } from "inspector"; + /** + * The `inspector.Session` is used for dispatching messages to the V8 inspector + * back-end and receiving message responses and notifications. + * @since v19.0.0 + */ + interface Session { + /** + * Posts a message to the inspector back-end. + * + * ```js + * import { Session } from 'node:inspector/promises'; + * try { + * const session = new Session(); + * session.connect(); + * const result = await session.post('Runtime.evaluate', { expression: '2 + 2' }); + * console.log(result); + * } catch (error) { + * console.error(error); + * } + * // Output: { result: { type: 'number', value: 4, description: '4' } } + * ``` + * + * The latest version of the V8 inspector protocol is published on the + * [Chrome DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/v8/). + * + * Node.js inspector supports all the Chrome DevTools Protocol domains declared + * by V8. Chrome DevTools Protocol domain provides an interface for interacting + * with one of the runtime agents used to inspect the application state and listen + * to the run-time events. + */ + post(method: string, params?: object): Promise; + /** + * Returns supported domains. + */ + post(method: "Schema.getDomains"): Promise; + /** + * Evaluates expression on global object. + */ + post(method: "Runtime.evaluate", params?: Runtime.EvaluateParameterType): Promise; + /** + * Add handler to promise with given promise object id. + */ + post(method: "Runtime.awaitPromise", params?: Runtime.AwaitPromiseParameterType): Promise; + /** + * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. + */ + post(method: "Runtime.callFunctionOn", params?: Runtime.CallFunctionOnParameterType): Promise; + /** + * Returns properties of a given object. Object group of the result is inherited from the target object. + */ + post(method: "Runtime.getProperties", params?: Runtime.GetPropertiesParameterType): Promise; + /** + * Releases remote object with given id. + */ + post(method: "Runtime.releaseObject", params?: Runtime.ReleaseObjectParameterType): Promise; + /** + * Releases all remote objects that belong to a given group. + */ + post(method: "Runtime.releaseObjectGroup", params?: Runtime.ReleaseObjectGroupParameterType): Promise; + /** + * Tells inspected instance to run if it was waiting for debugger to attach. + */ + post(method: "Runtime.runIfWaitingForDebugger"): Promise; + /** + * Enables reporting of execution contexts creation by means of executionContextCreated event. When the reporting gets enabled the event will be sent immediately for each existing execution context. + */ + post(method: "Runtime.enable"): Promise; + /** + * Disables reporting of execution contexts creation. + */ + post(method: "Runtime.disable"): Promise; + /** + * Discards collected exceptions and console API calls. + */ + post(method: "Runtime.discardConsoleEntries"): Promise; + /** + * @experimental + */ + post(method: "Runtime.setCustomObjectFormatterEnabled", params?: Runtime.SetCustomObjectFormatterEnabledParameterType): Promise; + /** + * Compiles expression. + */ + post(method: "Runtime.compileScript", params?: Runtime.CompileScriptParameterType): Promise; + /** + * Runs script with given id in a given context. + */ + post(method: "Runtime.runScript", params?: Runtime.RunScriptParameterType): Promise; + post(method: "Runtime.queryObjects", params?: Runtime.QueryObjectsParameterType): Promise; + /** + * Returns all let, const and class variables from global scope. + */ + post(method: "Runtime.globalLexicalScopeNames", params?: Runtime.GlobalLexicalScopeNamesParameterType): Promise; + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received. + */ + post(method: "Debugger.enable"): Promise; + /** + * Disables debugger for given page. + */ + post(method: "Debugger.disable"): Promise; + /** + * Activates / deactivates all breakpoints on the page. + */ + post(method: "Debugger.setBreakpointsActive", params?: Debugger.SetBreakpointsActiveParameterType): Promise; + /** + * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). + */ + post(method: "Debugger.setSkipAllPauses", params?: Debugger.SetSkipAllPausesParameterType): Promise; + /** + * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in locations property. Further matching script parsing will result in subsequent breakpointResolved events issued. This logical breakpoint will survive page reloads. + */ + post(method: "Debugger.setBreakpointByUrl", params?: Debugger.SetBreakpointByUrlParameterType): Promise; + /** + * Sets JavaScript breakpoint at a given location. + */ + post(method: "Debugger.setBreakpoint", params?: Debugger.SetBreakpointParameterType): Promise; + /** + * Removes JavaScript breakpoint. + */ + post(method: "Debugger.removeBreakpoint", params?: Debugger.RemoveBreakpointParameterType): Promise; + /** + * Returns possible locations for breakpoint. scriptId in start and end range locations should be the same. + */ + post(method: "Debugger.getPossibleBreakpoints", params?: Debugger.GetPossibleBreakpointsParameterType): Promise; + /** + * Continues execution until specific location is reached. + */ + post(method: "Debugger.continueToLocation", params?: Debugger.ContinueToLocationParameterType): Promise; + /** + * @experimental + */ + post(method: "Debugger.pauseOnAsyncCall", params?: Debugger.PauseOnAsyncCallParameterType): Promise; + /** + * Steps over the statement. + */ + post(method: "Debugger.stepOver"): Promise; + /** + * Steps into the function call. + */ + post(method: "Debugger.stepInto", params?: Debugger.StepIntoParameterType): Promise; + /** + * Steps out of the function call. + */ + post(method: "Debugger.stepOut"): Promise; + /** + * Stops on the next JavaScript statement. + */ + post(method: "Debugger.pause"): Promise; + /** + * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and Debugger.pauseOnAsyncTask instead. Steps into next scheduled async task if any is scheduled before next pause. Returns success when async task is actually scheduled, returns error if no task were scheduled or another scheduleStepIntoAsync was called. + * @experimental + */ + post(method: "Debugger.scheduleStepIntoAsync"): Promise; + /** + * Resumes JavaScript execution. + */ + post(method: "Debugger.resume"): Promise; + /** + * Returns stack trace with given stackTraceId. + * @experimental + */ + post(method: "Debugger.getStackTrace", params?: Debugger.GetStackTraceParameterType): Promise; + /** + * Searches for given string in script content. + */ + post(method: "Debugger.searchInContent", params?: Debugger.SearchInContentParameterType): Promise; + /** + * Edits JavaScript source live. + */ + post(method: "Debugger.setScriptSource", params?: Debugger.SetScriptSourceParameterType): Promise; + /** + * Restarts particular call frame from the beginning. + */ + post(method: "Debugger.restartFrame", params?: Debugger.RestartFrameParameterType): Promise; + /** + * Returns source for the script with given id. + */ + post(method: "Debugger.getScriptSource", params?: Debugger.GetScriptSourceParameterType): Promise; + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is none. + */ + post(method: "Debugger.setPauseOnExceptions", params?: Debugger.SetPauseOnExceptionsParameterType): Promise; + /** + * Evaluates expression on a given call frame. + */ + post(method: "Debugger.evaluateOnCallFrame", params?: Debugger.EvaluateOnCallFrameParameterType): Promise; + /** + * Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually. + */ + post(method: "Debugger.setVariableValue", params?: Debugger.SetVariableValueParameterType): Promise; + /** + * Changes return value in top frame. Available only at return break position. + * @experimental + */ + post(method: "Debugger.setReturnValue", params?: Debugger.SetReturnValueParameterType): Promise; + /** + * Enables or disables async call stacks tracking. + */ + post(method: "Debugger.setAsyncCallStackDepth", params?: Debugger.SetAsyncCallStackDepthParameterType): Promise; + /** + * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * @experimental + */ + post(method: "Debugger.setBlackboxPatterns", params?: Debugger.SetBlackboxPatternsParameterType): Promise; + /** + * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted. + * @experimental + */ + post(method: "Debugger.setBlackboxedRanges", params?: Debugger.SetBlackboxedRangesParameterType): Promise; + /** + * Enables console domain, sends the messages collected so far to the client by means of the messageAdded notification. + */ + post(method: "Console.enable"): Promise; + /** + * Disables console domain, prevents further console messages from being reported to the client. + */ + post(method: "Console.disable"): Promise; + /** + * Does nothing. + */ + post(method: "Console.clearMessages"): Promise; + post(method: "Profiler.enable"): Promise; + post(method: "Profiler.disable"): Promise; + /** + * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. + */ + post(method: "Profiler.setSamplingInterval", params?: Profiler.SetSamplingIntervalParameterType): Promise; + post(method: "Profiler.start"): Promise; + post(method: "Profiler.stop"): Promise; + /** + * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code coverage may be incomplete. Enabling prevents running optimized code and resets execution counters. + */ + post(method: "Profiler.startPreciseCoverage", params?: Profiler.StartPreciseCoverageParameterType): Promise; + /** + * Disable precise code coverage. Disabling releases unnecessary execution count records and allows executing optimized code. + */ + post(method: "Profiler.stopPreciseCoverage"): Promise; + /** + * Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started. + */ + post(method: "Profiler.takePreciseCoverage"): Promise; + /** + * Collect coverage data for the current isolate. The coverage data may be incomplete due to garbage collection. + */ + post(method: "Profiler.getBestEffortCoverage"): Promise; + post(method: "HeapProfiler.enable"): Promise; + post(method: "HeapProfiler.disable"): Promise; + post(method: "HeapProfiler.startTrackingHeapObjects", params?: HeapProfiler.StartTrackingHeapObjectsParameterType): Promise; + post(method: "HeapProfiler.stopTrackingHeapObjects", params?: HeapProfiler.StopTrackingHeapObjectsParameterType): Promise; + post(method: "HeapProfiler.takeHeapSnapshot", params?: HeapProfiler.TakeHeapSnapshotParameterType): Promise; + post(method: "HeapProfiler.collectGarbage"): Promise; + post(method: "HeapProfiler.getObjectByHeapObjectId", params?: HeapProfiler.GetObjectByHeapObjectIdParameterType): Promise; + /** + * Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions). + */ + post(method: "HeapProfiler.addInspectedHeapObject", params?: HeapProfiler.AddInspectedHeapObjectParameterType): Promise; + post(method: "HeapProfiler.getHeapObjectId", params?: HeapProfiler.GetHeapObjectIdParameterType): Promise; + post(method: "HeapProfiler.startSampling", params?: HeapProfiler.StartSamplingParameterType): Promise; + post(method: "HeapProfiler.stopSampling"): Promise; + post(method: "HeapProfiler.getSamplingProfile"): Promise; + /** + * Gets supported tracing categories. + */ + post(method: "NodeTracing.getCategories"): Promise; + /** + * Start trace events collection. + */ + post(method: "NodeTracing.start", params?: NodeTracing.StartParameterType): Promise; + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: "NodeTracing.stop"): Promise; + /** + * Sends protocol message over session with given id. + */ + post(method: "NodeWorker.sendMessageToWorker", params?: NodeWorker.SendMessageToWorkerParameterType): Promise; + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post(method: "NodeWorker.enable", params?: NodeWorker.EnableParameterType): Promise; + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: "NodeWorker.disable"): Promise; + /** + * Detached from the worker with given sessionId. + */ + post(method: "NodeWorker.detach", params?: NodeWorker.DetachParameterType): Promise; + /** + * Disables network tracking, prevents network events from being sent to the client. + */ + post(method: "Network.disable"): Promise; + /** + * Enables network tracking, network events will now be delivered to the client. + */ + post(method: "Network.enable"): Promise; + /** + * Returns post data sent with the request. Returns an error when no data was sent with the request. + */ + post(method: "Network.getRequestPostData", params?: Network.GetRequestPostDataParameterType): Promise; + /** + * Returns content served for the given request. + */ + post(method: "Network.getResponseBody", params?: Network.GetResponseBodyParameterType): Promise; + /** + * Enables streaming of the response for the given requestId. + * If enabled, the dataReceived event contains the data that was received during streaming. + * @experimental + */ + post(method: "Network.streamResourceContent", params?: Network.StreamResourceContentParameterType): Promise; + /** + * Fetches the resource and returns the content. + */ + post(method: "Network.loadNetworkResource", params?: Network.LoadNetworkResourceParameterType): Promise; + /** + * Enable the NodeRuntime events except by `NodeRuntime.waitingForDisconnect`. + */ + post(method: "NodeRuntime.enable"): Promise; + /** + * Disable NodeRuntime events + */ + post(method: "NodeRuntime.disable"): Promise; + /** + * Enable the `NodeRuntime.waitingForDisconnect`. + */ + post(method: "NodeRuntime.notifyWhenWaitingForDisconnect", params?: NodeRuntime.NotifyWhenWaitingForDisconnectParameterType): Promise; + post(method: "Target.setAutoAttach", params?: Target.SetAutoAttachParameterType): Promise; + /** + * Read a chunk of the stream + */ + post(method: "IO.read", params?: IO.ReadParameterType): Promise; + post(method: "IO.close", params?: IO.CloseParameterType): Promise; + addListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + addListener(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + addListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + addListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + addListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + addListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + addListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + addListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + addListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + addListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + addListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + addListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + addListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + addListener(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + addListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + addListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + addListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + addListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + addListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + addListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + addListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + addListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + addListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + addListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + addListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + addListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + addListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + addListener(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + addListener(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + addListener(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + addListener(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + addListener(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * Fired upon WebSocket creation. + */ + addListener(event: "Network.webSocketCreated", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket is closed. + */ + addListener(event: "Network.webSocketClosed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket handshake response becomes available. + */ + addListener(event: "Network.webSocketHandshakeResponseReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + addListener(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + addListener(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + addListener(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + addListener(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "inspectorNotification", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextCreated", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextDestroyed", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextsCleared"): boolean; + emit(event: "Runtime.exceptionThrown", message: InspectorNotification): boolean; + emit(event: "Runtime.exceptionRevoked", message: InspectorNotification): boolean; + emit(event: "Runtime.consoleAPICalled", message: InspectorNotification): boolean; + emit(event: "Runtime.inspectRequested", message: InspectorNotification): boolean; + emit(event: "Debugger.scriptParsed", message: InspectorNotification): boolean; + emit(event: "Debugger.scriptFailedToParse", message: InspectorNotification): boolean; + emit(event: "Debugger.breakpointResolved", message: InspectorNotification): boolean; + emit(event: "Debugger.paused", message: InspectorNotification): boolean; + emit(event: "Debugger.resumed"): boolean; + emit(event: "Console.messageAdded", message: InspectorNotification): boolean; + emit(event: "Profiler.consoleProfileStarted", message: InspectorNotification): boolean; + emit(event: "Profiler.consoleProfileFinished", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.addHeapSnapshotChunk", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.resetProfiles"): boolean; + emit(event: "HeapProfiler.reportHeapSnapshotProgress", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.lastSeenObjectId", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.heapStatsUpdate", message: InspectorNotification): boolean; + emit(event: "NodeTracing.dataCollected", message: InspectorNotification): boolean; + emit(event: "NodeTracing.tracingComplete"): boolean; + emit(event: "NodeWorker.attachedToWorker", message: InspectorNotification): boolean; + emit(event: "NodeWorker.detachedFromWorker", message: InspectorNotification): boolean; + emit(event: "NodeWorker.receivedMessageFromWorker", message: InspectorNotification): boolean; + emit(event: "Network.requestWillBeSent", message: InspectorNotification): boolean; + emit(event: "Network.responseReceived", message: InspectorNotification): boolean; + emit(event: "Network.loadingFailed", message: InspectorNotification): boolean; + emit(event: "Network.loadingFinished", message: InspectorNotification): boolean; + emit(event: "Network.dataReceived", message: InspectorNotification): boolean; + emit(event: "Network.webSocketCreated", message: InspectorNotification): boolean; + emit(event: "Network.webSocketClosed", message: InspectorNotification): boolean; + emit(event: "Network.webSocketHandshakeResponseReceived", message: InspectorNotification): boolean; + emit(event: "NodeRuntime.waitingForDisconnect"): boolean; + emit(event: "NodeRuntime.waitingForDebugger"): boolean; + emit(event: "Target.targetCreated", message: InspectorNotification): boolean; + emit(event: "Target.attachedToTarget", message: InspectorNotification): boolean; + on(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + on(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + on(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + on(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + on(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + on(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + on(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + on(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + on(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + on(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + on(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + on(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + on(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + on(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + on(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + on(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + on(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + on(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + on(event: "HeapProfiler.resetProfiles", listener: () => void): this; + on(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + on(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + on(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + on(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + on(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + on(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + on(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + on(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + on(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + on(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + on(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + on(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + on(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * Fired upon WebSocket creation. + */ + on(event: "Network.webSocketCreated", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket is closed. + */ + on(event: "Network.webSocketClosed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket handshake response becomes available. + */ + on(event: "Network.webSocketHandshakeResponseReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + on(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + on(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + on(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + on(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + once(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + once(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + once(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + once(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + once(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + once(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + once(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + once(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + once(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + once(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + once(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + once(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + once(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + once(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + once(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + once(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + once(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + once(event: "HeapProfiler.resetProfiles", listener: () => void): this; + once(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + once(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + once(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + once(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + once(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + once(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + once(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + once(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + once(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + once(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + once(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + once(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + once(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * Fired upon WebSocket creation. + */ + once(event: "Network.webSocketCreated", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket is closed. + */ + once(event: "Network.webSocketClosed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket handshake response becomes available. + */ + once(event: "Network.webSocketHandshakeResponseReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + once(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + once(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + once(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + once(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependListener(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependListener(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + prependListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + prependListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + prependListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + prependListener(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + prependListener(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + prependListener(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * Fired upon WebSocket creation. + */ + prependListener(event: "Network.webSocketCreated", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket is closed. + */ + prependListener(event: "Network.webSocketClosed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket handshake response becomes available. + */ + prependListener(event: "Network.webSocketHandshakeResponseReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependListener(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependListener(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + prependListener(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependOnceListener(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependOnceListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependOnceListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependOnceListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependOnceListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependOnceListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependOnceListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependOnceListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependOnceListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependOnceListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependOnceListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependOnceListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependOnceListener(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependOnceListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependOnceListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + prependOnceListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependOnceListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependOnceListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependOnceListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependOnceListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependOnceListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependOnceListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + prependOnceListener(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + prependOnceListener(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + prependOnceListener(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * Fired upon WebSocket creation. + */ + prependOnceListener(event: "Network.webSocketCreated", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket is closed. + */ + prependOnceListener(event: "Network.webSocketClosed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket handshake response becomes available. + */ + prependOnceListener(event: "Network.webSocketHandshakeResponseReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependOnceListener(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependOnceListener(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + prependOnceListener(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + } +} diff --git a/backend/node_modules/@types/node/inspector/promises.d.ts b/backend/node_modules/@types/node/inspector/promises.d.ts new file mode 100644 index 0000000..54e1250 --- /dev/null +++ b/backend/node_modules/@types/node/inspector/promises.d.ts @@ -0,0 +1,41 @@ +/** + * The `node:inspector/promises` module provides an API for interacting with the V8 + * inspector. + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/inspector/promises.js) + * @since v19.0.0 + */ +declare module "node:inspector/promises" { + import { EventEmitter } from "node:events"; + export { close, console, NetworkResources, open, url, waitForDebugger } from "node:inspector"; + /** + * The `inspector.Session` is used for dispatching messages to the V8 inspector + * back-end and receiving message responses and notifications. + * @since v19.0.0 + */ + export class Session extends EventEmitter { + /** + * Create a new instance of the inspector.Session class. + * The inspector session needs to be connected through `session.connect()` before the messages can be dispatched to the inspector backend. + */ + constructor(); + /** + * Connects a session to the inspector back-end. + */ + connect(): void; + /** + * Connects a session to the inspector back-end. + * An exception will be thrown if this API was not called on a Worker thread. + * @since v12.11.0 + */ + connectToMainThread(): void; + /** + * Immediately close the session. All pending message callbacks will be called with an error. + * `session.connect()` will need to be called to be able to send messages again. + * Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints. + */ + disconnect(): void; + } +} +declare module "inspector/promises" { + export * from "node:inspector/promises"; +} diff --git a/backend/node_modules/@types/node/module.d.ts b/backend/node_modules/@types/node/module.d.ts new file mode 100644 index 0000000..14c898f --- /dev/null +++ b/backend/node_modules/@types/node/module.d.ts @@ -0,0 +1,819 @@ +/** + * @since v0.3.7 + */ +declare module "node:module" { + import { URL } from "node:url"; + class Module { + constructor(id: string, parent?: Module); + } + interface Module extends NodeJS.Module {} + namespace Module { + export { Module }; + } + namespace Module { + /** + * A list of the names of all modules provided by Node.js. Can be used to verify + * if a module is maintained by a third party or not. + * + * Note: the list doesn't contain prefix-only modules like `node:test`. + * @since v9.3.0, v8.10.0, v6.13.0 + */ + const builtinModules: readonly string[]; + /** + * @since v12.2.0 + * @param path Filename to be used to construct the require + * function. Must be a file URL object, file URL string, or absolute path + * string. + */ + function createRequire(path: string | URL): NodeJS.Require; + namespace constants { + /** + * The following constants are returned as the `status` field in the object returned by + * {@link enableCompileCache} to indicate the result of the attempt to enable the + * [module compile cache](https://nodejs.org/docs/latest-v25.x/api/module.html#module-compile-cache). + * @since v22.8.0 + */ + namespace compileCacheStatus { + /** + * Node.js has enabled the compile cache successfully. The directory used to store the + * compile cache will be returned in the `directory` field in the + * returned object. + */ + const ENABLED: number; + /** + * The compile cache has already been enabled before, either by a previous call to + * {@link enableCompileCache}, or by the `NODE_COMPILE_CACHE=dir` + * environment variable. The directory used to store the + * compile cache will be returned in the `directory` field in the + * returned object. + */ + const ALREADY_ENABLED: number; + /** + * Node.js fails to enable the compile cache. This can be caused by the lack of + * permission to use the specified directory, or various kinds of file system errors. + * The detail of the failure will be returned in the `message` field in the + * returned object. + */ + const FAILED: number; + /** + * Node.js cannot enable the compile cache because the environment variable + * `NODE_DISABLE_COMPILE_CACHE=1` has been set. + */ + const DISABLED: number; + } + } + interface EnableCompileCacheOptions { + /** + * Optional. Directory to store the compile cache. If not specified, + * the directory specified by the `NODE_COMPILE_CACHE=dir` environment variable + * will be used if it's set, or `path.join(os.tmpdir(), 'node-compile-cache')` + * otherwise. + * @since v25.0.0 + */ + directory?: string | undefined; + /** + * Optional. If `true`, enables portable compile cache so that + * the cache can be reused even if the project directory is moved. This is a best-effort + * feature. If not specified, it will depend on whether the environment variable + * `NODE_COMPILE_CACHE_PORTABLE=1` is set. + * @since v25.0.0 + */ + portable?: boolean | undefined; + } + interface EnableCompileCacheResult { + /** + * One of the {@link constants.compileCacheStatus} + */ + status: number; + /** + * If Node.js cannot enable the compile cache, this contains + * the error message. Only set if `status` is `module.constants.compileCacheStatus.FAILED`. + */ + message?: string; + /** + * If the compile cache is enabled, this contains the directory + * where the compile cache is stored. Only set if `status` is + * `module.constants.compileCacheStatus.ENABLED` or + * `module.constants.compileCacheStatus.ALREADY_ENABLED`. + */ + directory?: string; + } + /** + * Enable [module compile cache](https://nodejs.org/docs/latest-v25.x/api/module.html#module-compile-cache) + * in the current Node.js instance. + * + * For general use cases, it's recommended to call `module.enableCompileCache()` without + * specifying the `options.directory`, so that the directory can be overridden by the + * `NODE_COMPILE_CACHE` environment variable when necessary. + * + * Since compile cache is supposed to be a optimization that is not mission critical, this + * method is designed to not throw any exception when the compile cache cannot be enabled. + * Instead, it will return an object containing an error message in the `message` field to + * aid debugging. If compile cache is enabled successfully, the `directory` field in the + * returned object contains the path to the directory where the compile cache is stored. The + * `status` field in the returned object would be one of the `module.constants.compileCacheStatus` + * values to indicate the result of the attempt to enable the + * [module compile cache](https://nodejs.org/docs/latest-v25.x/api/module.html#module-compile-cache). + * + * This method only affects the current Node.js instance. To enable it in child worker threads, + * either call this method in child worker threads too, or set the + * `process.env.NODE_COMPILE_CACHE` value to compile cache directory so the behavior can + * be inherited into the child workers. The directory can be obtained either from the + * `directory` field returned by this method, or with {@link getCompileCacheDir}. + * @since v22.8.0 + * @param options Optional. If a string is passed, it is considered to be `options.directory`. + */ + function enableCompileCache(options?: string | EnableCompileCacheOptions): EnableCompileCacheResult; + /** + * Flush the [module compile cache](https://nodejs.org/docs/latest-v25.x/api/module.html#module-compile-cache) + * accumulated from modules already loaded + * in the current Node.js instance to disk. This returns after all the flushing + * file system operations come to an end, no matter they succeed or not. If there + * are any errors, this will fail silently, since compile cache misses should not + * interfere with the actual operation of the application. + * @since v22.10.0 + */ + function flushCompileCache(): void; + /** + * @since v22.8.0 + * @return Path to the [module compile cache](https://nodejs.org/docs/latest-v25.x/api/module.html#module-compile-cache) + * directory if it is enabled, or `undefined` otherwise. + */ + function getCompileCacheDir(): string | undefined; + /** + * ```text + * /path/to/project + * ├ packages/ + * ├ bar/ + * ├ bar.js + * └ package.json // name = '@foo/bar' + * └ qux/ + * ├ node_modules/ + * └ some-package/ + * └ package.json // name = 'some-package' + * ├ qux.js + * └ package.json // name = '@foo/qux' + * ├ main.js + * └ package.json // name = '@foo' + * ``` + * ```js + * // /path/to/project/packages/bar/bar.js + * import { findPackageJSON } from 'node:module'; + * + * findPackageJSON('..', import.meta.url); + * // '/path/to/project/package.json' + * // Same result when passing an absolute specifier instead: + * findPackageJSON(new URL('../', import.meta.url)); + * findPackageJSON(import.meta.resolve('../')); + * + * findPackageJSON('some-package', import.meta.url); + * // '/path/to/project/packages/bar/node_modules/some-package/package.json' + * // When passing an absolute specifier, you might get a different result if the + * // resolved module is inside a subfolder that has nested `package.json`. + * findPackageJSON(import.meta.resolve('some-package')); + * // '/path/to/project/packages/bar/node_modules/some-package/some-subfolder/package.json' + * + * findPackageJSON('@foo/qux', import.meta.url); + * // '/path/to/project/packages/qux/package.json' + * ``` + * @since v22.14.0 + * @param specifier The specifier for the module whose `package.json` to + * retrieve. When passing a _bare specifier_, the `package.json` at the root of + * the package is returned. When passing a _relative specifier_ or an _absolute specifier_, + * the closest parent `package.json` is returned. + * @param base The absolute location (`file:` URL string or FS path) of the + * containing module. For CJS, use `__filename` (not `__dirname`!); for ESM, use + * `import.meta.url`. You do not need to pass it if `specifier` is an _absolute specifier_. + * @returns A path if the `package.json` is found. When `startLocation` + * is a package, the package's root `package.json`; when a relative or unresolved, the closest + * `package.json` to the `startLocation`. + */ + function findPackageJSON(specifier: string | URL, base?: string | URL): string | undefined; + /** + * @since v18.6.0, v16.17.0 + */ + function isBuiltin(moduleName: string): boolean; + interface RegisterOptions { + /** + * If you want to resolve `specifier` relative to a + * base URL, such as `import.meta.url`, you can pass that URL here. This + * property is ignored if the `parentURL` is supplied as the second argument. + * @default 'data:' + */ + parentURL?: string | URL | undefined; + /** + * Any arbitrary, cloneable JavaScript value to pass into the + * {@link initialize} hook. + */ + data?: Data | undefined; + /** + * [Transferable objects](https://nodejs.org/docs/latest-v25.x/api/worker_threads.html#portpostmessagevalue-transferlist) + * to be passed into the `initialize` hook. + */ + transferList?: any[] | undefined; + } + /* eslint-disable @definitelytyped/no-unnecessary-generics */ + /** + * Register a module that exports hooks that customize Node.js module + * resolution and loading behavior. See + * [Customization hooks](https://nodejs.org/docs/latest-v25.x/api/module.html#customization-hooks). + * + * This feature requires `--allow-worker` if used with the + * [Permission Model](https://nodejs.org/docs/latest-v25.x/api/permissions.html#permission-model). + * @since v20.6.0, v18.19.0 + * @param specifier Customization hooks to be registered; this should be + * the same string that would be passed to `import()`, except that if it is + * relative, it is resolved relative to `parentURL`. + * @param parentURL f you want to resolve `specifier` relative to a base + * URL, such as `import.meta.url`, you can pass that URL here. + */ + function register( + specifier: string | URL, + parentURL?: string | URL, + options?: RegisterOptions, + ): void; + function register(specifier: string | URL, options?: RegisterOptions): void; + interface RegisterHooksOptions { + /** + * See [load hook](https://nodejs.org/docs/latest-v25.x/api/module.html#loadurl-context-nextload). + * @default undefined + */ + load?: LoadHookSync | undefined; + /** + * See [resolve hook](https://nodejs.org/docs/latest-v25.x/api/module.html#resolvespecifier-context-nextresolve). + * @default undefined + */ + resolve?: ResolveHookSync | undefined; + } + interface ModuleHooks { + /** + * Deregister the hook instance. + */ + deregister(): void; + } + /** + * Register [hooks](https://nodejs.org/docs/latest-v25.x/api/module.html#customization-hooks) + * that customize Node.js module resolution and loading behavior. + * @since v22.15.0 + * @experimental + */ + function registerHooks(options: RegisterHooksOptions): ModuleHooks; + interface StripTypeScriptTypesOptions { + /** + * Possible values are: + * * `'strip'` Only strip type annotations without performing the transformation of TypeScript features. + * * `'transform'` Strip type annotations and transform TypeScript features to JavaScript. + * @default 'strip' + */ + mode?: "strip" | "transform" | undefined; + /** + * Only when `mode` is `'transform'`, if `true`, a source map + * will be generated for the transformed code. + * @default false + */ + sourceMap?: boolean | undefined; + /** + * Specifies the source url used in the source map. + */ + sourceUrl?: string | undefined; + } + /** + * `module.stripTypeScriptTypes()` removes type annotations from TypeScript code. It + * can be used to strip type annotations from TypeScript code before running it + * with `vm.runInContext()` or `vm.compileFunction()`. + * By default, it will throw an error if the code contains TypeScript features + * that require transformation such as `Enums`, + * see [type-stripping](https://nodejs.org/docs/latest-v25.x/api/typescript.md#type-stripping) for more information. + * When mode is `'transform'`, it also transforms TypeScript features to JavaScript, + * see [transform TypeScript features](https://nodejs.org/docs/latest-v25.x/api/typescript.md#typescript-features) for more information. + * When mode is `'strip'`, source maps are not generated, because locations are preserved. + * If `sourceMap` is provided, when mode is `'strip'`, an error will be thrown. + * + * _WARNING_: The output of this function should not be considered stable across Node.js versions, + * due to changes in the TypeScript parser. + * + * ```js + * import { stripTypeScriptTypes } from 'node:module'; + * const code = 'const a: number = 1;'; + * const strippedCode = stripTypeScriptTypes(code); + * console.log(strippedCode); + * // Prints: const a = 1; + * ``` + * + * If `sourceUrl` is provided, it will be used appended as a comment at the end of the output: + * + * ```js + * import { stripTypeScriptTypes } from 'node:module'; + * const code = 'const a: number = 1;'; + * const strippedCode = stripTypeScriptTypes(code, { mode: 'strip', sourceUrl: 'source.ts' }); + * console.log(strippedCode); + * // Prints: const a = 1\n\n//# sourceURL=source.ts; + * ``` + * + * When `mode` is `'transform'`, the code is transformed to JavaScript: + * + * ```js + * import { stripTypeScriptTypes } from 'node:module'; + * const code = ` + * namespace MathUtil { + * export const add = (a: number, b: number) => a + b; + * }`; + * const strippedCode = stripTypeScriptTypes(code, { mode: 'transform', sourceMap: true }); + * console.log(strippedCode); + * // Prints: + * // var MathUtil; + * // (function(MathUtil) { + * // MathUtil.add = (a, b)=>a + b; + * // })(MathUtil || (MathUtil = {})); + * // # sourceMappingURL=data:application/json;base64, ... + * ``` + * @since v22.13.0 + * @param code The code to strip type annotations from. + * @returns The code with type annotations stripped. + */ + function stripTypeScriptTypes(code: string, options?: StripTypeScriptTypesOptions): string; + /* eslint-enable @definitelytyped/no-unnecessary-generics */ + /** + * The `module.syncBuiltinESMExports()` method updates all the live bindings for + * builtin `ES Modules` to match the properties of the `CommonJS` exports. It + * does not add or remove exported names from the `ES Modules`. + * + * ```js + * import fs from 'node:fs'; + * import assert from 'node:assert'; + * import { syncBuiltinESMExports } from 'node:module'; + * + * fs.readFile = newAPI; + * + * delete fs.readFileSync; + * + * function newAPI() { + * // ... + * } + * + * fs.newAPI = newAPI; + * + * syncBuiltinESMExports(); + * + * import('node:fs').then((esmFS) => { + * // It syncs the existing readFile property with the new value + * assert.strictEqual(esmFS.readFile, newAPI); + * // readFileSync has been deleted from the required fs + * assert.strictEqual('readFileSync' in fs, false); + * // syncBuiltinESMExports() does not remove readFileSync from esmFS + * assert.strictEqual('readFileSync' in esmFS, true); + * // syncBuiltinESMExports() does not add names + * assert.strictEqual(esmFS.newAPI, undefined); + * }); + * ``` + * @since v12.12.0 + */ + function syncBuiltinESMExports(): void; + interface ImportAttributes extends NodeJS.Dict { + type?: string | undefined; + } + type ImportPhase = "source" | "evaluation"; + type ModuleFormat = + | "addon" + | "builtin" + | "commonjs" + | "commonjs-typescript" + | "json" + | "module" + | "module-typescript" + | "wasm"; + type ModuleSource = string | ArrayBuffer | NodeJS.TypedArray; + /** + * The `initialize` hook provides a way to define a custom function that runs in + * the hooks thread when the hooks module is initialized. Initialization happens + * when the hooks module is registered via {@link register}. + * + * This hook can receive data from a {@link register} invocation, including + * ports and other transferable objects. The return value of `initialize` can be a + * `Promise`, in which case it will be awaited before the main application thread + * execution resumes. + */ + type InitializeHook = (data: Data) => void | Promise; + interface ResolveHookContext { + /** + * Export conditions of the relevant `package.json` + */ + conditions: string[]; + /** + * An object whose key-value pairs represent the assertions for the module to import + */ + importAttributes: ImportAttributes; + /** + * The module importing this one, or undefined if this is the Node.js entry point + */ + parentURL: string | undefined; + } + interface ResolveFnOutput { + /** + * A hint to the load hook (it might be ignored); can be an intermediary value. + */ + format?: string | null | undefined; + /** + * The import attributes to use when caching the module (optional; if excluded the input will be used) + */ + importAttributes?: ImportAttributes | undefined; + /** + * A signal that this hook intends to terminate the chain of `resolve` hooks. + * @default false + */ + shortCircuit?: boolean | undefined; + /** + * The absolute URL to which this input resolves + */ + url: string; + } + /** + * The `resolve` hook chain is responsible for telling Node.js where to find and + * how to cache a given `import` statement or expression, or `require` call. It can + * optionally return a format (such as `'module'`) as a hint to the `load` hook. If + * a format is specified, the `load` hook is ultimately responsible for providing + * the final `format` value (and it is free to ignore the hint provided by + * `resolve`); if `resolve` provides a `format`, a custom `load` hook is required + * even if only to pass the value to the Node.js default `load` hook. + */ + type ResolveHook = ( + specifier: string, + context: ResolveHookContext, + nextResolve: ( + specifier: string, + context?: Partial, + ) => ResolveFnOutput | Promise, + ) => ResolveFnOutput | Promise; + type ResolveHookSync = ( + specifier: string, + context: ResolveHookContext, + nextResolve: ( + specifier: string, + context?: Partial, + ) => ResolveFnOutput, + ) => ResolveFnOutput; + interface LoadHookContext { + /** + * Export conditions of the relevant `package.json` + */ + conditions: string[]; + /** + * The format optionally supplied by the `resolve` hook chain (can be an intermediary value). + */ + format: string | null | undefined; + /** + * An object whose key-value pairs represent the assertions for the module to import + */ + importAttributes: ImportAttributes; + } + interface LoadFnOutput { + format: string | null | undefined; + /** + * A signal that this hook intends to terminate the chain of `resolve` hooks. + * @default false + */ + shortCircuit?: boolean | undefined; + /** + * The source for Node.js to evaluate + */ + source?: ModuleSource | undefined; + } + /** + * The `load` hook provides a way to define a custom method of determining how a + * URL should be interpreted, retrieved, and parsed. It is also in charge of + * validating the import attributes. + */ + type LoadHook = ( + url: string, + context: LoadHookContext, + nextLoad: ( + url: string, + context?: Partial, + ) => LoadFnOutput | Promise, + ) => LoadFnOutput | Promise; + type LoadHookSync = ( + url: string, + context: LoadHookContext, + nextLoad: ( + url: string, + context?: Partial, + ) => LoadFnOutput, + ) => LoadFnOutput; + interface SourceMapsSupport { + /** + * If the source maps support is enabled + */ + enabled: boolean; + /** + * If the support is enabled for files in `node_modules`. + */ + nodeModules: boolean; + /** + * If the support is enabled for generated code from `eval` or `new Function`. + */ + generatedCode: boolean; + } + /** + * This method returns whether the [Source Map v3](https://tc39.es/ecma426/) support for stack + * traces is enabled. + * @since v23.7.0, v22.14.0 + */ + function getSourceMapsSupport(): SourceMapsSupport; + /** + * `path` is the resolved path for the file for which a corresponding source map + * should be fetched. + * @since v13.7.0, v12.17.0 + * @return Returns `module.SourceMap` if a source map is found, `undefined` otherwise. + */ + function findSourceMap(path: string): SourceMap | undefined; + interface SetSourceMapsSupportOptions { + /** + * If enabling the support for files in `node_modules`. + * @default false + */ + nodeModules?: boolean | undefined; + /** + * If enabling the support for generated code from `eval` or `new Function`. + * @default false + */ + generatedCode?: boolean | undefined; + } + /** + * This function enables or disables the [Source Map v3](https://tc39.es/ecma426/) support for + * stack traces. + * + * It provides same features as launching Node.js process with commandline options + * `--enable-source-maps`, with additional options to alter the support for files + * in `node_modules` or generated codes. + * + * Only source maps in JavaScript files that are loaded after source maps has been + * enabled will be parsed and loaded. Preferably, use the commandline options + * `--enable-source-maps` to avoid losing track of source maps of modules loaded + * before this API call. + * @since v23.7.0, v22.14.0 + */ + function setSourceMapsSupport(enabled: boolean, options?: SetSourceMapsSupportOptions): void; + interface SourceMapConstructorOptions { + /** + * @since v21.0.0, v20.5.0 + */ + lineLengths?: readonly number[] | undefined; + } + interface SourceMapPayload { + file: string; + version: number; + sources: string[]; + sourcesContent: string[]; + names: string[]; + mappings: string; + sourceRoot: string; + } + interface SourceMapping { + generatedLine: number; + generatedColumn: number; + originalSource: string; + originalLine: number; + originalColumn: number; + } + interface SourceOrigin { + /** + * The name of the range in the source map, if one was provided + */ + name: string | undefined; + /** + * The file name of the original source, as reported in the SourceMap + */ + fileName: string; + /** + * The 1-indexed lineNumber of the corresponding call site in the original source + */ + lineNumber: number; + /** + * The 1-indexed columnNumber of the corresponding call site in the original source + */ + columnNumber: number; + } + /** + * @since v13.7.0, v12.17.0 + */ + class SourceMap { + constructor(payload: SourceMapPayload, options?: SourceMapConstructorOptions); + /** + * Getter for the payload used to construct the `SourceMap` instance. + */ + readonly payload: SourceMapPayload; + /** + * Given a line offset and column offset in the generated source + * file, returns an object representing the SourceMap range in the + * original file if found, or an empty object if not. + * + * The object returned contains the following keys: + * + * The returned value represents the raw range as it appears in the + * SourceMap, based on zero-indexed offsets, _not_ 1-indexed line and + * column numbers as they appear in Error messages and CallSite + * objects. + * + * To get the corresponding 1-indexed line and column numbers from a + * lineNumber and columnNumber as they are reported by Error stacks + * and CallSite objects, use `sourceMap.findOrigin(lineNumber, columnNumber)` + * @param lineOffset The zero-indexed line number offset in the generated source + * @param columnOffset The zero-indexed column number offset in the generated source + */ + findEntry(lineOffset: number, columnOffset: number): SourceMapping | {}; + /** + * Given a 1-indexed `lineNumber` and `columnNumber` from a call site in the generated source, + * find the corresponding call site location in the original source. + * + * If the `lineNumber` and `columnNumber` provided are not found in any source map, + * then an empty object is returned. + * @param lineNumber The 1-indexed line number of the call site in the generated source + * @param columnNumber The 1-indexed column number of the call site in the generated source + */ + findOrigin(lineNumber: number, columnNumber: number): SourceOrigin | {}; + } + function runMain(main?: string): void; + function wrap(script: string): string; + } + global { + namespace NodeJS { + interface Module { + /** + * The module objects required for the first time by this one. + * @since v0.1.16 + */ + children: Module[]; + /** + * The `module.exports` object is created by the `Module` system. Sometimes this is + * not acceptable; many want their module to be an instance of some class. To do + * this, assign the desired export object to `module.exports`. + * @since v0.1.16 + */ + exports: any; + /** + * The fully resolved filename of the module. + * @since v0.1.16 + */ + filename: string; + /** + * The identifier for the module. Typically this is the fully resolved + * filename. + * @since v0.1.16 + */ + id: string; + /** + * `true` if the module is running during the Node.js preload + * phase. + * @since v15.4.0, v14.17.0 + */ + isPreloading: boolean; + /** + * Whether or not the module is done loading, or is in the process of + * loading. + * @since v0.1.16 + */ + loaded: boolean; + /** + * The module that first required this one, or `null` if the current module is the + * entry point of the current process, or `undefined` if the module was loaded by + * something that is not a CommonJS module (e.g. REPL or `import`). + * @since v0.1.16 + * @deprecated Please use `require.main` and `module.children` instead. + */ + parent: Module | null | undefined; + /** + * The directory name of the module. This is usually the same as the + * `path.dirname()` of the `module.id`. + * @since v11.14.0 + */ + path: string; + /** + * The search paths for the module. + * @since v0.4.0 + */ + paths: string[]; + /** + * The `module.require()` method provides a way to load a module as if + * `require()` was called from the original module. + * @since v0.5.1 + */ + require(id: string): any; + } + interface Require { + /** + * Used to import modules, `JSON`, and local files. + * @since v0.1.13 + */ + (id: string): any; + /** + * Modules are cached in this object when they are required. By deleting a key + * value from this object, the next `require` will reload the module. + * This does not apply to + * [native addons](https://nodejs.org/docs/latest-v25.x/api/addons.html), + * for which reloading will result in an error. + * @since v0.3.0 + */ + cache: Dict; + /** + * Instruct `require` on how to handle certain file extensions. + * @since v0.3.0 + * @deprecated + */ + extensions: RequireExtensions; + /** + * The `Module` object representing the entry script loaded when the Node.js + * process launched, or `undefined` if the entry point of the program is not a + * CommonJS module. + * @since v0.1.17 + */ + main: Module | undefined; + /** + * @since v0.3.0 + */ + resolve: RequireResolve; + } + /** @deprecated */ + interface RequireExtensions extends Dict<(module: Module, filename: string) => any> { + ".js": (module: Module, filename: string) => any; + ".json": (module: Module, filename: string) => any; + ".node": (module: Module, filename: string) => any; + } + interface RequireResolveOptions { + /** + * Paths to resolve module location from. If present, these + * paths are used instead of the default resolution paths, with the exception + * of + * [GLOBAL\_FOLDERS](https://nodejs.org/docs/latest-v25.x/api/modules.html#loading-from-the-global-folders) + * like `$HOME/.node_modules`, which are + * always included. Each of these paths is used as a starting point for + * the module resolution algorithm, meaning that the `node_modules` hierarchy + * is checked from this location. + * @since v8.9.0 + */ + paths?: string[] | undefined; + } + interface RequireResolve { + /** + * Use the internal `require()` machinery to look up the location of a module, + * but rather than loading the module, just return the resolved filename. + * + * If the module can not be found, a `MODULE_NOT_FOUND` error is thrown. + * @since v0.3.0 + * @param request The module path to resolve. + */ + (request: string, options?: RequireResolveOptions): string; + /** + * Returns an array containing the paths searched during resolution of `request` or + * `null` if the `request` string references a core module, for example `http` or + * `fs`. + * @since v8.9.0 + * @param request The module path whose lookup paths are being retrieved. + */ + paths(request: string): string[] | null; + } + } + /** + * The directory name of the current module. This is the same as the + * `path.dirname()` of the `__filename`. + * @since v0.1.27 + */ + var __dirname: string; + /** + * The file name of the current module. This is the current module file's absolute + * path with symlinks resolved. + * + * For a main program this is not necessarily the same as the file name used in the + * command line. + * @since v0.0.1 + */ + var __filename: string; + /** + * The `exports` variable is available within a module's file-level scope, and is + * assigned the value of `module.exports` before the module is evaluated. + * @since v0.1.16 + */ + var exports: NodeJS.Module["exports"]; + /** + * A reference to the current module. + * @since v0.1.16 + */ + var module: NodeJS.Module; + /** + * @since v0.1.13 + */ + var require: NodeJS.Require; + // Global-scope aliases for backwards compatibility with @types/node <13.0.x + // TODO: consider removing in a future major version update + /** @deprecated Use `NodeJS.Module` instead. */ + interface NodeModule extends NodeJS.Module {} + /** @deprecated Use `NodeJS.Require` instead. */ + interface NodeRequire extends NodeJS.Require {} + /** @deprecated Use `NodeJS.RequireResolve` instead. */ + interface RequireResolve extends NodeJS.RequireResolve {} + } + export = Module; +} +declare module "module" { + import module = require("node:module"); + export = module; +} diff --git a/backend/node_modules/@types/node/net.d.ts b/backend/node_modules/@types/node/net.d.ts new file mode 100644 index 0000000..e0cf837 --- /dev/null +++ b/backend/node_modules/@types/node/net.d.ts @@ -0,0 +1,933 @@ +/** + * > Stability: 2 - Stable + * + * The `node:net` module provides an asynchronous network API for creating stream-based + * TCP or `IPC` servers ({@link createServer}) and clients + * ({@link createConnection}). + * + * It can be accessed using: + * + * ```js + * import net from 'node:net'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/net.js) + */ +declare module "node:net" { + import { NonSharedBuffer } from "node:buffer"; + import * as dns from "node:dns"; + import { Abortable, EventEmitter, InternalEventEmitter } from "node:events"; + import * as stream from "node:stream"; + type LookupFunction = ( + hostname: string, + options: dns.LookupOptions, + callback: (err: NodeJS.ErrnoException | null, address: string | dns.LookupAddress[], family?: number) => void, + ) => void; + interface AddressInfo { + address: string; + family: string; + port: number; + } + interface SocketConstructorOpts { + fd?: number | undefined; + allowHalfOpen?: boolean | undefined; + onread?: OnReadOpts | undefined; + readable?: boolean | undefined; + writable?: boolean | undefined; + signal?: AbortSignal | undefined; + } + interface OnReadOpts { + buffer: Uint8Array | (() => Uint8Array); + /** + * This function is called for every chunk of incoming data. + * Two arguments are passed to it: the number of bytes written to `buffer` and a reference to `buffer`. + * Return `false` from this function to implicitly `pause()` the socket. + */ + callback(bytesWritten: number, buffer: Uint8Array): boolean; + } + interface TcpSocketConnectOpts { + port: number; + host?: string | undefined; + localAddress?: string | undefined; + localPort?: number | undefined; + hints?: number | undefined; + family?: number | undefined; + lookup?: LookupFunction | undefined; + noDelay?: boolean | undefined; + keepAlive?: boolean | undefined; + keepAliveInitialDelay?: number | undefined; + /** + * @since v18.13.0 + */ + autoSelectFamily?: boolean | undefined; + /** + * @since v18.13.0 + */ + autoSelectFamilyAttemptTimeout?: number | undefined; + blockList?: BlockList | undefined; + } + interface IpcSocketConnectOpts { + path: string; + } + type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts; + type SocketReadyState = "opening" | "open" | "readOnly" | "writeOnly" | "closed"; + interface SocketEventMap extends Omit { + "close": [hadError: boolean]; + "connect": []; + "connectionAttempt": [ip: string, port: number, family: number]; + "connectionAttemptFailed": [ip: string, port: number, family: number, error: Error]; + "connectionAttemptTimeout": [ip: string, port: number, family: number]; + "data": [data: string | NonSharedBuffer]; + "lookup": [err: Error | null, address: string, family: number | null, host: string]; + "ready": []; + "timeout": []; + } + /** + * This class is an abstraction of a TCP socket or a streaming `IPC` endpoint + * (uses named pipes on Windows, and Unix domain sockets otherwise). It is also + * an `EventEmitter`. + * + * A `net.Socket` can be created by the user and used directly to interact with + * a server. For example, it is returned by {@link createConnection}, + * so the user can use it to talk to the server. + * + * It can also be created by Node.js and passed to the user when a connection + * is received. For example, it is passed to the listeners of a `'connection'` event emitted on a {@link Server}, so the user can use + * it to interact with the client. + * @since v0.3.4 + */ + class Socket extends stream.Duplex { + constructor(options?: SocketConstructorOpts); + /** + * Destroys the socket after all data is written. If the `finish` event was already emitted the socket is destroyed immediately. + * If the socket is still writable it implicitly calls `socket.end()`. + * @since v0.3.4 + */ + destroySoon(): void; + /** + * Sends data on the socket. The second parameter specifies the encoding in the + * case of a string. It defaults to UTF8 encoding. + * + * Returns `true` if the entire data was flushed successfully to the kernel + * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is again free. + * + * The optional `callback` parameter will be executed when the data is finally + * written out, which may not be immediately. + * + * See `Writable` stream `write()` method for more + * information. + * @since v0.1.90 + * @param [encoding='utf8'] Only used when data is `string`. + */ + write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean; + write(str: Uint8Array | string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean; + /** + * Initiate a connection on a given socket. + * + * Possible signatures: + * + * * `socket.connect(options[, connectListener])` + * * `socket.connect(path[, connectListener])` for `IPC` connections. + * * `socket.connect(port[, host][, connectListener])` for TCP connections. + * * Returns: `net.Socket` The socket itself. + * + * This function is asynchronous. When the connection is established, the `'connect'` event will be emitted. If there is a problem connecting, + * instead of a `'connect'` event, an `'error'` event will be emitted with + * the error passed to the `'error'` listener. + * The last parameter `connectListener`, if supplied, will be added as a listener + * for the `'connect'` event **once**. + * + * This function should only be used for reconnecting a socket after`'close'` has been emitted or otherwise it may lead to undefined + * behavior. + */ + connect(options: SocketConnectOpts, connectionListener?: () => void): this; + connect(port: number, host: string, connectionListener?: () => void): this; + connect(port: number, connectionListener?: () => void): this; + connect(path: string, connectionListener?: () => void): this; + /** + * Set the encoding for the socket as a `Readable Stream`. See `readable.setEncoding()` for more information. + * @since v0.1.90 + * @return The socket itself. + */ + setEncoding(encoding?: BufferEncoding): this; + /** + * Pauses the reading of data. That is, `'data'` events will not be emitted. + * Useful to throttle back an upload. + * @return The socket itself. + */ + pause(): this; + /** + * Close the TCP connection by sending an RST packet and destroy the stream. + * If this TCP socket is in connecting status, it will send an RST packet and destroy this TCP socket once it is connected. + * Otherwise, it will call `socket.destroy` with an `ERR_SOCKET_CLOSED` Error. + * If this is not a TCP socket (for example, a pipe), calling this method will immediately throw an `ERR_INVALID_HANDLE_TYPE` Error. + * @since v18.3.0, v16.17.0 + */ + resetAndDestroy(): this; + /** + * Resumes reading after a call to `socket.pause()`. + * @return The socket itself. + */ + resume(): this; + /** + * Sets the socket to timeout after `timeout` milliseconds of inactivity on + * the socket. By default `net.Socket` do not have a timeout. + * + * When an idle timeout is triggered the socket will receive a `'timeout'` event but the connection will not be severed. The user must manually call `socket.end()` or `socket.destroy()` to + * end the connection. + * + * ```js + * socket.setTimeout(3000); + * socket.on('timeout', () => { + * console.log('socket timeout'); + * socket.end(); + * }); + * ``` + * + * If `timeout` is 0, then the existing idle timeout is disabled. + * + * The optional `callback` parameter will be added as a one-time listener for the `'timeout'` event. + * @since v0.1.90 + * @return The socket itself. + */ + setTimeout(timeout: number, callback?: () => void): this; + /** + * Enable/disable the use of Nagle's algorithm. + * + * When a TCP connection is created, it will have Nagle's algorithm enabled. + * + * Nagle's algorithm delays data before it is sent via the network. It attempts + * to optimize throughput at the expense of latency. + * + * Passing `true` for `noDelay` or not passing an argument will disable Nagle's + * algorithm for the socket. Passing `false` for `noDelay` will enable Nagle's + * algorithm. + * @since v0.1.90 + * @param [noDelay=true] + * @return The socket itself. + */ + setNoDelay(noDelay?: boolean): this; + /** + * Enable/disable keep-alive functionality, and optionally set the initial + * delay before the first keepalive probe is sent on an idle socket. + * + * Set `initialDelay` (in milliseconds) to set the delay between the last + * data packet received and the first keepalive probe. Setting `0` for`initialDelay` will leave the value unchanged from the default + * (or previous) setting. + * + * Enabling the keep-alive functionality will set the following socket options: + * + * * `SO_KEEPALIVE=1` + * * `TCP_KEEPIDLE=initialDelay` + * * `TCP_KEEPCNT=10` + * * `TCP_KEEPINTVL=1` + * @since v0.1.92 + * @param [enable=false] + * @param [initialDelay=0] + * @return The socket itself. + */ + setKeepAlive(enable?: boolean, initialDelay?: number): this; + /** + * Returns the bound `address`, the address `family` name and `port` of the + * socket as reported by the operating system:`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` + * @since v0.1.90 + */ + address(): AddressInfo | {}; + /** + * Calling `unref()` on a socket will allow the program to exit if this is the only + * active socket in the event system. If the socket is already `unref`ed calling`unref()` again will have no effect. + * @since v0.9.1 + * @return The socket itself. + */ + unref(): this; + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref`ed socket will _not_ let the program exit if it's the only socket left (the default behavior). + * If the socket is `ref`ed calling `ref` again will have no effect. + * @since v0.9.1 + * @return The socket itself. + */ + ref(): this; + /** + * This property is only present if the family autoselection algorithm is enabled in `socket.connect(options)` + * and it is an array of the addresses that have been attempted. + * + * Each address is a string in the form of `$IP:$PORT`. + * If the connection was successful, then the last address is the one that the socket is currently connected to. + * @since v19.4.0 + */ + readonly autoSelectFamilyAttemptedAddresses: string[]; + /** + * This property shows the number of characters buffered for writing. The buffer + * may contain strings whose length after encoding is not yet known. So this number + * is only an approximation of the number of bytes in the buffer. + * + * `net.Socket` has the property that `socket.write()` always works. This is to + * help users get up and running quickly. The computer cannot always keep up + * with the amount of data that is written to a socket. The network connection + * simply might be too slow. Node.js will internally queue up the data written to a + * socket and send it out over the wire when it is possible. + * + * The consequence of this internal buffering is that memory may grow. + * Users who experience large or growing `bufferSize` should attempt to + * "throttle" the data flows in their program with `socket.pause()` and `socket.resume()`. + * @since v0.3.8 + * @deprecated Since v14.6.0 - Use `writableLength` instead. + */ + readonly bufferSize: number; + /** + * The amount of received bytes. + * @since v0.5.3 + */ + readonly bytesRead: number; + /** + * The amount of bytes sent. + * @since v0.5.3 + */ + readonly bytesWritten: number; + /** + * If `true`, `socket.connect(options[, connectListener])` was + * called and has not yet finished. It will stay `true` until the socket becomes + * connected, then it is set to `false` and the `'connect'` event is emitted. Note + * that the `socket.connect(options[, connectListener])` callback is a listener for the `'connect'` event. + * @since v6.1.0 + */ + readonly connecting: boolean; + /** + * This is `true` if the socket is not connected yet, either because `.connect()`has not yet been called or because it is still in the process of connecting + * (see `socket.connecting`). + * @since v11.2.0, v10.16.0 + */ + readonly pending: boolean; + /** + * See `writable.destroyed` for further details. + */ + readonly destroyed: boolean; + /** + * The string representation of the local IP address the remote client is + * connecting on. For example, in a server listening on `'0.0.0.0'`, if a client + * connects on `'192.168.1.1'`, the value of `socket.localAddress` would be`'192.168.1.1'`. + * @since v0.9.6 + */ + readonly localAddress?: string; + /** + * The numeric representation of the local port. For example, `80` or `21`. + * @since v0.9.6 + */ + readonly localPort?: number; + /** + * The string representation of the local IP family. `'IPv4'` or `'IPv6'`. + * @since v18.8.0, v16.18.0 + */ + readonly localFamily?: string; + /** + * This property represents the state of the connection as a string. + * + * * If the stream is connecting `socket.readyState` is `opening`. + * * If the stream is readable and writable, it is `open`. + * * If the stream is readable and not writable, it is `readOnly`. + * * If the stream is not readable and writable, it is `writeOnly`. + * @since v0.5.0 + */ + readonly readyState: SocketReadyState; + /** + * The string representation of the remote IP address. For example,`'74.125.127.100'` or `'2001:4860:a005::68'`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.5.10 + */ + readonly remoteAddress: string | undefined; + /** + * The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.11.14 + */ + readonly remoteFamily: string | undefined; + /** + * The numeric representation of the remote port. For example, `80` or `21`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.5.10 + */ + readonly remotePort: number | undefined; + /** + * The socket timeout in milliseconds as set by `socket.setTimeout()`. + * It is `undefined` if a timeout has not been set. + * @since v10.7.0 + */ + readonly timeout?: number; + /** + * Half-closes the socket. i.e., it sends a FIN packet. It is possible the + * server will still send some data. + * + * See `writable.end()` for further details. + * @since v0.1.90 + * @param [encoding='utf8'] Only used when data is `string`. + * @param callback Optional callback for when the socket is finished. + * @return The socket itself. + */ + end(callback?: () => void): this; + end(buffer: Uint8Array | string, callback?: () => void): this; + end(str: Uint8Array | string, encoding?: BufferEncoding, callback?: () => void): this; + // #region InternalEventEmitter + addListener(eventName: E, listener: (...args: SocketEventMap[E]) => void): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: SocketEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: SocketEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners(eventName: E): ((...args: SocketEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off(eventName: E, listener: (...args: SocketEventMap[E]) => void): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on(eventName: E, listener: (...args: SocketEventMap[E]) => void): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once(eventName: E, listener: (...args: SocketEventMap[E]) => void): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: SocketEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: SocketEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners(eventName: E): ((...args: SocketEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: SocketEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + interface ListenOptions extends Abortable { + backlog?: number | undefined; + exclusive?: boolean | undefined; + host?: string | undefined; + /** + * @default false + */ + ipv6Only?: boolean | undefined; + reusePort?: boolean | undefined; + path?: string | undefined; + port?: number | undefined; + readableAll?: boolean | undefined; + writableAll?: boolean | undefined; + } + interface ServerOpts { + /** + * Indicates whether half-opened TCP connections are allowed. + * @default false + */ + allowHalfOpen?: boolean | undefined; + /** + * Indicates whether the socket should be paused on incoming connections. + * @default false + */ + pauseOnConnect?: boolean | undefined; + /** + * If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. + * @default false + * @since v16.5.0 + */ + noDelay?: boolean | undefined; + /** + * If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, + * similarly on what is done in `socket.setKeepAlive([enable][, initialDelay])`. + * @default false + * @since v16.5.0 + */ + keepAlive?: boolean | undefined; + /** + * If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. + * @default 0 + * @since v16.5.0 + */ + keepAliveInitialDelay?: number | undefined; + /** + * Optionally overrides all `net.Socket`s' `readableHighWaterMark` and `writableHighWaterMark`. + * @default See [stream.getDefaultHighWaterMark()](https://nodejs.org/docs/latest-v25.x/api/stream.html#streamgetdefaulthighwatermarkobjectmode). + * @since v18.17.0, v20.1.0 + */ + highWaterMark?: number | undefined; + /** + * `blockList` can be used for disabling inbound + * access to specific IP addresses, IP ranges, or IP subnets. This does not + * work if the server is behind a reverse proxy, NAT, etc. because the address + * checked against the block list is the address of the proxy, or the one + * specified by the NAT. + * @since v22.13.0 + */ + blockList?: BlockList | undefined; + } + interface DropArgument { + localAddress?: string; + localPort?: number; + localFamily?: string; + remoteAddress?: string; + remotePort?: number; + remoteFamily?: string; + } + interface ServerEventMap { + "close": []; + "connection": [socket: Socket]; + "error": [err: Error]; + "listening": []; + "drop": [data?: DropArgument]; + } + /** + * This class is used to create a TCP or `IPC` server. + * @since v0.1.90 + */ + class Server implements EventEmitter { + constructor(connectionListener?: (socket: Socket) => void); + constructor(options?: ServerOpts, connectionListener?: (socket: Socket) => void); + /** + * Start a server listening for connections. A `net.Server` can be a TCP or + * an `IPC` server depending on what it listens to. + * + * Possible signatures: + * + * * `server.listen(handle[, backlog][, callback])` + * * `server.listen(options[, callback])` + * * `server.listen(path[, backlog][, callback])` for `IPC` servers + * * `server.listen([port[, host[, backlog]]][, callback])` for TCP servers + * + * This function is asynchronous. When the server starts listening, the `'listening'` event will be emitted. The last parameter `callback`will be added as a listener for the `'listening'` + * event. + * + * All `listen()` methods can take a `backlog` parameter to specify the maximum + * length of the queue of pending connections. The actual length will be determined + * by the OS through sysctl settings such as `tcp_max_syn_backlog` and `somaxconn` on Linux. The default value of this parameter is 511 (not 512). + * + * All {@link Socket} are set to `SO_REUSEADDR` (see [`socket(7)`](https://man7.org/linux/man-pages/man7/socket.7.html) for + * details). + * + * The `server.listen()` method can be called again if and only if there was an + * error during the first `server.listen()` call or `server.close()` has been + * called. Otherwise, an `ERR_SERVER_ALREADY_LISTEN` error will be thrown. + * + * One of the most common errors raised when listening is `EADDRINUSE`. + * This happens when another server is already listening on the requested`port`/`path`/`handle`. One way to handle this would be to retry + * after a certain amount of time: + * + * ```js + * server.on('error', (e) => { + * if (e.code === 'EADDRINUSE') { + * console.error('Address in use, retrying...'); + * setTimeout(() => { + * server.close(); + * server.listen(PORT, HOST); + * }, 1000); + * } + * }); + * ``` + */ + listen(port?: number, hostname?: string, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, hostname?: string, listeningListener?: () => void): this; + listen(port?: number, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, listeningListener?: () => void): this; + listen(path: string, backlog?: number, listeningListener?: () => void): this; + listen(path: string, listeningListener?: () => void): this; + listen(options: ListenOptions, listeningListener?: () => void): this; + listen(handle: any, backlog?: number, listeningListener?: () => void): this; + listen(handle: any, listeningListener?: () => void): this; + /** + * Stops the server from accepting new connections and keeps existing + * connections. This function is asynchronous, the server is finally closed + * when all connections are ended and the server emits a `'close'` event. + * The optional `callback` will be called once the `'close'` event occurs. Unlike + * that event, it will be called with an `Error` as its only argument if the server + * was not open when it was closed. + * @since v0.1.90 + * @param callback Called when the server is closed. + */ + close(callback?: (err?: Error) => void): this; + /** + * Returns the bound `address`, the address `family` name, and `port` of the server + * as reported by the operating system if listening on an IP socket + * (useful to find which port was assigned when getting an OS-assigned address):`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`. + * + * For a server listening on a pipe or Unix domain socket, the name is returned + * as a string. + * + * ```js + * const server = net.createServer((socket) => { + * socket.end('goodbye\n'); + * }).on('error', (err) => { + * // Handle errors here. + * throw err; + * }); + * + * // Grab an arbitrary unused port. + * server.listen(() => { + * console.log('opened server on', server.address()); + * }); + * ``` + * + * `server.address()` returns `null` before the `'listening'` event has been + * emitted or after calling `server.close()`. + * @since v0.1.90 + */ + address(): AddressInfo | string | null; + /** + * Asynchronously get the number of concurrent connections on the server. Works + * when sockets were sent to forks. + * + * Callback should take two arguments `err` and `count`. + * @since v0.9.7 + */ + getConnections(cb: (error: Error | null, count: number) => void): this; + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref`ed server will _not_ let the program exit if it's the only server left (the default behavior). + * If the server is `ref`ed calling `ref()` again will have no effect. + * @since v0.9.1 + */ + ref(): this; + /** + * Calling `unref()` on a server will allow the program to exit if this is the only + * active server in the event system. If the server is already `unref`ed calling`unref()` again will have no effect. + * @since v0.9.1 + */ + unref(): this; + /** + * Set this property to reject connections when the server's connection count gets + * high. + * + * It is not recommended to use this option once a socket has been sent to a child + * with `child_process.fork()`. + * @since v0.2.0 + */ + maxConnections: number; + connections: number; + /** + * Indicates whether or not the server is listening for connections. + * @since v5.7.0 + */ + readonly listening: boolean; + /** + * Calls {@link Server.close()} and returns a promise that fulfills when the server has closed. + * @since v20.5.0 + */ + [Symbol.asyncDispose](): Promise; + } + interface Server extends InternalEventEmitter {} + type IPVersion = "ipv4" | "ipv6"; + /** + * The `BlockList` object can be used with some network APIs to specify rules for + * disabling inbound or outbound access to specific IP addresses, IP ranges, or + * IP subnets. + * @since v15.0.0, v14.18.0 + */ + class BlockList { + /** + * Adds a rule to block the given IP address. + * @since v15.0.0, v14.18.0 + * @param address An IPv4 or IPv6 address. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addAddress(address: string, type?: IPVersion): void; + addAddress(address: SocketAddress): void; + /** + * Adds a rule to block a range of IP addresses from `start` (inclusive) to`end` (inclusive). + * @since v15.0.0, v14.18.0 + * @param start The starting IPv4 or IPv6 address in the range. + * @param end The ending IPv4 or IPv6 address in the range. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addRange(start: string, end: string, type?: IPVersion): void; + addRange(start: SocketAddress, end: SocketAddress): void; + /** + * Adds a rule to block a range of IP addresses specified as a subnet mask. + * @since v15.0.0, v14.18.0 + * @param net The network IPv4 or IPv6 address. + * @param prefix The number of CIDR prefix bits. For IPv4, this must be a value between `0` and `32`. For IPv6, this must be between `0` and `128`. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addSubnet(net: SocketAddress, prefix: number): void; + addSubnet(net: string, prefix: number, type?: IPVersion): void; + /** + * Returns `true` if the given IP address matches any of the rules added to the`BlockList`. + * + * ```js + * const blockList = new net.BlockList(); + * blockList.addAddress('123.123.123.123'); + * blockList.addRange('10.0.0.1', '10.0.0.10'); + * blockList.addSubnet('8592:757c:efae:4e45::', 64, 'ipv6'); + * + * console.log(blockList.check('123.123.123.123')); // Prints: true + * console.log(blockList.check('10.0.0.3')); // Prints: true + * console.log(blockList.check('222.111.111.222')); // Prints: false + * + * // IPv6 notation for IPv4 addresses works: + * console.log(blockList.check('::ffff:7b7b:7b7b', 'ipv6')); // Prints: true + * console.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true + * ``` + * @since v15.0.0, v14.18.0 + * @param address The IP address to check + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + check(address: SocketAddress): boolean; + check(address: string, type?: IPVersion): boolean; + /** + * The list of rules added to the blocklist. + * @since v15.0.0, v14.18.0 + */ + rules: readonly string[]; + /** + * Returns `true` if the `value` is a `net.BlockList`. + * @since v22.13.0 + * @param value Any JS value + */ + static isBlockList(value: unknown): value is BlockList; + /** + * ```js + * const blockList = new net.BlockList(); + * const data = [ + * 'Subnet: IPv4 192.168.1.0/24', + * 'Address: IPv4 10.0.0.5', + * 'Range: IPv4 192.168.2.1-192.168.2.10', + * 'Range: IPv4 10.0.0.1-10.0.0.10', + * ]; + * blockList.fromJSON(data); + * blockList.fromJSON(JSON.stringify(data)); + * ``` + * @since v24.5.0 + * @experimental + */ + fromJSON(data: string | readonly string[]): void; + /** + * @since v24.5.0 + * @experimental + */ + toJSON(): readonly string[]; + } + interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts { + timeout?: number | undefined; + } + interface IpcNetConnectOpts extends IpcSocketConnectOpts, SocketConstructorOpts { + timeout?: number | undefined; + } + type NetConnectOpts = TcpNetConnectOpts | IpcNetConnectOpts; + /** + * Creates a new TCP or `IPC` server. + * + * If `allowHalfOpen` is set to `true`, when the other end of the socket + * signals the end of transmission, the server will only send back the end of + * transmission when `socket.end()` is explicitly called. For example, in the + * context of TCP, when a FIN packed is received, a FIN packed is sent + * back only when `socket.end()` is explicitly called. Until then the + * connection is half-closed (non-readable but still writable). See `'end'` event and [RFC 1122](https://tools.ietf.org/html/rfc1122) (section 4.2.2.13) for more information. + * + * If `pauseOnConnect` is set to `true`, then the socket associated with each + * incoming connection will be paused, and no data will be read from its handle. + * This allows connections to be passed between processes without any data being + * read by the original process. To begin reading data from a paused socket, call `socket.resume()`. + * + * The server can be a TCP server or an `IPC` server, depending on what it `listen()` to. + * + * Here is an example of a TCP echo server which listens for connections + * on port 8124: + * + * ```js + * import net from 'node:net'; + * const server = net.createServer((c) => { + * // 'connection' listener. + * console.log('client connected'); + * c.on('end', () => { + * console.log('client disconnected'); + * }); + * c.write('hello\r\n'); + * c.pipe(c); + * }); + * server.on('error', (err) => { + * throw err; + * }); + * server.listen(8124, () => { + * console.log('server bound'); + * }); + * ``` + * + * Test this by using `telnet`: + * + * ```bash + * telnet localhost 8124 + * ``` + * + * To listen on the socket `/tmp/echo.sock`: + * + * ```js + * server.listen('/tmp/echo.sock', () => { + * console.log('server bound'); + * }); + * ``` + * + * Use `nc` to connect to a Unix domain socket server: + * + * ```bash + * nc -U /tmp/echo.sock + * ``` + * @since v0.5.0 + * @param connectionListener Automatically set as a listener for the {@link 'connection'} event. + */ + function createServer(connectionListener?: (socket: Socket) => void): Server; + function createServer(options?: ServerOpts, connectionListener?: (socket: Socket) => void): Server; + /** + * Aliases to {@link createConnection}. + * + * Possible signatures: + * + * * {@link connect} + * * {@link connect} for `IPC` connections. + * * {@link connect} for TCP connections. + */ + function connect(options: NetConnectOpts, connectionListener?: () => void): Socket; + function connect(port: number, host?: string, connectionListener?: () => void): Socket; + function connect(path: string, connectionListener?: () => void): Socket; + /** + * A factory function, which creates a new {@link Socket}, + * immediately initiates connection with `socket.connect()`, + * then returns the `net.Socket` that starts the connection. + * + * When the connection is established, a `'connect'` event will be emitted + * on the returned socket. The last parameter `connectListener`, if supplied, + * will be added as a listener for the `'connect'` event **once**. + * + * Possible signatures: + * + * * {@link createConnection} + * * {@link createConnection} for `IPC` connections. + * * {@link createConnection} for TCP connections. + * + * The {@link connect} function is an alias to this function. + */ + function createConnection(options: NetConnectOpts, connectionListener?: () => void): Socket; + function createConnection(port: number, host?: string, connectionListener?: () => void): Socket; + function createConnection(path: string, connectionListener?: () => void): Socket; + /** + * Gets the current default value of the `autoSelectFamily` option of `socket.connect(options)`. + * The initial default value is `true`, unless the command line option`--no-network-family-autoselection` is provided. + * @since v19.4.0 + */ + function getDefaultAutoSelectFamily(): boolean; + /** + * Sets the default value of the `autoSelectFamily` option of `socket.connect(options)`. + * @param value The new default value. + * The initial default value is `true`, unless the command line option + * `--no-network-family-autoselection` is provided. + * @since v19.4.0 + */ + function setDefaultAutoSelectFamily(value: boolean): void; + /** + * Gets the current default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`. + * The initial default value is `250` or the value specified via the command line option `--network-family-autoselection-attempt-timeout`. + * @returns The current default value of the `autoSelectFamilyAttemptTimeout` option. + * @since v19.8.0, v18.8.0 + */ + function getDefaultAutoSelectFamilyAttemptTimeout(): number; + /** + * Sets the default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`. + * @param value The new default value, which must be a positive number. If the number is less than `10`, the value `10` is used instead. The initial default value is `250` or the value specified via the command line + * option `--network-family-autoselection-attempt-timeout`. + * @since v19.8.0, v18.8.0 + */ + function setDefaultAutoSelectFamilyAttemptTimeout(value: number): void; + /** + * Returns `6` if `input` is an IPv6 address. Returns `4` if `input` is an IPv4 + * address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no leading zeroes. Otherwise, returns`0`. + * + * ```js + * net.isIP('::1'); // returns 6 + * net.isIP('127.0.0.1'); // returns 4 + * net.isIP('127.000.000.001'); // returns 0 + * net.isIP('127.0.0.1/24'); // returns 0 + * net.isIP('fhqwhgads'); // returns 0 + * ``` + * @since v0.3.0 + */ + function isIP(input: string): number; + /** + * Returns `true` if `input` is an IPv4 address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no + * leading zeroes. Otherwise, returns `false`. + * + * ```js + * net.isIPv4('127.0.0.1'); // returns true + * net.isIPv4('127.000.000.001'); // returns false + * net.isIPv4('127.0.0.1/24'); // returns false + * net.isIPv4('fhqwhgads'); // returns false + * ``` + * @since v0.3.0 + */ + function isIPv4(input: string): boolean; + /** + * Returns `true` if `input` is an IPv6 address. Otherwise, returns `false`. + * + * ```js + * net.isIPv6('::1'); // returns true + * net.isIPv6('fhqwhgads'); // returns false + * ``` + * @since v0.3.0 + */ + function isIPv6(input: string): boolean; + interface SocketAddressInitOptions { + /** + * The network address as either an IPv4 or IPv6 string. + * @default 127.0.0.1 + */ + address?: string | undefined; + /** + * @default `'ipv4'` + */ + family?: IPVersion | undefined; + /** + * An IPv6 flow-label used only if `family` is `'ipv6'`. + * @default 0 + */ + flowlabel?: number | undefined; + /** + * An IP port. + * @default 0 + */ + port?: number | undefined; + } + /** + * @since v15.14.0, v14.18.0 + */ + class SocketAddress { + constructor(options: SocketAddressInitOptions); + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0, v14.18.0 + */ + readonly address: string; + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0, v14.18.0 + */ + readonly family: IPVersion; + /** + * @since v15.14.0, v14.18.0 + */ + readonly port: number; + /** + * @since v15.14.0, v14.18.0 + */ + readonly flowlabel: number; + /** + * @since v22.13.0 + * @param input An input string containing an IP address and optional port, + * e.g. `123.1.2.3:1234` or `[1::1]:1234`. + * @returns Returns a `SocketAddress` if parsing was successful. + * Otherwise returns `undefined`. + */ + static parse(input: string): SocketAddress | undefined; + } +} +declare module "net" { + export * from "node:net"; +} diff --git a/backend/node_modules/@types/node/os.d.ts b/backend/node_modules/@types/node/os.d.ts new file mode 100644 index 0000000..db86e9b --- /dev/null +++ b/backend/node_modules/@types/node/os.d.ts @@ -0,0 +1,507 @@ +/** + * The `node:os` module provides operating system-related utility methods and + * properties. It can be accessed using: + * + * ```js + * import os from 'node:os'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/os.js) + */ +declare module "node:os" { + import { NonSharedBuffer } from "buffer"; + interface CpuInfo { + model: string; + speed: number; + times: { + /** The number of milliseconds the CPU has spent in user mode. */ + user: number; + /** The number of milliseconds the CPU has spent in nice mode. */ + nice: number; + /** The number of milliseconds the CPU has spent in sys mode. */ + sys: number; + /** The number of milliseconds the CPU has spent in idle mode. */ + idle: number; + /** The number of milliseconds the CPU has spent in irq mode. */ + irq: number; + }; + } + interface NetworkInterfaceBase { + address: string; + netmask: string; + mac: string; + internal: boolean; + cidr: string | null; + scopeid?: number; + } + interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase { + family: "IPv4"; + } + interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase { + family: "IPv6"; + scopeid: number; + } + interface UserInfo { + username: T; + uid: number; + gid: number; + shell: T | null; + homedir: T; + } + type NetworkInterfaceInfo = NetworkInterfaceInfoIPv4 | NetworkInterfaceInfoIPv6; + /** + * Returns the host name of the operating system as a string. + * @since v0.3.3 + */ + function hostname(): string; + /** + * Returns an array containing the 1, 5, and 15 minute load averages. + * + * The load average is a measure of system activity calculated by the operating + * system and expressed as a fractional number. + * + * The load average is a Unix-specific concept. On Windows, the return value is + * always `[0, 0, 0]`. + * @since v0.3.3 + */ + function loadavg(): number[]; + /** + * Returns the system uptime in number of seconds. + * @since v0.3.3 + */ + function uptime(): number; + /** + * Returns the amount of free system memory in bytes as an integer. + * @since v0.3.3 + */ + function freemem(): number; + /** + * Returns the total amount of system memory in bytes as an integer. + * @since v0.3.3 + */ + function totalmem(): number; + /** + * Returns an array of objects containing information about each logical CPU core. + * The array will be empty if no CPU information is available, such as if the `/proc` file system is unavailable. + * + * The properties included on each object include: + * + * ```js + * [ + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 252020, + * nice: 0, + * sys: 30340, + * idle: 1070356870, + * irq: 0, + * }, + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 306960, + * nice: 0, + * sys: 26980, + * idle: 1071569080, + * irq: 0, + * }, + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 248450, + * nice: 0, + * sys: 21750, + * idle: 1070919370, + * irq: 0, + * }, + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 256880, + * nice: 0, + * sys: 19430, + * idle: 1070905480, + * irq: 20, + * }, + * }, + * ] + * ``` + * + * `nice` values are POSIX-only. On Windows, the `nice` values of all processors + * are always 0. + * + * `os.cpus().length` should not be used to calculate the amount of parallelism + * available to an application. Use {@link availableParallelism} for this purpose. + * @since v0.3.3 + */ + function cpus(): CpuInfo[]; + /** + * Returns an estimate of the default amount of parallelism a program should use. + * Always returns a value greater than zero. + * + * This function is a small wrapper about libuv's [`uv_available_parallelism()`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_available_parallelism). + * @since v19.4.0, v18.14.0 + */ + function availableParallelism(): number; + /** + * Returns the operating system name as returned by [`uname(3)`](https://linux.die.net/man/3/uname). For example, it + * returns `'Linux'` on Linux, `'Darwin'` on macOS, and `'Windows_NT'` on Windows. + * + * See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for additional information + * about the output of running [`uname(3)`](https://linux.die.net/man/3/uname) on various operating systems. + * @since v0.3.3 + */ + function type(): string; + /** + * Returns the operating system as a string. + * + * On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `GetVersionExW()` is used. See + * [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v0.3.3 + */ + function release(): string; + /** + * Returns an object containing network interfaces that have been assigned a + * network address. + * + * Each key on the returned object identifies a network interface. The associated + * value is an array of objects that each describe an assigned network address. + * + * The properties available on the assigned network address object include: + * + * ```js + * { + * lo: [ + * { + * address: '127.0.0.1', + * netmask: '255.0.0.0', + * family: 'IPv4', + * mac: '00:00:00:00:00:00', + * internal: true, + * cidr: '127.0.0.1/8' + * }, + * { + * address: '::1', + * netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', + * family: 'IPv6', + * mac: '00:00:00:00:00:00', + * scopeid: 0, + * internal: true, + * cidr: '::1/128' + * } + * ], + * eth0: [ + * { + * address: '192.168.1.108', + * netmask: '255.255.255.0', + * family: 'IPv4', + * mac: '01:02:03:0a:0b:0c', + * internal: false, + * cidr: '192.168.1.108/24' + * }, + * { + * address: 'fe80::a00:27ff:fe4e:66a1', + * netmask: 'ffff:ffff:ffff:ffff::', + * family: 'IPv6', + * mac: '01:02:03:0a:0b:0c', + * scopeid: 1, + * internal: false, + * cidr: 'fe80::a00:27ff:fe4e:66a1/64' + * } + * ] + * } + * ``` + * @since v0.6.0 + */ + function networkInterfaces(): NodeJS.Dict; + /** + * Returns the string path of the current user's home directory. + * + * On POSIX, it uses the `$HOME` environment variable if defined. Otherwise it + * uses the [effective UID](https://en.wikipedia.org/wiki/User_identifier#Effective_user_ID) to look up the user's home directory. + * + * On Windows, it uses the `USERPROFILE` environment variable if defined. + * Otherwise it uses the path to the profile directory of the current user. + * @since v2.3.0 + */ + function homedir(): string; + interface UserInfoOptions { + encoding?: BufferEncoding | "buffer" | undefined; + } + interface UserInfoOptionsWithBufferEncoding extends UserInfoOptions { + encoding: "buffer"; + } + interface UserInfoOptionsWithStringEncoding extends UserInfoOptions { + encoding?: BufferEncoding | undefined; + } + /** + * Returns information about the currently effective user. On POSIX platforms, + * this is typically a subset of the password file. The returned object includes + * the `username`, `uid`, `gid`, `shell`, and `homedir`. On Windows, the `uid` and `gid` fields are `-1`, and `shell` is `null`. + * + * The value of `homedir` returned by `os.userInfo()` is provided by the operating + * system. This differs from the result of `os.homedir()`, which queries + * environment variables for the home directory before falling back to the + * operating system response. + * + * Throws a [`SystemError`](https://nodejs.org/docs/latest-v25.x/api/errors.html#class-systemerror) if a user has no `username` or `homedir`. + * @since v6.0.0 + */ + function userInfo(options?: UserInfoOptionsWithStringEncoding): UserInfo; + function userInfo(options: UserInfoOptionsWithBufferEncoding): UserInfo; + function userInfo(options: UserInfoOptions): UserInfo; + type SignalConstants = { + [key in NodeJS.Signals]: number; + }; + namespace constants { + const UV_UDP_REUSEADDR: number; + namespace signals {} + const signals: SignalConstants; + namespace errno { + const E2BIG: number; + const EACCES: number; + const EADDRINUSE: number; + const EADDRNOTAVAIL: number; + const EAFNOSUPPORT: number; + const EAGAIN: number; + const EALREADY: number; + const EBADF: number; + const EBADMSG: number; + const EBUSY: number; + const ECANCELED: number; + const ECHILD: number; + const ECONNABORTED: number; + const ECONNREFUSED: number; + const ECONNRESET: number; + const EDEADLK: number; + const EDESTADDRREQ: number; + const EDOM: number; + const EDQUOT: number; + const EEXIST: number; + const EFAULT: number; + const EFBIG: number; + const EHOSTUNREACH: number; + const EIDRM: number; + const EILSEQ: number; + const EINPROGRESS: number; + const EINTR: number; + const EINVAL: number; + const EIO: number; + const EISCONN: number; + const EISDIR: number; + const ELOOP: number; + const EMFILE: number; + const EMLINK: number; + const EMSGSIZE: number; + const EMULTIHOP: number; + const ENAMETOOLONG: number; + const ENETDOWN: number; + const ENETRESET: number; + const ENETUNREACH: number; + const ENFILE: number; + const ENOBUFS: number; + const ENODATA: number; + const ENODEV: number; + const ENOENT: number; + const ENOEXEC: number; + const ENOLCK: number; + const ENOLINK: number; + const ENOMEM: number; + const ENOMSG: number; + const ENOPROTOOPT: number; + const ENOSPC: number; + const ENOSR: number; + const ENOSTR: number; + const ENOSYS: number; + const ENOTCONN: number; + const ENOTDIR: number; + const ENOTEMPTY: number; + const ENOTSOCK: number; + const ENOTSUP: number; + const ENOTTY: number; + const ENXIO: number; + const EOPNOTSUPP: number; + const EOVERFLOW: number; + const EPERM: number; + const EPIPE: number; + const EPROTO: number; + const EPROTONOSUPPORT: number; + const EPROTOTYPE: number; + const ERANGE: number; + const EROFS: number; + const ESPIPE: number; + const ESRCH: number; + const ESTALE: number; + const ETIME: number; + const ETIMEDOUT: number; + const ETXTBSY: number; + const EWOULDBLOCK: number; + const EXDEV: number; + const WSAEINTR: number; + const WSAEBADF: number; + const WSAEACCES: number; + const WSAEFAULT: number; + const WSAEINVAL: number; + const WSAEMFILE: number; + const WSAEWOULDBLOCK: number; + const WSAEINPROGRESS: number; + const WSAEALREADY: number; + const WSAENOTSOCK: number; + const WSAEDESTADDRREQ: number; + const WSAEMSGSIZE: number; + const WSAEPROTOTYPE: number; + const WSAENOPROTOOPT: number; + const WSAEPROTONOSUPPORT: number; + const WSAESOCKTNOSUPPORT: number; + const WSAEOPNOTSUPP: number; + const WSAEPFNOSUPPORT: number; + const WSAEAFNOSUPPORT: number; + const WSAEADDRINUSE: number; + const WSAEADDRNOTAVAIL: number; + const WSAENETDOWN: number; + const WSAENETUNREACH: number; + const WSAENETRESET: number; + const WSAECONNABORTED: number; + const WSAECONNRESET: number; + const WSAENOBUFS: number; + const WSAEISCONN: number; + const WSAENOTCONN: number; + const WSAESHUTDOWN: number; + const WSAETOOMANYREFS: number; + const WSAETIMEDOUT: number; + const WSAECONNREFUSED: number; + const WSAELOOP: number; + const WSAENAMETOOLONG: number; + const WSAEHOSTDOWN: number; + const WSAEHOSTUNREACH: number; + const WSAENOTEMPTY: number; + const WSAEPROCLIM: number; + const WSAEUSERS: number; + const WSAEDQUOT: number; + const WSAESTALE: number; + const WSAEREMOTE: number; + const WSASYSNOTREADY: number; + const WSAVERNOTSUPPORTED: number; + const WSANOTINITIALISED: number; + const WSAEDISCON: number; + const WSAENOMORE: number; + const WSAECANCELLED: number; + const WSAEINVALIDPROCTABLE: number; + const WSAEINVALIDPROVIDER: number; + const WSAEPROVIDERFAILEDINIT: number; + const WSASYSCALLFAILURE: number; + const WSASERVICE_NOT_FOUND: number; + const WSATYPE_NOT_FOUND: number; + const WSA_E_NO_MORE: number; + const WSA_E_CANCELLED: number; + const WSAEREFUSED: number; + } + namespace dlopen { + const RTLD_LAZY: number; + const RTLD_NOW: number; + const RTLD_GLOBAL: number; + const RTLD_LOCAL: number; + const RTLD_DEEPBIND: number; + } + namespace priority { + const PRIORITY_LOW: number; + const PRIORITY_BELOW_NORMAL: number; + const PRIORITY_NORMAL: number; + const PRIORITY_ABOVE_NORMAL: number; + const PRIORITY_HIGH: number; + const PRIORITY_HIGHEST: number; + } + } + const devNull: string; + /** + * The operating system-specific end-of-line marker. + * * `\n` on POSIX + * * `\r\n` on Windows + */ + const EOL: string; + /** + * Returns the operating system CPU architecture for which the Node.js binary was + * compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`, + * `'mips'`, `'mipsel'`, `'ppc64'`, `'riscv64'`, `'s390x'`, and `'x64'`. + * + * The return value is equivalent to [process.arch](https://nodejs.org/docs/latest-v25.x/api/process.html#processarch). + * @since v0.5.0 + */ + function arch(): NodeJS.Architecture; + /** + * Returns a string identifying the kernel version. + * + * On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not + * available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v13.11.0, v12.17.0 + */ + function version(): string; + /** + * Returns a string identifying the operating system platform for which + * the Node.js binary was compiled. The value is set at compile time. + * Possible values are `'aix'`, `'darwin'`, `'freebsd'`, `'linux'`, `'openbsd'`, `'sunos'`, and `'win32'`. + * + * The return value is equivalent to `process.platform`. + * + * The value `'android'` may also be returned if Node.js is built on the Android + * operating system. [Android support is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). + * @since v0.5.0 + */ + function platform(): NodeJS.Platform; + /** + * Returns the machine type as a string, such as `arm`, `arm64`, `aarch64`, + * `mips`, `mips64`, `ppc64`, `ppc64le`, `s390x`, `i386`, `i686`, `x86_64`. + * + * On POSIX systems, the machine type is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not + * available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v18.9.0, v16.18.0 + */ + function machine(): string; + /** + * Returns the operating system's default directory for temporary files as a + * string. + * @since v0.9.9 + */ + function tmpdir(): string; + /** + * Returns a string identifying the endianness of the CPU for which the Node.js + * binary was compiled. + * + * Possible values are `'BE'` for big endian and `'LE'` for little endian. + * @since v0.9.4 + */ + function endianness(): "BE" | "LE"; + /** + * Returns the scheduling priority for the process specified by `pid`. If `pid` is + * not provided or is `0`, the priority of the current process is returned. + * @since v10.10.0 + * @param [pid=0] The process ID to retrieve scheduling priority for. + */ + function getPriority(pid?: number): number; + /** + * Attempts to set the scheduling priority for the process specified by `pid`. If `pid` is not provided or is `0`, the process ID of the current process is used. + * + * The `priority` input must be an integer between `-20` (high priority) and `19` (low priority). Due to differences between Unix priority levels and Windows + * priority classes, `priority` is mapped to one of six priority constants in `os.constants.priority`. When retrieving a process priority level, this range + * mapping may cause the return value to be slightly different on Windows. To avoid + * confusion, set `priority` to one of the priority constants. + * + * On Windows, setting priority to `PRIORITY_HIGHEST` requires elevated user + * privileges. Otherwise the set priority will be silently reduced to `PRIORITY_HIGH`. + * @since v10.10.0 + * @param [pid=0] The process ID to set scheduling priority for. + * @param priority The scheduling priority to assign to the process. + */ + function setPriority(priority: number): void; + function setPriority(pid: number, priority: number): void; +} +declare module "os" { + export * from "node:os"; +} diff --git a/backend/node_modules/@types/node/package.json b/backend/node_modules/@types/node/package.json new file mode 100644 index 0000000..58c1107 --- /dev/null +++ b/backend/node_modules/@types/node/package.json @@ -0,0 +1,155 @@ +{ + "name": "@types/node", + "version": "25.0.0", + "description": "TypeScript definitions for node", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node", + "license": "MIT", + "contributors": [ + { + "name": "Microsoft TypeScript", + "githubUsername": "Microsoft", + "url": "https://github.com/Microsoft" + }, + { + "name": "Alberto Schiabel", + "githubUsername": "jkomyno", + "url": "https://github.com/jkomyno" + }, + { + "name": "Andrew Makarov", + "githubUsername": "r3nya", + "url": "https://github.com/r3nya" + }, + { + "name": "Benjamin Toueg", + "githubUsername": "btoueg", + "url": "https://github.com/btoueg" + }, + { + "name": "David Junger", + "githubUsername": "touffy", + "url": "https://github.com/touffy" + }, + { + "name": "Mohsen Azimi", + "githubUsername": "mohsen1", + "url": "https://github.com/mohsen1" + }, + { + "name": "Nikita Galkin", + "githubUsername": "galkin", + "url": "https://github.com/galkin" + }, + { + "name": "Sebastian Silbermann", + "githubUsername": "eps1lon", + "url": "https://github.com/eps1lon" + }, + { + "name": "Wilco Bakker", + "githubUsername": "WilcoBakker", + "url": "https://github.com/WilcoBakker" + }, + { + "name": "Marcin Kopacz", + "githubUsername": "chyzwar", + "url": "https://github.com/chyzwar" + }, + { + "name": "Trivikram Kamat", + "githubUsername": "trivikr", + "url": "https://github.com/trivikr" + }, + { + "name": "Junxiao Shi", + "githubUsername": "yoursunny", + "url": "https://github.com/yoursunny" + }, + { + "name": "Ilia Baryshnikov", + "githubUsername": "qwelias", + "url": "https://github.com/qwelias" + }, + { + "name": "ExE Boss", + "githubUsername": "ExE-Boss", + "url": "https://github.com/ExE-Boss" + }, + { + "name": "Piotr Błażejewicz", + "githubUsername": "peterblazejewicz", + "url": "https://github.com/peterblazejewicz" + }, + { + "name": "Anna Henningsen", + "githubUsername": "addaleax", + "url": "https://github.com/addaleax" + }, + { + "name": "Victor Perin", + "githubUsername": "victorperin", + "url": "https://github.com/victorperin" + }, + { + "name": "NodeJS Contributors", + "githubUsername": "NodeJS", + "url": "https://github.com/NodeJS" + }, + { + "name": "Linus Unnebäck", + "githubUsername": "LinusU", + "url": "https://github.com/LinusU" + }, + { + "name": "wafuwafu13", + "githubUsername": "wafuwafu13", + "url": "https://github.com/wafuwafu13" + }, + { + "name": "Matteo Collina", + "githubUsername": "mcollina", + "url": "https://github.com/mcollina" + }, + { + "name": "Dmitry Semigradsky", + "githubUsername": "Semigradsky", + "url": "https://github.com/Semigradsky" + }, + { + "name": "René", + "githubUsername": "Renegade334", + "url": "https://github.com/Renegade334" + }, + { + "name": "Yagiz Nizipli", + "githubUsername": "anonrig", + "url": "https://github.com/anonrig" + } + ], + "main": "", + "types": "index.d.ts", + "typesVersions": { + "<=5.6": { + "*": [ + "ts5.6/*" + ] + }, + "<=5.7": { + "*": [ + "ts5.7/*" + ] + } + }, + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/node" + }, + "scripts": {}, + "dependencies": { + "undici-types": "~7.16.0" + }, + "peerDependencies": {}, + "typesPublisherContentHash": "358d9e288f53b02f484b0f2cc72378f0f2c3c1d563a28e74f187d8ce1492a4f1", + "typeScriptVersion": "5.2" +} \ No newline at end of file diff --git a/backend/node_modules/@types/node/path.d.ts b/backend/node_modules/@types/node/path.d.ts new file mode 100644 index 0000000..c0b22f6 --- /dev/null +++ b/backend/node_modules/@types/node/path.d.ts @@ -0,0 +1,187 @@ +/** + * The `node:path` module provides utilities for working with file and directory + * paths. It can be accessed using: + * + * ```js + * import path from 'node:path'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/path.js) + */ +declare module "node:path" { + namespace path { + /** + * A parsed path object generated by path.parse() or consumed by path.format(). + */ + interface ParsedPath { + /** + * The root of the path such as '/' or 'c:\' + */ + root: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base: string; + /** + * The file extension (if any) such as '.html' + */ + ext: string; + /** + * The file name without extension (if any) such as 'index' + */ + name: string; + } + interface FormatInputPathObject { + /** + * The root of the path such as '/' or 'c:\' + */ + root?: string | undefined; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir?: string | undefined; + /** + * The file name including extension (if any) such as 'index.html' + */ + base?: string | undefined; + /** + * The file extension (if any) such as '.html' + */ + ext?: string | undefined; + /** + * The file name without extension (if any) such as 'index' + */ + name?: string | undefined; + } + /** + * Normalize a string path, reducing '..' and '.' parts. + * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. If the path is a zero-length string, '.' is returned, representing the current working directory. + * + * @param path string path to normalize. + * @throws {TypeError} if `path` is not a string. + */ + function normalize(path: string): string; + /** + * Join all arguments together and normalize the resulting path. + * + * @param paths paths to join. + * @throws {TypeError} if any of the path segments is not a string. + */ + function join(...paths: string[]): string; + /** + * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. + * + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. + * + * If {to} isn't already absolute, {from} arguments are prepended in right to left order, + * until an absolute path is found. If after using all {from} paths still no absolute path is found, + * the current working directory is used as well. The resulting path is normalized, + * and trailing slashes are removed unless the path gets resolved to the root directory. + * + * @param paths A sequence of paths or path segments. + * @throws {TypeError} if any of the arguments is not a string. + */ + function resolve(...paths: string[]): string; + /** + * The `path.matchesGlob()` method determines if `path` matches the `pattern`. + * @param path The path to glob-match against. + * @param pattern The glob to check the path against. + * @returns Whether or not the `path` matched the `pattern`. + * @throws {TypeError} if `path` or `pattern` are not strings. + * @since v22.5.0 + */ + function matchesGlob(path: string, pattern: string): boolean; + /** + * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. + * + * If the given {path} is a zero-length string, `false` will be returned. + * + * @param path path to test. + * @throws {TypeError} if `path` is not a string. + */ + function isAbsolute(path: string): boolean; + /** + * Solve the relative path from {from} to {to} based on the current working directory. + * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. + * + * @throws {TypeError} if either `from` or `to` is not a string. + */ + function relative(from: string, to: string): string; + /** + * Return the directory name of a path. Similar to the Unix dirname command. + * + * @param path the path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + function dirname(path: string): string; + /** + * Return the last portion of a path. Similar to the Unix basename command. + * Often used to extract the file name from a fully qualified path. + * + * @param path the path to evaluate. + * @param suffix optionally, an extension to remove from the result. + * @throws {TypeError} if `path` is not a string or if `ext` is given and is not a string. + */ + function basename(path: string, suffix?: string): string; + /** + * Return the extension of the path, from the last '.' to end of string in the last portion of the path. + * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string. + * + * @param path the path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + function extname(path: string): string; + /** + * The platform-specific file separator. '\\' or '/'. + */ + const sep: "\\" | "/"; + /** + * The platform-specific file delimiter. ';' or ':'. + */ + const delimiter: ";" | ":"; + /** + * Returns an object from a path string - the opposite of format(). + * + * @param path path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + function parse(path: string): ParsedPath; + /** + * Returns a path string from an object - the opposite of parse(). + * + * @param pathObject path to evaluate. + */ + function format(pathObject: FormatInputPathObject): string; + /** + * On Windows systems only, returns an equivalent namespace-prefixed path for the given path. + * If path is not a string, path will be returned without modifications. + * This method is meaningful only on Windows system. + * On POSIX systems, the method is non-operational and always returns path without modifications. + */ + function toNamespacedPath(path: string): string; + } + namespace path { + export { + /** + * The `path.posix` property provides access to POSIX specific implementations of the `path` methods. + * + * The API is accessible via `require('node:path').posix` or `require('node:path/posix')`. + */ + path as posix, + /** + * The `path.win32` property provides access to Windows-specific implementations of the `path` methods. + * + * The API is accessible via `require('node:path').win32` or `require('node:path/win32')`. + */ + path as win32, + }; + } + export = path; +} +declare module "path" { + import path = require("node:path"); + export = path; +} diff --git a/backend/node_modules/@types/node/path/posix.d.ts b/backend/node_modules/@types/node/path/posix.d.ts new file mode 100644 index 0000000..d60f629 --- /dev/null +++ b/backend/node_modules/@types/node/path/posix.d.ts @@ -0,0 +1,8 @@ +declare module "node:path/posix" { + import path = require("node:path"); + export = path.posix; +} +declare module "path/posix" { + import path = require("path"); + export = path.posix; +} diff --git a/backend/node_modules/@types/node/path/win32.d.ts b/backend/node_modules/@types/node/path/win32.d.ts new file mode 100644 index 0000000..e6aa9fa --- /dev/null +++ b/backend/node_modules/@types/node/path/win32.d.ts @@ -0,0 +1,8 @@ +declare module "node:path/win32" { + import path = require("node:path"); + export = path.win32; +} +declare module "path/win32" { + import path = require("path"); + export = path.win32; +} diff --git a/backend/node_modules/@types/node/perf_hooks.d.ts b/backend/node_modules/@types/node/perf_hooks.d.ts new file mode 100644 index 0000000..699f3bf --- /dev/null +++ b/backend/node_modules/@types/node/perf_hooks.d.ts @@ -0,0 +1,621 @@ +/** + * This module provides an implementation of a subset of the W3C [Web Performance APIs](https://w3c.github.io/perf-timing-primer/) as well as additional APIs for + * Node.js-specific performance measurements. + * + * Node.js supports the following [Web Performance APIs](https://w3c.github.io/perf-timing-primer/): + * + * * [High Resolution Time](https://www.w3.org/TR/hr-time-2) + * * [Performance Timeline](https://w3c.github.io/performance-timeline/) + * * [User Timing](https://www.w3.org/TR/user-timing/) + * * [Resource Timing](https://www.w3.org/TR/resource-timing-2/) + * + * ```js + * import { PerformanceObserver, performance } from 'node:perf_hooks'; + * + * const obs = new PerformanceObserver((items) => { + * console.log(items.getEntries()[0].duration); + * performance.clearMarks(); + * }); + * obs.observe({ type: 'measure' }); + * performance.measure('Start to Now'); + * + * performance.mark('A'); + * doSomeLongRunningProcess(() => { + * performance.measure('A to Now', 'A'); + * + * performance.mark('B'); + * performance.measure('A to B', 'A', 'B'); + * }); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/perf_hooks.js) + */ +declare module "node:perf_hooks" { + import { InternalEventTargetEventProperties } from "node:events"; + // #region web types + type EntryType = + | "dns" // Node.js only + | "function" // Node.js only + | "gc" // Node.js only + | "http2" // Node.js only + | "http" // Node.js only + | "mark" // available on the Web + | "measure" // available on the Web + | "net" // Node.js only + | "node" // Node.js only + | "resource"; // available on the Web + interface EventLoopUtilization { + idle: number; + active: number; + utilization: number; + } + interface ConnectionTimingInfo { + domainLookupStartTime: number; + domainLookupEndTime: number; + connectionStartTime: number; + connectionEndTime: number; + secureConnectionStartTime: number; + ALPNNegotiatedProtocol: string; + } + interface FetchTimingInfo { + startTime: number; + redirectStartTime: number; + redirectEndTime: number; + postRedirectStartTime: number; + finalServiceWorkerStartTime: number; + finalNetworkRequestStartTime: number; + finalNetworkResponseStartTime: number; + endTime: number; + finalConnectionTimingInfo: ConnectionTimingInfo | null; + encodedBodySize: number; + decodedBodySize: number; + } + type PerformanceEntryList = PerformanceEntry[]; + interface PerformanceMarkOptions { + detail?: any; + startTime?: number; + } + interface PerformanceMeasureOptions { + detail?: any; + duration?: number; + end?: string | number; + start?: string | number; + } + interface PerformanceObserverCallback { + (entries: PerformanceObserverEntryList, observer: PerformanceObserver): void; + } + interface PerformanceObserverInit { + buffered?: boolean; + entryTypes?: EntryType[]; + type?: EntryType; + } + interface PerformanceEventMap { + "resourcetimingbufferfull": Event; + } + interface Performance extends EventTarget, InternalEventTargetEventProperties { + readonly nodeTiming: PerformanceNodeTiming; + readonly timeOrigin: number; + clearMarks(markName?: string): void; + clearMeasures(measureName?: string): void; + clearResourceTimings(resourceTimingName?: string): void; + getEntries(): PerformanceEntryList; + getEntriesByName(name: string, type?: EntryType): PerformanceEntryList; + getEntriesByType(type: EntryType): PerformanceEntryList; + mark(markName: string, markOptions?: PerformanceMarkOptions): PerformanceMark; + markResourceTiming( + timingInfo: FetchTimingInfo, + requestedUrl: string, + initiatorType: string, + global: unknown, + cacheMode: string, + bodyInfo: unknown, + responseStatus: number, + deliveryType?: string, + ): PerformanceResourceTiming; + measure(measureName: string, startMark?: string, endMark?: string): PerformanceMeasure; + measure(measureName: string, options: PerformanceMeasureOptions, endMark?: string): PerformanceMeasure; + now(): number; + setResourceTimingBufferSize(maxSize: number): void; + toJSON(): any; + addEventListener( + type: K, + listener: (ev: PerformanceEventMap[K]) => void, + options?: AddEventListenerOptions | boolean, + ): void; + addEventListener( + type: string, + listener: EventListener | EventListenerObject, + options?: AddEventListenerOptions | boolean, + ): void; + removeEventListener( + type: K, + listener: (ev: PerformanceEventMap[K]) => void, + options?: EventListenerOptions | boolean, + ): void; + removeEventListener( + type: string, + listener: EventListener | EventListenerObject, + options?: EventListenerOptions | boolean, + ): void; + /** + * The `eventLoopUtilization()` method returns an object that contains the + * cumulative duration of time the event loop has been both idle and active as a + * high resolution milliseconds timer. The `utilization` value is the calculated + * Event Loop Utilization (ELU). + * + * If bootstrapping has not yet finished on the main thread the properties have + * the value of `0`. The ELU is immediately available on [Worker threads](https://nodejs.org/docs/latest-v25.x/api/worker_threads.html#worker-threads) since + * bootstrap happens within the event loop. + * + * Both `utilization1` and `utilization2` are optional parameters. + * + * If `utilization1` is passed, then the delta between the current call's `active` + * and `idle` times, as well as the corresponding `utilization` value are + * calculated and returned (similar to `process.hrtime()`). + * + * If `utilization1` and `utilization2` are both passed, then the delta is + * calculated between the two arguments. This is a convenience option because, + * unlike `process.hrtime()`, calculating the ELU is more complex than a + * single subtraction. + * + * ELU is similar to CPU utilization, except that it only measures event loop + * statistics and not CPU usage. It represents the percentage of time the event + * loop has spent outside the event loop's event provider (e.g. `epoll_wait`). + * No other CPU idle time is taken into consideration. The following is an example + * of how a mostly idle process will have a high ELU. + * + * ```js + * import { eventLoopUtilization } from 'node:perf_hooks'; + * import { spawnSync } from 'node:child_process'; + * + * setImmediate(() => { + * const elu = eventLoopUtilization(); + * spawnSync('sleep', ['5']); + * console.log(eventLoopUtilization(elu).utilization); + * }); + * ``` + * + * Although the CPU is mostly idle while running this script, the value of + * `utilization` is `1`. This is because the call to + * `child_process.spawnSync()` blocks the event loop from proceeding. + * + * Passing in a user-defined object instead of the result of a previous call to + * `eventLoopUtilization()` will lead to undefined behavior. The return values + * are not guaranteed to reflect any correct state of the event loop. + * @since v14.10.0, v12.19.0 + * @param utilization1 The result of a previous call to + * `eventLoopUtilization()`. + * @param utilization2 The result of a previous call to + * `eventLoopUtilization()` prior to `utilization1`. + */ + eventLoopUtilization( + utilization1?: EventLoopUtilization, + utilization2?: EventLoopUtilization, + ): EventLoopUtilization; + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Wraps a function within a new function that measures the running time of the + * wrapped function. A `PerformanceObserver` must be subscribed to the `'function'` + * event type in order for the timing details to be accessed. + * + * ```js + * import { performance, PerformanceObserver } from 'node:perf_hooks'; + * + * function someFunction() { + * console.log('hello world'); + * } + * + * const wrapped = performance.timerify(someFunction); + * + * const obs = new PerformanceObserver((list) => { + * console.log(list.getEntries()[0].duration); + * + * performance.clearMarks(); + * performance.clearMeasures(); + * obs.disconnect(); + * }); + * obs.observe({ entryTypes: ['function'] }); + * + * // A performance timeline entry will be created + * wrapped(); + * ``` + * + * If the wrapped function returns a promise, a finally handler will be attached + * to the promise and the duration will be reported once the finally handler is + * invoked. + * @since v8.5.0 + */ + timerify any>(fn: T, options?: PerformanceTimerifyOptions): T; + } + var Performance: { + prototype: Performance; + new(): Performance; + }; + interface PerformanceEntry { + readonly duration: number; + readonly entryType: EntryType; + readonly name: string; + readonly startTime: number; + toJSON(): any; + } + var PerformanceEntry: { + prototype: PerformanceEntry; + new(): PerformanceEntry; + }; + interface PerformanceMark extends PerformanceEntry { + readonly detail: any; + readonly entryType: "mark"; + } + var PerformanceMark: { + prototype: PerformanceMark; + new(markName: string, markOptions?: PerformanceMarkOptions): PerformanceMark; + }; + interface PerformanceMeasure extends PerformanceEntry { + readonly detail: any; + readonly entryType: "measure"; + } + var PerformanceMeasure: { + prototype: PerformanceMeasure; + new(): PerformanceMeasure; + }; + interface PerformanceObserver { + disconnect(): void; + observe(options: PerformanceObserverInit): void; + takeRecords(): PerformanceEntryList; + } + var PerformanceObserver: { + prototype: PerformanceObserver; + new(callback: PerformanceObserverCallback): PerformanceObserver; + readonly supportedEntryTypes: readonly EntryType[]; + }; + interface PerformanceObserverEntryList { + getEntries(): PerformanceEntryList; + getEntriesByName(name: string, type?: EntryType): PerformanceEntryList; + getEntriesByType(type: EntryType): PerformanceEntryList; + } + var PerformanceObserverEntryList: { + prototype: PerformanceObserverEntryList; + new(): PerformanceObserverEntryList; + }; + interface PerformanceResourceTiming extends PerformanceEntry { + readonly connectEnd: number; + readonly connectStart: number; + readonly decodedBodySize: number; + readonly domainLookupEnd: number; + readonly domainLookupStart: number; + readonly encodedBodySize: number; + readonly entryType: "resource"; + readonly fetchStart: number; + readonly initiatorType: string; + readonly nextHopProtocol: string; + readonly redirectEnd: number; + readonly redirectStart: number; + readonly requestStart: number; + readonly responseEnd: number; + readonly responseStart: number; + readonly responseStatus: number; + readonly secureConnectionStart: number; + readonly transferSize: number; + readonly workerStart: number; + toJSON(): any; + } + var PerformanceResourceTiming: { + prototype: PerformanceResourceTiming; + new(): PerformanceResourceTiming; + }; + var performance: Performance; + // #endregion + interface PerformanceTimerifyOptions { + /** + * A histogram object created using + * `perf_hooks.createHistogram()` that will record runtime durations in + * nanoseconds. + */ + histogram?: RecordableHistogram | undefined; + } + /** + * _This class is an extension by Node.js. It is not available in Web browsers._ + * + * Provides detailed Node.js timing data. + * + * The constructor of this class is not exposed to users directly. + * @since v19.0.0 + */ + class PerformanceNodeEntry extends PerformanceEntry { + /** + * Additional detail specific to the `entryType`. + * @since v16.0.0 + */ + readonly detail: any; + readonly entryType: "dns" | "function" | "gc" | "http2" | "http" | "net" | "node"; + } + interface UVMetrics { + /** + * Number of event loop iterations. + */ + readonly loopCount: number; + /** + * Number of events that have been processed by the event handler. + */ + readonly events: number; + /** + * Number of events that were waiting to be processed when the event provider was called. + */ + readonly eventsWaiting: number; + } + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Provides timing details for Node.js itself. The constructor of this class + * is not exposed to users. + * @since v8.5.0 + */ + interface PerformanceNodeTiming extends PerformanceEntry { + /** + * The high resolution millisecond timestamp at which the Node.js process + * completed bootstrapping. If bootstrapping has not yet finished, the property + * has the value of -1. + * @since v8.5.0 + */ + readonly bootstrapComplete: number; + readonly entryType: "node"; + /** + * The high resolution millisecond timestamp at which the Node.js environment was + * initialized. + * @since v8.5.0 + */ + readonly environment: number; + /** + * The high resolution millisecond timestamp of the amount of time the event loop + * has been idle within the event loop's event provider (e.g. `epoll_wait`). This + * does not take CPU usage into consideration. If the event loop has not yet + * started (e.g., in the first tick of the main script), the property has the + * value of 0. + * @since v14.10.0, v12.19.0 + */ + readonly idleTime: number; + /** + * The high resolution millisecond timestamp at which the Node.js event loop + * exited. If the event loop has not yet exited, the property has the value of -1\. + * It can only have a value of not -1 in a handler of the `'exit'` event. + * @since v8.5.0 + */ + readonly loopExit: number; + /** + * The high resolution millisecond timestamp at which the Node.js event loop + * started. If the event loop has not yet started (e.g., in the first tick of the + * main script), the property has the value of -1. + * @since v8.5.0 + */ + readonly loopStart: number; + /** + * The high resolution millisecond timestamp at which the Node.js process was initialized. + * @since v8.5.0 + */ + readonly nodeStart: number; + /** + * This is a wrapper to the `uv_metrics_info` function. + * It returns the current set of event loop metrics. + * + * It is recommended to use this property inside a function whose execution was + * scheduled using `setImmediate` to avoid collecting metrics before finishing all + * operations scheduled during the current loop iteration. + * @since v22.8.0, v20.18.0 + */ + readonly uvMetricsInfo: UVMetrics; + /** + * The high resolution millisecond timestamp at which the V8 platform was + * initialized. + * @since v8.5.0 + */ + readonly v8Start: number; + } + namespace constants { + const NODE_PERFORMANCE_GC_MAJOR: number; + const NODE_PERFORMANCE_GC_MINOR: number; + const NODE_PERFORMANCE_GC_INCREMENTAL: number; + const NODE_PERFORMANCE_GC_WEAKCB: number; + const NODE_PERFORMANCE_GC_FLAGS_NO: number; + const NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED: number; + const NODE_PERFORMANCE_GC_FLAGS_FORCED: number; + const NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY: number; + const NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE: number; + } + interface EventLoopMonitorOptions { + /** + * The sampling rate in milliseconds. + * Must be greater than zero. + * @default 10 + */ + resolution?: number | undefined; + } + interface Histogram { + /** + * The number of samples recorded by the histogram. + * @since v17.4.0, v16.14.0 + */ + readonly count: number; + /** + * The number of samples recorded by the histogram. + * v17.4.0, v16.14.0 + */ + readonly countBigInt: bigint; + /** + * The number of times the event loop delay exceeded the maximum 1 hour event + * loop delay threshold. + * @since v11.10.0 + */ + readonly exceeds: number; + /** + * The number of times the event loop delay exceeded the maximum 1 hour event loop delay threshold. + * @since v17.4.0, v16.14.0 + */ + readonly exceedsBigInt: bigint; + /** + * The maximum recorded event loop delay. + * @since v11.10.0 + */ + readonly max: number; + /** + * The maximum recorded event loop delay. + * v17.4.0, v16.14.0 + */ + readonly maxBigInt: number; + /** + * The mean of the recorded event loop delays. + * @since v11.10.0 + */ + readonly mean: number; + /** + * The minimum recorded event loop delay. + * @since v11.10.0 + */ + readonly min: number; + /** + * The minimum recorded event loop delay. + * v17.4.0, v16.14.0 + */ + readonly minBigInt: bigint; + /** + * Returns the value at the given percentile. + * @since v11.10.0 + * @param percentile A percentile value in the range (0, 100]. + */ + percentile(percentile: number): number; + /** + * Returns the value at the given percentile. + * @since v17.4.0, v16.14.0 + * @param percentile A percentile value in the range (0, 100]. + */ + percentileBigInt(percentile: number): bigint; + /** + * Returns a `Map` object detailing the accumulated percentile distribution. + * @since v11.10.0 + */ + readonly percentiles: Map; + /** + * Returns a `Map` object detailing the accumulated percentile distribution. + * @since v17.4.0, v16.14.0 + */ + readonly percentilesBigInt: Map; + /** + * Resets the collected histogram data. + * @since v11.10.0 + */ + reset(): void; + /** + * The standard deviation of the recorded event loop delays. + * @since v11.10.0 + */ + readonly stddev: number; + } + interface IntervalHistogram extends Histogram { + /** + * Enables the update interval timer. Returns `true` if the timer was + * started, `false` if it was already started. + * @since v11.10.0 + */ + enable(): boolean; + /** + * Disables the update interval timer. Returns `true` if the timer was + * stopped, `false` if it was already stopped. + * @since v11.10.0 + */ + disable(): boolean; + /** + * Disables the update interval timer when the histogram is disposed. + * + * ```js + * const { monitorEventLoopDelay } = require('node:perf_hooks'); + * { + * using hist = monitorEventLoopDelay({ resolution: 20 }); + * hist.enable(); + * // The histogram will be disabled when the block is exited. + * } + * ``` + * @since v24.2.0 + */ + [Symbol.dispose](): void; + } + interface RecordableHistogram extends Histogram { + /** + * @since v15.9.0, v14.18.0 + * @param val The amount to record in the histogram. + */ + record(val: number | bigint): void; + /** + * Calculates the amount of time (in nanoseconds) that has passed since the + * previous call to `recordDelta()` and records that amount in the histogram. + * @since v15.9.0, v14.18.0 + */ + recordDelta(): void; + /** + * Adds the values from `other` to this histogram. + * @since v17.4.0, v16.14.0 + */ + add(other: RecordableHistogram): void; + } + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Creates an `IntervalHistogram` object that samples and reports the event loop + * delay over time. The delays will be reported in nanoseconds. + * + * Using a timer to detect approximate event loop delay works because the + * execution of timers is tied specifically to the lifecycle of the libuv + * event loop. That is, a delay in the loop will cause a delay in the execution + * of the timer, and those delays are specifically what this API is intended to + * detect. + * + * ```js + * import { monitorEventLoopDelay } from 'node:perf_hooks'; + * const h = monitorEventLoopDelay({ resolution: 20 }); + * h.enable(); + * // Do something. + * h.disable(); + * console.log(h.min); + * console.log(h.max); + * console.log(h.mean); + * console.log(h.stddev); + * console.log(h.percentiles); + * console.log(h.percentile(50)); + * console.log(h.percentile(99)); + * ``` + * @since v11.10.0 + */ + function monitorEventLoopDelay(options?: EventLoopMonitorOptions): IntervalHistogram; + interface CreateHistogramOptions { + /** + * The minimum recordable value. Must be an integer value greater than 0. + * @default 1 + */ + lowest?: number | bigint | undefined; + /** + * The maximum recordable value. Must be an integer value greater than min. + * @default Number.MAX_SAFE_INTEGER + */ + highest?: number | bigint | undefined; + /** + * The number of accuracy digits. Must be a number between 1 and 5. + * @default 3 + */ + figures?: number | undefined; + } + /** + * Returns a `RecordableHistogram`. + * @since v15.9.0, v14.18.0 + */ + function createHistogram(options?: CreateHistogramOptions): RecordableHistogram; + // TODO: remove these in a future major + /** @deprecated Use the canonical `PerformanceMarkOptions` instead. */ + interface MarkOptions extends PerformanceMarkOptions {} + /** @deprecated Use the canonical `PerformanceMeasureOptions` instead. */ + interface MeasureOptions extends PerformanceMeasureOptions {} + /** @deprecated Use `PerformanceTimerifyOptions` instead. */ + interface TimerifyOptions extends PerformanceTimerifyOptions {} +} +declare module "perf_hooks" { + export * from "node:perf_hooks"; +} diff --git a/backend/node_modules/@types/node/process.d.ts b/backend/node_modules/@types/node/process.d.ts new file mode 100644 index 0000000..67a2705 --- /dev/null +++ b/backend/node_modules/@types/node/process.d.ts @@ -0,0 +1,2092 @@ +declare module "node:process" { + import { Control, MessageOptions, SendHandle } from "node:child_process"; + import { InternalEventEmitter } from "node:events"; + import { PathLike } from "node:fs"; + import * as tty from "node:tty"; + import { Worker } from "node:worker_threads"; + interface BuiltInModule { + "assert": typeof import("assert"); + "node:assert": typeof import("node:assert"); + "assert/strict": typeof import("assert/strict"); + "node:assert/strict": typeof import("node:assert/strict"); + "async_hooks": typeof import("async_hooks"); + "node:async_hooks": typeof import("node:async_hooks"); + "buffer": typeof import("buffer"); + "node:buffer": typeof import("node:buffer"); + "child_process": typeof import("child_process"); + "node:child_process": typeof import("node:child_process"); + "cluster": typeof import("cluster"); + "node:cluster": typeof import("node:cluster"); + "console": typeof import("console"); + "node:console": typeof import("node:console"); + "constants": typeof import("constants"); + "node:constants": typeof import("node:constants"); + "crypto": typeof import("crypto"); + "node:crypto": typeof import("node:crypto"); + "dgram": typeof import("dgram"); + "node:dgram": typeof import("node:dgram"); + "diagnostics_channel": typeof import("diagnostics_channel"); + "node:diagnostics_channel": typeof import("node:diagnostics_channel"); + "dns": typeof import("dns"); + "node:dns": typeof import("node:dns"); + "dns/promises": typeof import("dns/promises"); + "node:dns/promises": typeof import("node:dns/promises"); + "domain": typeof import("domain"); + "node:domain": typeof import("node:domain"); + "events": typeof import("events"); + "node:events": typeof import("node:events"); + "fs": typeof import("fs"); + "node:fs": typeof import("node:fs"); + "fs/promises": typeof import("fs/promises"); + "node:fs/promises": typeof import("node:fs/promises"); + "http": typeof import("http"); + "node:http": typeof import("node:http"); + "http2": typeof import("http2"); + "node:http2": typeof import("node:http2"); + "https": typeof import("https"); + "node:https": typeof import("node:https"); + "inspector": typeof import("inspector"); + "node:inspector": typeof import("node:inspector"); + "inspector/promises": typeof import("inspector/promises"); + "node:inspector/promises": typeof import("node:inspector/promises"); + "module": typeof import("module"); + "node:module": typeof import("node:module"); + "net": typeof import("net"); + "node:net": typeof import("node:net"); + "os": typeof import("os"); + "node:os": typeof import("node:os"); + "path": typeof import("path"); + "node:path": typeof import("node:path"); + "path/posix": typeof import("path/posix"); + "node:path/posix": typeof import("node:path/posix"); + "path/win32": typeof import("path/win32"); + "node:path/win32": typeof import("node:path/win32"); + "perf_hooks": typeof import("perf_hooks"); + "node:perf_hooks": typeof import("node:perf_hooks"); + "process": typeof import("process"); + "node:process": typeof import("node:process"); + "punycode": typeof import("punycode"); + "node:punycode": typeof import("node:punycode"); + "querystring": typeof import("querystring"); + "node:querystring": typeof import("node:querystring"); + "node:quic": typeof import("node:quic"); + "readline": typeof import("readline"); + "node:readline": typeof import("node:readline"); + "readline/promises": typeof import("readline/promises"); + "node:readline/promises": typeof import("node:readline/promises"); + "repl": typeof import("repl"); + "node:repl": typeof import("node:repl"); + "node:sea": typeof import("node:sea"); + "node:sqlite": typeof import("node:sqlite"); + "stream": typeof import("stream"); + "node:stream": typeof import("node:stream"); + "stream/consumers": typeof import("stream/consumers"); + "node:stream/consumers": typeof import("node:stream/consumers"); + "stream/promises": typeof import("stream/promises"); + "node:stream/promises": typeof import("node:stream/promises"); + "stream/web": typeof import("stream/web"); + "node:stream/web": typeof import("node:stream/web"); + "string_decoder": typeof import("string_decoder"); + "node:string_decoder": typeof import("node:string_decoder"); + "node:test": typeof import("node:test"); + "node:test/reporters": typeof import("node:test/reporters"); + "timers": typeof import("timers"); + "node:timers": typeof import("node:timers"); + "timers/promises": typeof import("timers/promises"); + "node:timers/promises": typeof import("node:timers/promises"); + "tls": typeof import("tls"); + "node:tls": typeof import("node:tls"); + "trace_events": typeof import("trace_events"); + "node:trace_events": typeof import("node:trace_events"); + "tty": typeof import("tty"); + "node:tty": typeof import("node:tty"); + "url": typeof import("url"); + "node:url": typeof import("node:url"); + "util": typeof import("util"); + "node:util": typeof import("node:util"); + "util/types": typeof import("util/types"); + "node:util/types": typeof import("node:util/types"); + "v8": typeof import("v8"); + "node:v8": typeof import("node:v8"); + "vm": typeof import("vm"); + "node:vm": typeof import("node:vm"); + "wasi": typeof import("wasi"); + "node:wasi": typeof import("node:wasi"); + "worker_threads": typeof import("worker_threads"); + "node:worker_threads": typeof import("node:worker_threads"); + "zlib": typeof import("zlib"); + "node:zlib": typeof import("node:zlib"); + } + type SignalsEventMap = { [S in NodeJS.Signals]: [signal: S] }; + interface ProcessEventMap extends SignalsEventMap { + "beforeExit": [code: number]; + "disconnect": []; + "exit": [code: number]; + "message": [ + message: object | boolean | number | string | null, + sendHandle: SendHandle | undefined, + ]; + "rejectionHandled": [promise: Promise]; + "uncaughtException": [error: Error, origin: NodeJS.UncaughtExceptionOrigin]; + "uncaughtExceptionMonitor": [error: Error, origin: NodeJS.UncaughtExceptionOrigin]; + "unhandledRejection": [reason: unknown, promise: Promise]; + "warning": [warning: Error]; + "worker": [worker: Worker]; + "workerMessage": [value: any, source: number]; + } + global { + var process: NodeJS.Process; + namespace process { + export { ProcessEventMap }; + } + namespace NodeJS { + // this namespace merge is here because these are specifically used + // as the type for process.stdin, process.stdout, and process.stderr. + // they can't live in tty.d.ts because we need to disambiguate the imported name. + interface ReadStream extends tty.ReadStream {} + interface WriteStream extends tty.WriteStream {} + interface MemoryUsageFn { + /** + * The `process.memoryUsage()` method iterate over each page to gather informations about memory + * usage which can be slow depending on the program memory allocations. + */ + (): MemoryUsage; + /** + * method returns an integer representing the Resident Set Size (RSS) in bytes. + */ + rss(): number; + } + interface MemoryUsage { + /** + * Resident Set Size, is the amount of space occupied in the main memory device (that is a subset of the total allocated memory) for the + * process, including all C++ and JavaScript objects and code. + */ + rss: number; + /** + * Refers to V8's memory usage. + */ + heapTotal: number; + /** + * Refers to V8's memory usage. + */ + heapUsed: number; + external: number; + /** + * Refers to memory allocated for `ArrayBuffer`s and `SharedArrayBuffer`s, including all Node.js Buffers. This is also included + * in the external value. When Node.js is used as an embedded library, this value may be `0` because allocations for `ArrayBuffer`s + * may not be tracked in that case. + */ + arrayBuffers: number; + } + interface CpuUsage { + user: number; + system: number; + } + interface ProcessRelease { + name: string; + sourceUrl?: string | undefined; + headersUrl?: string | undefined; + libUrl?: string | undefined; + lts?: string | undefined; + } + interface ProcessFeatures { + /** + * A boolean value that is `true` if the current Node.js build is caching builtin modules. + * @since v12.0.0 + */ + readonly cached_builtins: boolean; + /** + * A boolean value that is `true` if the current Node.js build is a debug build. + * @since v0.5.5 + */ + readonly debug: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes the inspector. + * @since v11.10.0 + */ + readonly inspector: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for IPv6. + * + * Since all Node.js builds have IPv6 support, this value is always `true`. + * @since v0.5.3 + * @deprecated This property is always true, and any checks based on it are redundant. + */ + readonly ipv6: boolean; + /** + * A boolean value that is `true` if the current Node.js build supports + * [loading ECMAScript modules using `require()`](https://nodejs.org/docs/latest-v25.x/api/modules.md#loading-ecmascript-modules-using-require). + * @since v22.10.0 + */ + readonly require_module: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for TLS. + * @since v0.5.3 + */ + readonly tls: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for ALPN in TLS. + * + * In Node.js 11.0.0 and later versions, the OpenSSL dependencies feature unconditional ALPN support. + * This value is therefore identical to that of `process.features.tls`. + * @since v4.8.0 + * @deprecated Use `process.features.tls` instead. + */ + readonly tls_alpn: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for OCSP in TLS. + * + * In Node.js 11.0.0 and later versions, the OpenSSL dependencies feature unconditional OCSP support. + * This value is therefore identical to that of `process.features.tls`. + * @since v0.11.13 + * @deprecated Use `process.features.tls` instead. + */ + readonly tls_ocsp: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for SNI in TLS. + * + * In Node.js 11.0.0 and later versions, the OpenSSL dependencies feature unconditional SNI support. + * This value is therefore identical to that of `process.features.tls`. + * @since v0.5.3 + * @deprecated Use `process.features.tls` instead. + */ + readonly tls_sni: boolean; + /** + * A value that is `"strip"` by default, + * `"transform"` if Node.js is run with `--experimental-transform-types`, and `false` if + * Node.js is run with `--no-experimental-strip-types`. + * @since v22.10.0 + */ + readonly typescript: "strip" | "transform" | false; + /** + * A boolean value that is `true` if the current Node.js build includes support for libuv. + * + * Since it's not possible to build Node.js without libuv, this value is always `true`. + * @since v0.5.3 + * @deprecated This property is always true, and any checks based on it are redundant. + */ + readonly uv: boolean; + } + interface ProcessVersions extends Dict { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + modules: string; + openssl: string; + } + type Platform = + | "aix" + | "android" + | "darwin" + | "freebsd" + | "haiku" + | "linux" + | "openbsd" + | "sunos" + | "win32" + | "cygwin" + | "netbsd"; + type Architecture = + | "arm" + | "arm64" + | "ia32" + | "loong64" + | "mips" + | "mipsel" + | "ppc64" + | "riscv64" + | "s390x" + | "x64"; + type Signals = + | "SIGABRT" + | "SIGALRM" + | "SIGBUS" + | "SIGCHLD" + | "SIGCONT" + | "SIGFPE" + | "SIGHUP" + | "SIGILL" + | "SIGINT" + | "SIGIO" + | "SIGIOT" + | "SIGKILL" + | "SIGPIPE" + | "SIGPOLL" + | "SIGPROF" + | "SIGPWR" + | "SIGQUIT" + | "SIGSEGV" + | "SIGSTKFLT" + | "SIGSTOP" + | "SIGSYS" + | "SIGTERM" + | "SIGTRAP" + | "SIGTSTP" + | "SIGTTIN" + | "SIGTTOU" + | "SIGUNUSED" + | "SIGURG" + | "SIGUSR1" + | "SIGUSR2" + | "SIGVTALRM" + | "SIGWINCH" + | "SIGXCPU" + | "SIGXFSZ" + | "SIGBREAK" + | "SIGLOST" + | "SIGINFO"; + type UncaughtExceptionOrigin = "uncaughtException" | "unhandledRejection"; + /** + * @deprecated Global listener types will be removed in a future version. + * Callbacks passed directly to `process`'s EventEmitter methods + * have their parameter types inferred automatically. + * + * `process` event types are also available via `ProcessEventMap`: + * + * ```ts + * import type { ProcessEventMap } from 'node:process'; + * const listener = (...args: ProcessEventMap['beforeExit']) => { ... }; + * ``` + */ + type BeforeExitListener = (...args: ProcessEventMap["beforeExit"]) => void; + /** + * @deprecated Global listener types will be removed in a future version. + * Callbacks passed directly to `process`'s EventEmitter methods + * have their parameter types inferred automatically. + * + * `process` event types are also available via `ProcessEventMap`: + * + * ```ts + * import type { ProcessEventMap } from 'node:process'; + * const listener = (...args: ProcessEventMap['disconnect']) => { ... }; + * ``` + */ + type DisconnectListener = (...args: ProcessEventMap["disconnect"]) => void; + /** + * @deprecated Global listener types will be removed in a future version. + * Callbacks passed directly to `process`'s EventEmitter methods + * have their parameter types inferred automatically. + * + * `process` event types are also available via `ProcessEventMap`: + * + * ```ts + * import type { ProcessEventMap } from 'node:process'; + * const listener = (...args: ProcessEventMap['exit']) => { ... }; + * ``` + */ + type ExitListener = (...args: ProcessEventMap["exit"]) => void; + /** + * @deprecated Global listener types will be removed in a future version. + * Callbacks passed directly to `process`'s EventEmitter methods + * have their parameter types inferred automatically. + * + * `process` event types are also available via `ProcessEventMap`: + * + * ```ts + * import type { ProcessEventMap } from 'node:process'; + * const listener = (...args: ProcessEventMap['message']) => { ... }; + * ``` + */ + type MessageListener = (...args: ProcessEventMap["message"]) => void; + /** + * @deprecated Global listener types will be removed in a future version. + * Callbacks passed directly to `process`'s EventEmitter methods + * have their parameter types inferred automatically. + * + * `process` event types are also available via `ProcessEventMap`: + * + * ```ts + * import type { ProcessEventMap } from 'node:process'; + * const listener = (...args: ProcessEventMap['rejectionHandled']) => { ... }; + * ``` + */ + type RejectionHandledListener = (...args: ProcessEventMap["rejectionHandled"]) => void; + /** + * @deprecated Global listener types will be removed in a future version. + * Callbacks passed directly to `process`'s EventEmitter methods + * have their parameter types inferred automatically. + */ + type SignalsListener = (signal: Signals) => void; + /** + * @deprecated Global listener types will be removed in a future version. + * Callbacks passed directly to `process`'s EventEmitter methods + * have their parameter types inferred automatically. + * + * `process` event types are also available via `ProcessEventMap`: + * + * ```ts + * import type { ProcessEventMap } from 'node:process'; + * const listener = (...args: ProcessEventMap['uncaughtException']) => { ... }; + * ``` + */ + type UncaughtExceptionListener = (...args: ProcessEventMap["uncaughtException"]) => void; + /** + * @deprecated Global listener types will be removed in a future version. + * Callbacks passed directly to `process`'s EventEmitter methods + * have their parameter types inferred automatically. + * + * `process` event types are also available via `ProcessEventMap`: + * + * ```ts + * import type { ProcessEventMap } from 'node:process'; + * const listener = (...args: ProcessEventMap['unhandledRejection']) => { ... }; + * ``` + */ + type UnhandledRejectionListener = (...args: ProcessEventMap["unhandledRejection"]) => void; + /** + * @deprecated Global listener types will be removed in a future version. + * Callbacks passed directly to `process`'s EventEmitter methods + * have their parameter types inferred automatically. + * + * `process` event types are also available via `ProcessEventMap`: + * + * ```ts + * import type { ProcessEventMap } from 'node:process'; + * const listener = (...args: ProcessEventMap['warning']) => { ... }; + * ``` + */ + type WarningListener = (...args: ProcessEventMap["warning"]) => void; + /** + * @deprecated Global listener types will be removed in a future version. + * Callbacks passed directly to `process`'s EventEmitter methods + * have their parameter types inferred automatically. + * + * `process` event types are also available via `ProcessEventMap`: + * + * ```ts + * import type { ProcessEventMap } from 'node:process'; + * const listener = (...args: ProcessEventMap['worker']) => { ... }; + * ``` + */ + type WorkerListener = (...args: ProcessEventMap["worker"]) => void; + interface Socket extends ReadWriteStream { + isTTY?: true | undefined; + } + // Alias for compatibility + interface ProcessEnv extends Dict { + /** + * Can be used to change the default timezone at runtime + */ + TZ?: string | undefined; + } + interface HRTime { + /** + * This is the legacy version of {@link process.hrtime.bigint()} + * before bigint was introduced in JavaScript. + * + * The `process.hrtime()` method returns the current high-resolution real time in a `[seconds, nanoseconds]` tuple `Array`, + * where `nanoseconds` is the remaining part of the real time that can't be represented in second precision. + * + * `time` is an optional parameter that must be the result of a previous `process.hrtime()` call to diff with the current time. + * If the parameter passed in is not a tuple `Array`, a TypeError will be thrown. + * Passing in a user-defined array instead of the result of a previous call to `process.hrtime()` will lead to undefined behavior. + * + * These times are relative to an arbitrary time in the past, + * and not related to the time of day and therefore not subject to clock drift. + * The primary use is for measuring performance between intervals: + * ```js + * const { hrtime } = require('node:process'); + * const NS_PER_SEC = 1e9; + * const time = hrtime(); + * // [ 1800216, 25 ] + * + * setTimeout(() => { + * const diff = hrtime(time); + * // [ 1, 552 ] + * + * console.log(`Benchmark took ${diff[0] * NS_PER_SEC + diff[1]} nanoseconds`); + * // Benchmark took 1000000552 nanoseconds + * }, 1000); + * ``` + * @since 0.7.6 + * @legacy Use {@link process.hrtime.bigint()} instead. + * @param time The result of a previous call to `process.hrtime()` + */ + (time?: [number, number]): [number, number]; + /** + * The `bigint` version of the {@link process.hrtime()} method returning the current high-resolution real time in nanoseconds as a `bigint`. + * + * Unlike {@link process.hrtime()}, it does not support an additional time argument since the difference can just be computed directly by subtraction of the two `bigint`s. + * ```js + * import { hrtime } from 'node:process'; + * + * const start = hrtime.bigint(); + * // 191051479007711n + * + * setTimeout(() => { + * const end = hrtime.bigint(); + * // 191052633396993n + * + * console.log(`Benchmark took ${end - start} nanoseconds`); + * // Benchmark took 1154389282 nanoseconds + * }, 1000); + * ``` + * @since v10.7.0 + */ + bigint(): bigint; + } + interface ProcessPermission { + /** + * Verifies that the process is able to access the given scope and reference. + * If no reference is provided, a global scope is assumed, for instance, `process.permission.has('fs.read')` + * will check if the process has ALL file system read permissions. + * + * The reference has a meaning based on the provided scope. For example, the reference when the scope is File System means files and folders. + * + * The available scopes are: + * + * * `fs` - All File System + * * `fs.read` - File System read operations + * * `fs.write` - File System write operations + * * `child` - Child process spawning operations + * * `worker` - Worker thread spawning operation + * + * ```js + * // Check if the process has permission to read the README file + * process.permission.has('fs.read', './README.md'); + * // Check if the process has read permission operations + * process.permission.has('fs.read'); + * ``` + * @since v20.0.0 + */ + has(scope: string, reference?: string): boolean; + } + interface ProcessReport { + /** + * Write reports in a compact format, single-line JSON, more easily consumable by log processing systems + * than the default multi-line format designed for human consumption. + * @since v13.12.0, v12.17.0 + */ + compact: boolean; + /** + * Directory where the report is written. + * The default value is the empty string, indicating that reports are written to the current + * working directory of the Node.js process. + */ + directory: string; + /** + * Filename where the report is written. If set to the empty string, the output filename will be comprised + * of a timestamp, PID, and sequence number. The default value is the empty string. + */ + filename: string; + /** + * Returns a JavaScript Object representation of a diagnostic report for the running process. + * The report's JavaScript stack trace is taken from `err`, if present. + */ + getReport(err?: Error): object; + /** + * If true, a diagnostic report is generated on fatal errors, + * such as out of memory errors or failed C++ assertions. + * @default false + */ + reportOnFatalError: boolean; + /** + * If true, a diagnostic report is generated when the process + * receives the signal specified by process.report.signal. + * @default false + */ + reportOnSignal: boolean; + /** + * If true, a diagnostic report is generated on uncaught exception. + * @default false + */ + reportOnUncaughtException: boolean; + /** + * The signal used to trigger the creation of a diagnostic report. + * @default 'SIGUSR2' + */ + signal: Signals; + /** + * Writes a diagnostic report to a file. If filename is not provided, the default filename + * includes the date, time, PID, and a sequence number. + * The report's JavaScript stack trace is taken from `err`, if present. + * + * If the value of filename is set to `'stdout'` or `'stderr'`, the report is written + * to the stdout or stderr of the process respectively. + * @param fileName Name of the file where the report is written. + * This should be a relative path, that will be appended to the directory specified in + * `process.report.directory`, or the current working directory of the Node.js process, + * if unspecified. + * @param err A custom error used for reporting the JavaScript stack. + * @return Filename of the generated report. + */ + writeReport(fileName?: string, err?: Error): string; + writeReport(err?: Error): string; + } + interface ResourceUsage { + fsRead: number; + fsWrite: number; + involuntaryContextSwitches: number; + ipcReceived: number; + ipcSent: number; + majorPageFault: number; + maxRSS: number; + minorPageFault: number; + sharedMemorySize: number; + signalsCount: number; + swappedOut: number; + systemCPUTime: number; + unsharedDataSize: number; + unsharedStackSize: number; + userCPUTime: number; + voluntaryContextSwitches: number; + } + interface EmitWarningOptions { + /** + * When `warning` is a `string`, `type` is the name to use for the _type_ of warning being emitted. + * + * @default 'Warning' + */ + type?: string | undefined; + /** + * A unique identifier for the warning instance being emitted. + */ + code?: string | undefined; + /** + * When `warning` is a `string`, `ctor` is an optional function used to limit the generated stack trace. + * + * @default process.emitWarning + */ + ctor?: Function | undefined; + /** + * Additional text to include with the error. + */ + detail?: string | undefined; + } + interface ProcessConfig { + readonly target_defaults: { + readonly cflags: any[]; + readonly default_configuration: string; + readonly defines: string[]; + readonly include_dirs: string[]; + readonly libraries: string[]; + }; + readonly variables: { + readonly clang: number; + readonly host_arch: string; + readonly node_install_npm: boolean; + readonly node_install_waf: boolean; + readonly node_prefix: string; + readonly node_shared_openssl: boolean; + readonly node_shared_v8: boolean; + readonly node_shared_zlib: boolean; + readonly node_use_dtrace: boolean; + readonly node_use_etw: boolean; + readonly node_use_openssl: boolean; + readonly target_arch: string; + readonly v8_no_strict_aliasing: number; + readonly v8_use_snapshot: boolean; + readonly visibility: string; + }; + } + interface Process extends InternalEventEmitter { + /** + * The `process.stdout` property returns a stream connected to`stdout` (fd `1`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `1` refers to a file, in which case it is + * a `Writable` stream. + * + * For example, to copy `process.stdin` to `process.stdout`: + * + * ```js + * import { stdin, stdout } from 'node:process'; + * + * stdin.pipe(stdout); + * ``` + * + * `process.stdout` differs from other Node.js streams in important ways. See `note on process I/O` for more information. + */ + stdout: WriteStream & { + fd: 1; + }; + /** + * The `process.stderr` property returns a stream connected to`stderr` (fd `2`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `2` refers to a file, in which case it is + * a `Writable` stream. + * + * `process.stderr` differs from other Node.js streams in important ways. See `note on process I/O` for more information. + */ + stderr: WriteStream & { + fd: 2; + }; + /** + * The `process.stdin` property returns a stream connected to`stdin` (fd `0`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `0` refers to a file, in which case it is + * a `Readable` stream. + * + * For details of how to read from `stdin` see `readable.read()`. + * + * As a `Duplex` stream, `process.stdin` can also be used in "old" mode that + * is compatible with scripts written for Node.js prior to v0.10\. + * For more information see `Stream compatibility`. + * + * In "old" streams mode the `stdin` stream is paused by default, so one + * must call `process.stdin.resume()` to read from it. Note also that calling `process.stdin.resume()` itself would switch stream to "old" mode. + */ + stdin: ReadStream & { + fd: 0; + }; + /** + * The `process.argv` property returns an array containing the command-line + * arguments passed when the Node.js process was launched. The first element will + * be {@link execPath}. See `process.argv0` if access to the original value + * of `argv[0]` is needed. The second element will be the path to the JavaScript + * file being executed. The remaining elements will be any additional command-line + * arguments. + * + * For example, assuming the following script for `process-args.js`: + * + * ```js + * import { argv } from 'node:process'; + * + * // print process.argv + * argv.forEach((val, index) => { + * console.log(`${index}: ${val}`); + * }); + * ``` + * + * Launching the Node.js process as: + * + * ```bash + * node process-args.js one two=three four + * ``` + * + * Would generate the output: + * + * ```text + * 0: /usr/local/bin/node + * 1: /Users/mjr/work/node/process-args.js + * 2: one + * 3: two=three + * 4: four + * ``` + * @since v0.1.27 + */ + argv: string[]; + /** + * The `process.argv0` property stores a read-only copy of the original value of`argv[0]` passed when Node.js starts. + * + * ```console + * $ bash -c 'exec -a customArgv0 ./node' + * > process.argv[0] + * '/Volumes/code/external/node/out/Release/node' + * > process.argv0 + * 'customArgv0' + * ``` + * @since v6.4.0 + */ + argv0: string; + /** + * The `process.execArgv` property returns the set of Node.js-specific command-line + * options passed when the Node.js process was launched. These options do not + * appear in the array returned by the {@link argv} property, and do not + * include the Node.js executable, the name of the script, or any options following + * the script name. These options are useful in order to spawn child processes with + * the same execution environment as the parent. + * + * ```bash + * node --icu-data-dir=./foo --require ./bar.js script.js --version + * ``` + * + * Results in `process.execArgv`: + * + * ```js + * ["--icu-data-dir=./foo", "--require", "./bar.js"] + * ``` + * + * And `process.argv`: + * + * ```js + * ['/usr/local/bin/node', 'script.js', '--version'] + * ``` + * + * Refer to `Worker constructor` for the detailed behavior of worker + * threads with this property. + * @since v0.7.7 + */ + execArgv: string[]; + /** + * The `process.execPath` property returns the absolute pathname of the executable + * that started the Node.js process. Symbolic links, if any, are resolved. + * + * ```js + * '/usr/local/bin/node' + * ``` + * @since v0.1.100 + */ + execPath: string; + /** + * The `process.abort()` method causes the Node.js process to exit immediately and + * generate a core file. + * + * This feature is not available in `Worker` threads. + * @since v0.7.0 + */ + abort(): never; + /** + * The `process.chdir()` method changes the current working directory of the + * Node.js process or throws an exception if doing so fails (for instance, if + * the specified `directory` does not exist). + * + * ```js + * import { chdir, cwd } from 'node:process'; + * + * console.log(`Starting directory: ${cwd()}`); + * try { + * chdir('/tmp'); + * console.log(`New directory: ${cwd()}`); + * } catch (err) { + * console.error(`chdir: ${err}`); + * } + * ``` + * + * This feature is not available in `Worker` threads. + * @since v0.1.17 + */ + chdir(directory: string): void; + /** + * The `process.cwd()` method returns the current working directory of the Node.js + * process. + * + * ```js + * import { cwd } from 'node:process'; + * + * console.log(`Current directory: ${cwd()}`); + * ``` + * @since v0.1.8 + */ + cwd(): string; + /** + * The port used by the Node.js debugger when enabled. + * + * ```js + * import process from 'node:process'; + * + * process.debugPort = 5858; + * ``` + * @since v0.7.2 + */ + debugPort: number; + /** + * The `process.dlopen()` method allows dynamically loading shared objects. It is primarily used by `require()` to load C++ Addons, and + * should not be used directly, except in special cases. In other words, `require()` should be preferred over `process.dlopen()` + * unless there are specific reasons such as custom dlopen flags or loading from ES modules. + * + * The `flags` argument is an integer that allows to specify dlopen behavior. See the `[os.constants.dlopen](https://nodejs.org/docs/latest-v25.x/api/os.html#dlopen-constants)` + * documentation for details. + * + * An important requirement when calling `process.dlopen()` is that the `module` instance must be passed. Functions exported by the C++ Addon + * are then accessible via `module.exports`. + * + * The example below shows how to load a C++ Addon, named `local.node`, that exports a `foo` function. All the symbols are loaded before the call returns, by passing the `RTLD_NOW` constant. + * In this example the constant is assumed to be available. + * + * ```js + * import { dlopen } from 'node:process'; + * import { constants } from 'node:os'; + * import { fileURLToPath } from 'node:url'; + * + * const module = { exports: {} }; + * dlopen(module, fileURLToPath(new URL('local.node', import.meta.url)), + * constants.dlopen.RTLD_NOW); + * module.exports.foo(); + * ``` + */ + dlopen(module: object, filename: string, flags?: number): void; + /** + * The `process.emitWarning()` method can be used to emit custom or application + * specific process warnings. These can be listened for by adding a handler to the `'warning'` event. + * + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning using a string. + * emitWarning('Something happened!'); + * // Emits: (node: 56338) Warning: Something happened! + * ``` + * + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning using a string and a type. + * emitWarning('Something Happened!', 'CustomWarning'); + * // Emits: (node:56338) CustomWarning: Something Happened! + * ``` + * + * ```js + * import { emitWarning } from 'node:process'; + * + * emitWarning('Something happened!', 'CustomWarning', 'WARN001'); + * // Emits: (node:56338) [WARN001] CustomWarning: Something happened! + * ```js + * + * In each of the previous examples, an `Error` object is generated internally by `process.emitWarning()` and passed through to the `'warning'` handler. + * + * ```js + * import process from 'node:process'; + * + * process.on('warning', (warning) => { + * console.warn(warning.name); // 'Warning' + * console.warn(warning.message); // 'Something happened!' + * console.warn(warning.code); // 'MY_WARNING' + * console.warn(warning.stack); // Stack trace + * console.warn(warning.detail); // 'This is some additional information' + * }); + * ``` + * + * If `warning` is passed as an `Error` object, it will be passed through to the `'warning'` event handler + * unmodified (and the optional `type`, `code` and `ctor` arguments will be ignored): + * + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning using an Error object. + * const myWarning = new Error('Something happened!'); + * // Use the Error name property to specify the type name + * myWarning.name = 'CustomWarning'; + * myWarning.code = 'WARN001'; + * + * emitWarning(myWarning); + * // Emits: (node:56338) [WARN001] CustomWarning: Something happened! + * ``` + * + * A `TypeError` is thrown if `warning` is anything other than a string or `Error` object. + * + * While process warnings use `Error` objects, the process warning mechanism is not a replacement for normal error handling mechanisms. + * + * The following additional handling is implemented if the warning `type` is `'DeprecationWarning'`: + * * If the `--throw-deprecation` command-line flag is used, the deprecation warning is thrown as an exception rather than being emitted as an event. + * * If the `--no-deprecation` command-line flag is used, the deprecation warning is suppressed. + * * If the `--trace-deprecation` command-line flag is used, the deprecation warning is printed to `stderr` along with the full stack trace. + * @since v8.0.0 + * @param warning The warning to emit. + */ + emitWarning(warning: string | Error, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, code?: string, ctor?: Function): void; + emitWarning(warning: string | Error, options?: EmitWarningOptions): void; + /** + * The `process.env` property returns an object containing the user environment. + * See [`environ(7)`](http://man7.org/linux/man-pages/man7/environ.7.html). + * + * An example of this object looks like: + * + * ```js + * { + * TERM: 'xterm-256color', + * SHELL: '/usr/local/bin/bash', + * USER: 'maciej', + * PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin', + * PWD: '/Users/maciej', + * EDITOR: 'vim', + * SHLVL: '1', + * HOME: '/Users/maciej', + * LOGNAME: 'maciej', + * _: '/usr/local/bin/node' + * } + * ``` + * + * It is possible to modify this object, but such modifications will not be + * reflected outside the Node.js process, or (unless explicitly requested) + * to other `Worker` threads. + * In other words, the following example would not work: + * + * ```bash + * node -e 'process.env.foo = "bar"' && echo $foo + * ``` + * + * While the following will: + * + * ```js + * import { env } from 'node:process'; + * + * env.foo = 'bar'; + * console.log(env.foo); + * ``` + * + * Assigning a property on `process.env` will implicitly convert the value + * to a string. **This behavior is deprecated.** Future versions of Node.js may + * throw an error when the value is not a string, number, or boolean. + * + * ```js + * import { env } from 'node:process'; + * + * env.test = null; + * console.log(env.test); + * // => 'null' + * env.test = undefined; + * console.log(env.test); + * // => 'undefined' + * ``` + * + * Use `delete` to delete a property from `process.env`. + * + * ```js + * import { env } from 'node:process'; + * + * env.TEST = 1; + * delete env.TEST; + * console.log(env.TEST); + * // => undefined + * ``` + * + * On Windows operating systems, environment variables are case-insensitive. + * + * ```js + * import { env } from 'node:process'; + * + * env.TEST = 1; + * console.log(env.test); + * // => 1 + * ``` + * + * Unless explicitly specified when creating a `Worker` instance, + * each `Worker` thread has its own copy of `process.env`, based on its + * parent thread's `process.env`, or whatever was specified as the `env` option + * to the `Worker` constructor. Changes to `process.env` will not be visible + * across `Worker` threads, and only the main thread can make changes that + * are visible to the operating system or to native add-ons. On Windows, a copy of `process.env` on a `Worker` instance operates in a case-sensitive manner + * unlike the main thread. + * @since v0.1.27 + */ + env: ProcessEnv; + /** + * The `process.exit()` method instructs Node.js to terminate the process + * synchronously with an exit status of `code`. If `code` is omitted, exit uses + * either the 'success' code `0` or the value of `process.exitCode` if it has been + * set. Node.js will not terminate until all the `'exit'` event listeners are + * called. + * + * To exit with a 'failure' code: + * + * ```js + * import { exit } from 'node:process'; + * + * exit(1); + * ``` + * + * The shell that executed Node.js should see the exit code as `1`. + * + * Calling `process.exit()` will force the process to exit as quickly as possible + * even if there are still asynchronous operations pending that have not yet + * completed fully, including I/O operations to `process.stdout` and `process.stderr`. + * + * In most situations, it is not actually necessary to call `process.exit()` explicitly. The Node.js process will exit on its own _if there is no additional_ + * _work pending_ in the event loop. The `process.exitCode` property can be set to + * tell the process which exit code to use when the process exits gracefully. + * + * For instance, the following example illustrates a _misuse_ of the `process.exit()` method that could lead to data printed to stdout being + * truncated and lost: + * + * ```js + * import { exit } from 'node:process'; + * + * // This is an example of what *not* to do: + * if (someConditionNotMet()) { + * printUsageToStdout(); + * exit(1); + * } + * ``` + * + * The reason this is problematic is because writes to `process.stdout` in Node.js + * are sometimes _asynchronous_ and may occur over multiple ticks of the Node.js + * event loop. Calling `process.exit()`, however, forces the process to exit _before_ those additional writes to `stdout` can be performed. + * + * Rather than calling `process.exit()` directly, the code _should_ set the `process.exitCode` and allow the process to exit naturally by avoiding + * scheduling any additional work for the event loop: + * + * ```js + * import process from 'node:process'; + * + * // How to properly set the exit code while letting + * // the process exit gracefully. + * if (someConditionNotMet()) { + * printUsageToStdout(); + * process.exitCode = 1; + * } + * ``` + * + * If it is necessary to terminate the Node.js process due to an error condition, + * throwing an _uncaught_ error and allowing the process to terminate accordingly + * is safer than calling `process.exit()`. + * + * In `Worker` threads, this function stops the current thread rather + * than the current process. + * @since v0.1.13 + * @param [code=0] The exit code. For string type, only integer strings (e.g.,'1') are allowed. + */ + exit(code?: number | string | null): never; + /** + * A number which will be the process exit code, when the process either + * exits gracefully, or is exited via {@link exit} without specifying + * a code. + * + * Specifying a code to {@link exit} will override any + * previous setting of `process.exitCode`. + * @default undefined + * @since v0.11.8 + */ + exitCode: number | string | null | undefined; + finalization: { + /** + * This function registers a callback to be called when the process emits the `exit` event if the `ref` object was not garbage collected. + * If the object `ref` was garbage collected before the `exit` event is emitted, the callback will be removed from the finalization registry, and it will not be called on process exit. + * + * Inside the callback you can release the resources allocated by the `ref` object. + * Be aware that all limitations applied to the `beforeExit` event are also applied to the callback function, + * this means that there is a possibility that the callback will not be called under special circumstances. + * + * The idea of ​​this function is to help you free up resources when the starts process exiting, but also let the object be garbage collected if it is no longer being used. + * @param ref The reference to the resource that is being tracked. + * @param callback The callback function to be called when the resource is finalized. + * @since v22.5.0 + * @experimental + */ + register(ref: T, callback: (ref: T, event: "exit") => void): void; + /** + * This function behaves exactly like the `register`, except that the callback will be called when the process emits the `beforeExit` event if `ref` object was not garbage collected. + * + * Be aware that all limitations applied to the `beforeExit` event are also applied to the callback function, this means that there is a possibility that the callback will not be called under special circumstances. + * @param ref The reference to the resource that is being tracked. + * @param callback The callback function to be called when the resource is finalized. + * @since v22.5.0 + * @experimental + */ + registerBeforeExit(ref: T, callback: (ref: T, event: "beforeExit") => void): void; + /** + * This function remove the register of the object from the finalization registry, so the callback will not be called anymore. + * @param ref The reference to the resource that was registered previously. + * @since v22.5.0 + * @experimental + */ + unregister(ref: object): void; + }; + /** + * The `process.getActiveResourcesInfo()` method returns an array of strings containing + * the types of the active resources that are currently keeping the event loop alive. + * + * ```js + * import { getActiveResourcesInfo } from 'node:process'; + * import { setTimeout } from 'node:timers'; + + * console.log('Before:', getActiveResourcesInfo()); + * setTimeout(() => {}, 1000); + * console.log('After:', getActiveResourcesInfo()); + * // Prints: + * // Before: [ 'TTYWrap', 'TTYWrap', 'TTYWrap' ] + * // After: [ 'TTYWrap', 'TTYWrap', 'TTYWrap', 'Timeout' ] + * ``` + * @since v17.3.0, v16.14.0 + */ + getActiveResourcesInfo(): string[]; + /** + * Provides a way to load built-in modules in a globally available function. + * @param id ID of the built-in module being requested. + */ + getBuiltinModule(id: ID): BuiltInModule[ID]; + getBuiltinModule(id: string): object | undefined; + /** + * The `process.getgid()` method returns the numerical group identity of the + * process. (See [`getgid(2)`](http://man7.org/linux/man-pages/man2/getgid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.getgid) { + * console.log(`Current gid: ${process.getgid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.31 + */ + getgid?: () => number; + /** + * The `process.setgid()` method sets the group identity of the process. (See [`setgid(2)`](http://man7.org/linux/man-pages/man2/setgid.2.html).) The `id` can be passed as either a + * numeric ID or a group name + * string. If a group name is specified, this method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.getgid && process.setgid) { + * console.log(`Current gid: ${process.getgid()}`); + * try { + * process.setgid(501); + * console.log(`New gid: ${process.getgid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.31 + * @param id The group name or ID + */ + setgid?: (id: number | string) => void; + /** + * The `process.getuid()` method returns the numeric user identity of the process. + * (See [`getuid(2)`](http://man7.org/linux/man-pages/man2/getuid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.getuid) { + * console.log(`Current uid: ${process.getuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.28 + */ + getuid?: () => number; + /** + * The `process.setuid(id)` method sets the user identity of the process. (See [`setuid(2)`](http://man7.org/linux/man-pages/man2/setuid.2.html).) The `id` can be passed as either a + * numeric ID or a username string. + * If a username is specified, the method blocks while resolving the associated + * numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.getuid && process.setuid) { + * console.log(`Current uid: ${process.getuid()}`); + * try { + * process.setuid(501); + * console.log(`New uid: ${process.getuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.28 + */ + setuid?: (id: number | string) => void; + /** + * The `process.geteuid()` method returns the numerical effective user identity of + * the process. (See [`geteuid(2)`](http://man7.org/linux/man-pages/man2/geteuid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.geteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ + geteuid?: () => number; + /** + * The `process.seteuid()` method sets the effective user identity of the process. + * (See [`seteuid(2)`](http://man7.org/linux/man-pages/man2/seteuid.2.html).) The `id` can be passed as either a numeric ID or a username + * string. If a username is specified, the method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.geteuid && process.seteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * try { + * process.seteuid(501); + * console.log(`New uid: ${process.geteuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A user name or ID + */ + seteuid?: (id: number | string) => void; + /** + * The `process.getegid()` method returns the numerical effective group identity + * of the Node.js process. (See [`getegid(2)`](http://man7.org/linux/man-pages/man2/getegid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.getegid) { + * console.log(`Current gid: ${process.getegid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ + getegid?: () => number; + /** + * The `process.setegid()` method sets the effective group identity of the process. + * (See [`setegid(2)`](http://man7.org/linux/man-pages/man2/setegid.2.html).) The `id` can be passed as either a numeric ID or a group + * name string. If a group name is specified, this method blocks while resolving + * the associated a numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.getegid && process.setegid) { + * console.log(`Current gid: ${process.getegid()}`); + * try { + * process.setegid(501); + * console.log(`New gid: ${process.getegid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A group name or ID + */ + setegid?: (id: number | string) => void; + /** + * The `process.getgroups()` method returns an array with the supplementary group + * IDs. POSIX leaves it unspecified if the effective group ID is included but + * Node.js ensures it always is. + * + * ```js + * import process from 'node:process'; + * + * if (process.getgroups) { + * console.log(process.getgroups()); // [ 16, 21, 297 ] + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.9.4 + */ + getgroups?: () => number[]; + /** + * The `process.setgroups()` method sets the supplementary group IDs for the + * Node.js process. This is a privileged operation that requires the Node.js + * process to have `root` or the `CAP_SETGID` capability. + * + * The `groups` array can contain numeric group IDs, group names, or both. + * + * ```js + * import process from 'node:process'; + * + * if (process.getgroups && process.setgroups) { + * try { + * process.setgroups([501]); + * console.log(process.getgroups()); // new groups + * } catch (err) { + * console.log(`Failed to set groups: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.9.4 + */ + setgroups?: (groups: ReadonlyArray) => void; + /** + * The `process.setUncaughtExceptionCaptureCallback()` function sets a function + * that will be invoked when an uncaught exception occurs, which will receive the + * exception value itself as its first argument. + * + * If such a function is set, the `'uncaughtException'` event will + * not be emitted. If `--abort-on-uncaught-exception` was passed from the + * command line or set through `v8.setFlagsFromString()`, the process will + * not abort. Actions configured to take place on exceptions such as report + * generations will be affected too + * + * To unset the capture function, `process.setUncaughtExceptionCaptureCallback(null)` may be used. Calling this + * method with a non-`null` argument while another capture function is set will + * throw an error. + * + * Using this function is mutually exclusive with using the deprecated `domain` built-in module. + * @since v9.3.0 + */ + setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; + /** + * Indicates whether a callback has been set using {@link setUncaughtExceptionCaptureCallback}. + * @since v9.3.0 + */ + hasUncaughtExceptionCaptureCallback(): boolean; + /** + * The `process.sourceMapsEnabled` property returns whether the [Source Map v3](https://sourcemaps.info/spec.html) support for stack traces is enabled. + * @since v20.7.0 + * @experimental + */ + readonly sourceMapsEnabled: boolean; + /** + * This function enables or disables the [Source Map v3](https://sourcemaps.info/spec.html) support for + * stack traces. + * + * It provides same features as launching Node.js process with commandline options `--enable-source-maps`. + * + * Only source maps in JavaScript files that are loaded after source maps has been + * enabled will be parsed and loaded. + * @since v16.6.0, v14.18.0 + * @experimental + */ + setSourceMapsEnabled(value: boolean): void; + /** + * The `process.version` property contains the Node.js version string. + * + * ```js + * import { version } from 'node:process'; + * + * console.log(`Version: ${version}`); + * // Version: v14.8.0 + * ``` + * + * To get the version string without the prepended _v_, use`process.versions.node`. + * @since v0.1.3 + */ + readonly version: string; + /** + * The `process.versions` property returns an object listing the version strings of + * Node.js and its dependencies. `process.versions.modules` indicates the current + * ABI version, which is increased whenever a C++ API changes. Node.js will refuse + * to load modules that were compiled against a different module ABI version. + * + * ```js + * import { versions } from 'node:process'; + * + * console.log(versions); + * ``` + * + * Will generate an object similar to: + * + * ```console + * { node: '20.2.0', + * acorn: '8.8.2', + * ada: '2.4.0', + * ares: '1.19.0', + * base64: '0.5.0', + * brotli: '1.0.9', + * cjs_module_lexer: '1.2.2', + * cldr: '43.0', + * icu: '73.1', + * llhttp: '8.1.0', + * modules: '115', + * napi: '8', + * nghttp2: '1.52.0', + * nghttp3: '0.7.0', + * ngtcp2: '0.8.1', + * openssl: '3.0.8+quic', + * simdutf: '3.2.9', + * tz: '2023c', + * undici: '5.22.0', + * unicode: '15.0', + * uv: '1.44.2', + * uvwasi: '0.0.16', + * v8: '11.3.244.8-node.9', + * zlib: '1.2.13' } + * ``` + * @since v0.2.0 + */ + readonly versions: ProcessVersions; + /** + * The `process.config` property returns a frozen `Object` containing the + * JavaScript representation of the configure options used to compile the current + * Node.js executable. This is the same as the `config.gypi` file that was produced + * when running the `./configure` script. + * + * An example of the possible output looks like: + * + * ```js + * { + * target_defaults: + * { cflags: [], + * default_configuration: 'Release', + * defines: [], + * include_dirs: [], + * libraries: [] }, + * variables: + * { + * host_arch: 'x64', + * napi_build_version: 5, + * node_install_npm: 'true', + * node_prefix: '', + * node_shared_cares: 'false', + * node_shared_http_parser: 'false', + * node_shared_libuv: 'false', + * node_shared_zlib: 'false', + * node_use_openssl: 'true', + * node_shared_openssl: 'false', + * strict_aliasing: 'true', + * target_arch: 'x64', + * v8_use_snapshot: 1 + * } + * } + * ``` + * @since v0.7.7 + */ + readonly config: ProcessConfig; + /** + * The `process.kill()` method sends the `signal` to the process identified by`pid`. + * + * Signal names are strings such as `'SIGINT'` or `'SIGHUP'`. See `Signal Events` and [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for more information. + * + * This method will throw an error if the target `pid` does not exist. As a special + * case, a signal of `0` can be used to test for the existence of a process. + * Windows platforms will throw an error if the `pid` is used to kill a process + * group. + * + * Even though the name of this function is `process.kill()`, it is really just a + * signal sender, like the `kill` system call. The signal sent may do something + * other than kill the target process. + * + * ```js + * import process, { kill } from 'node:process'; + * + * process.on('SIGHUP', () => { + * console.log('Got SIGHUP signal.'); + * }); + * + * setTimeout(() => { + * console.log('Exiting.'); + * process.exit(0); + * }, 100); + * + * kill(process.pid, 'SIGHUP'); + * ``` + * + * When `SIGUSR1` is received by a Node.js process, Node.js will start the + * debugger. See `Signal Events`. + * @since v0.0.6 + * @param pid A process ID + * @param [signal='SIGTERM'] The signal to send, either as a string or number. + */ + kill(pid: number, signal?: string | number): true; + /** + * Loads the environment configuration from a `.env` file into `process.env`. If + * the file is not found, error will be thrown. + * + * To load a specific .env file by specifying its path, use the following code: + * + * ```js + * import { loadEnvFile } from 'node:process'; + * + * loadEnvFile('./development.env') + * ``` + * @since v20.12.0 + * @param path The path to the .env file + */ + loadEnvFile(path?: PathLike): void; + /** + * The `process.pid` property returns the PID of the process. + * + * ```js + * import { pid } from 'node:process'; + * + * console.log(`This process is pid ${pid}`); + * ``` + * @since v0.1.15 + */ + readonly pid: number; + /** + * The `process.ppid` property returns the PID of the parent of the + * current process. + * + * ```js + * import { ppid } from 'node:process'; + * + * console.log(`The parent process is pid ${ppid}`); + * ``` + * @since v9.2.0, v8.10.0, v6.13.0 + */ + readonly ppid: number; + /** + * The `process.threadCpuUsage()` method returns the user and system CPU time usage of + * the current worker thread, in an object with properties `user` and `system`, whose + * values are microsecond values (millionth of a second). + * + * The result of a previous call to `process.threadCpuUsage()` can be passed as the + * argument to the function, to get a diff reading. + * @since v23.9.0 + * @param previousValue A previous return value from calling + * `process.threadCpuUsage()` + */ + threadCpuUsage(previousValue?: CpuUsage): CpuUsage; + /** + * The `process.title` property returns the current process title (i.e. returns + * the current value of `ps`). Assigning a new value to `process.title` modifies + * the current value of `ps`. + * + * When a new value is assigned, different platforms will impose different maximum + * length restrictions on the title. Usually such restrictions are quite limited. + * For instance, on Linux and macOS, `process.title` is limited to the size of the + * binary name plus the length of the command-line arguments because setting the `process.title` overwrites the `argv` memory of the process. Node.js v0.8 + * allowed for longer process title strings by also overwriting the `environ` memory but that was potentially insecure and confusing in some (rather obscure) + * cases. + * + * Assigning a value to `process.title` might not result in an accurate label + * within process manager applications such as macOS Activity Monitor or Windows + * Services Manager. + * @since v0.1.104 + */ + title: string; + /** + * The operating system CPU architecture for which the Node.js binary was compiled. + * Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`, `'mips'`, + * `'mipsel'`, `'ppc64'`, `'riscv64'`, `'s390x'`, and `'x64'`. + * + * ```js + * import { arch } from 'node:process'; + * + * console.log(`This processor architecture is ${arch}`); + * ``` + * @since v0.5.0 + */ + readonly arch: Architecture; + /** + * The `process.platform` property returns a string identifying the operating + * system platform for which the Node.js binary was compiled. + * + * Currently possible values are: + * + * * `'aix'` + * * `'darwin'` + * * `'freebsd'` + * * `'linux'` + * * `'openbsd'` + * * `'sunos'` + * * `'win32'` + * + * ```js + * import { platform } from 'node:process'; + * + * console.log(`This platform is ${platform}`); + * ``` + * + * The value `'android'` may also be returned if the Node.js is built on the + * Android operating system. However, Android support in Node.js [is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). + * @since v0.1.16 + */ + readonly platform: Platform; + /** + * The `process.mainModule` property provides an alternative way of retrieving `require.main`. The difference is that if the main module changes at + * runtime, `require.main` may still refer to the original main module in + * modules that were required before the change occurred. Generally, it's + * safe to assume that the two refer to the same module. + * + * As with `require.main`, `process.mainModule` will be `undefined` if there + * is no entry script. + * @since v0.1.17 + * @deprecated Since v14.0.0 - Use `main` instead. + */ + mainModule?: Module; + memoryUsage: MemoryUsageFn; + /** + * Gets the amount of memory available to the process (in bytes) based on + * limits imposed by the OS. If there is no such constraint, or the constraint + * is unknown, `0` is returned. + * + * See [`uv_get_constrained_memory`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_get_constrained_memory) for more + * information. + * @since v19.6.0, v18.15.0 + */ + constrainedMemory(): number; + /** + * Gets the amount of free memory that is still available to the process (in bytes). + * See [`uv_get_available_memory`](https://nodejs.org/docs/latest-v25.x/api/process.html#processavailablememory) for more information. + * @since v20.13.0 + */ + availableMemory(): number; + /** + * The `process.cpuUsage()` method returns the user and system CPU time usage of + * the current process, in an object with properties `user` and `system`, whose + * values are microsecond values (millionth of a second). These values measure time + * spent in user and system code respectively, and may end up being greater than + * actual elapsed time if multiple CPU cores are performing work for this process. + * + * The result of a previous call to `process.cpuUsage()` can be passed as the + * argument to the function, to get a diff reading. + * + * ```js + * import { cpuUsage } from 'node:process'; + * + * const startUsage = cpuUsage(); + * // { user: 38579, system: 6986 } + * + * // spin the CPU for 500 milliseconds + * const now = Date.now(); + * while (Date.now() - now < 500); + * + * console.log(cpuUsage(startUsage)); + * // { user: 514883, system: 11226 } + * ``` + * @since v6.1.0 + * @param previousValue A previous return value from calling `process.cpuUsage()` + */ + cpuUsage(previousValue?: CpuUsage): CpuUsage; + /** + * `process.nextTick()` adds `callback` to the "next tick queue". This queue is + * fully drained after the current operation on the JavaScript stack runs to + * completion and before the event loop is allowed to continue. It's possible to + * create an infinite loop if one were to recursively call `process.nextTick()`. + * See the [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#process-nexttick) guide for more background. + * + * ```js + * import { nextTick } from 'node:process'; + * + * console.log('start'); + * nextTick(() => { + * console.log('nextTick callback'); + * }); + * console.log('scheduled'); + * // Output: + * // start + * // scheduled + * // nextTick callback + * ``` + * + * This is important when developing APIs in order to give users the opportunity + * to assign event handlers _after_ an object has been constructed but before any + * I/O has occurred: + * + * ```js + * import { nextTick } from 'node:process'; + * + * function MyThing(options) { + * this.setupOptions(options); + * + * nextTick(() => { + * this.startDoingStuff(); + * }); + * } + * + * const thing = new MyThing(); + * thing.getReadyForStuff(); + * + * // thing.startDoingStuff() gets called now, not before. + * ``` + * + * It is very important for APIs to be either 100% synchronous or 100% + * asynchronous. Consider this example: + * + * ```js + * // WARNING! DO NOT USE! BAD UNSAFE HAZARD! + * function maybeSync(arg, cb) { + * if (arg) { + * cb(); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * + * This API is hazardous because in the following case: + * + * ```js + * const maybeTrue = Math.random() > 0.5; + * + * maybeSync(maybeTrue, () => { + * foo(); + * }); + * + * bar(); + * ``` + * + * It is not clear whether `foo()` or `bar()` will be called first. + * + * The following approach is much better: + * + * ```js + * import { nextTick } from 'node:process'; + * + * function definitelyAsync(arg, cb) { + * if (arg) { + * nextTick(cb); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * @since v0.1.26 + * @param args Additional arguments to pass when invoking the `callback` + */ + nextTick(callback: Function, ...args: any[]): void; + /** + * This API is available through the [--permission](https://nodejs.org/api/cli.html#--permission) flag. + * + * `process.permission` is an object whose methods are used to manage permissions for the current process. + * Additional documentation is available in the [Permission Model](https://nodejs.org/api/permissions.html#permission-model). + * @since v20.0.0 + */ + permission: ProcessPermission; + /** + * The `process.release` property returns an `Object` containing metadata related + * to the current release, including URLs for the source tarball and headers-only + * tarball. + * + * `process.release` contains the following properties: + * + * ```js + * { + * name: 'node', + * lts: 'Hydrogen', + * sourceUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0.tar.gz', + * headersUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0-headers.tar.gz', + * libUrl: 'https://nodejs.org/download/release/v18.12.0/win-x64/node.lib' + * } + * ``` + * + * In custom builds from non-release versions of the source tree, only the `name` property may be present. The additional properties should not be + * relied upon to exist. + * @since v3.0.0 + */ + readonly release: ProcessRelease; + readonly features: ProcessFeatures; + /** + * `process.umask()` returns the Node.js process's file mode creation mask. Child + * processes inherit the mask from the parent process. + * @since v0.1.19 + * @deprecated Calling `process.umask()` with no argument causes the process-wide umask to be written twice. This introduces a race condition between threads, and is a potential + * security vulnerability. There is no safe, cross-platform alternative API. + */ + umask(): number; + /** + * Can only be set if not in worker thread. + */ + umask(mask: string | number): number; + /** + * The `process.uptime()` method returns the number of seconds the current Node.js + * process has been running. + * + * The return value includes fractions of a second. Use `Math.floor()` to get whole + * seconds. + * @since v0.5.0 + */ + uptime(): number; + hrtime: HRTime; + /** + * If the Node.js process was spawned with an IPC channel, the process.channel property is a reference to the IPC channel. + * If no IPC channel exists, this property is undefined. + * @since v7.1.0 + */ + channel?: Control; + /** + * If Node.js is spawned with an IPC channel, the `process.send()` method can be + * used to send messages to the parent process. Messages will be received as a `'message'` event on the parent's `ChildProcess` object. + * + * If Node.js was not spawned with an IPC channel, `process.send` will be `undefined`. + * + * The message goes through serialization and parsing. The resulting message might + * not be the same as what is originally sent. + * @since v0.5.9 + * @param options used to parameterize the sending of certain types of handles. `options` supports the following properties: + */ + send?( + message: any, + sendHandle?: SendHandle, + options?: MessageOptions, + callback?: (error: Error | null) => void, + ): boolean; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.disconnect()` method will close the + * IPC channel to the parent process, allowing the child process to exit gracefully + * once there are no other connections keeping it alive. + * + * The effect of calling `process.disconnect()` is the same as calling `ChildProcess.disconnect()` from the parent process. + * + * If the Node.js process was not spawned with an IPC channel, `process.disconnect()` will be `undefined`. + * @since v0.7.2 + */ + disconnect?(): void; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.connected` property will return `true` so long as the IPC + * channel is connected and will return `false` after `process.disconnect()` is called. + * + * Once `process.connected` is `false`, it is no longer possible to send messages + * over the IPC channel using `process.send()`. + * @since v0.7.2 + */ + connected: boolean; + /** + * The `process.allowedNodeEnvironmentFlags` property is a special, + * read-only `Set` of flags allowable within the `NODE_OPTIONS` environment variable. + * + * `process.allowedNodeEnvironmentFlags` extends `Set`, but overrides `Set.prototype.has` to recognize several different possible flag + * representations. `process.allowedNodeEnvironmentFlags.has()` will + * return `true` in the following cases: + * + * * Flags may omit leading single (`-`) or double (`--`) dashes; e.g., `inspect-brk` for `--inspect-brk`, or `r` for `-r`. + * * Flags passed through to V8 (as listed in `--v8-options`) may replace + * one or more _non-leading_ dashes for an underscore, or vice-versa; + * e.g., `--perf_basic_prof`, `--perf-basic-prof`, `--perf_basic-prof`, + * etc. + * * Flags may contain one or more equals (`=`) characters; all + * characters after and including the first equals will be ignored; + * e.g., `--stack-trace-limit=100`. + * * Flags _must_ be allowable within `NODE_OPTIONS`. + * + * When iterating over `process.allowedNodeEnvironmentFlags`, flags will + * appear only _once_; each will begin with one or more dashes. Flags + * passed through to V8 will contain underscores instead of non-leading + * dashes: + * + * ```js + * import { allowedNodeEnvironmentFlags } from 'node:process'; + * + * allowedNodeEnvironmentFlags.forEach((flag) => { + * // -r + * // --inspect-brk + * // --abort_on_uncaught_exception + * // ... + * }); + * ``` + * + * The methods `add()`, `clear()`, and `delete()` of`process.allowedNodeEnvironmentFlags` do nothing, and will fail + * silently. + * + * If Node.js was compiled _without_ `NODE_OPTIONS` support (shown in {@link config}), `process.allowedNodeEnvironmentFlags` will + * contain what _would have_ been allowable. + * @since v10.10.0 + */ + allowedNodeEnvironmentFlags: ReadonlySet; + /** + * `process.report` is an object whose methods are used to generate diagnostic reports for the current process. + * Additional documentation is available in the [report documentation](https://nodejs.org/docs/latest-v25.x/api/report.html). + * @since v11.8.0 + */ + report: ProcessReport; + /** + * ```js + * import { resourceUsage } from 'node:process'; + * + * console.log(resourceUsage()); + * /* + * Will output: + * { + * userCPUTime: 82872, + * systemCPUTime: 4143, + * maxRSS: 33164, + * sharedMemorySize: 0, + * unsharedDataSize: 0, + * unsharedStackSize: 0, + * minorPageFault: 2469, + * majorPageFault: 0, + * swappedOut: 0, + * fsRead: 0, + * fsWrite: 8, + * ipcSent: 0, + * ipcReceived: 0, + * signalsCount: 0, + * voluntaryContextSwitches: 79, + * involuntaryContextSwitches: 1 + * } + * + * ``` + * @since v12.6.0 + * @return the resource usage for the current process. All of these values come from the `uv_getrusage` call which returns a [`uv_rusage_t` struct][uv_rusage_t]. + */ + resourceUsage(): ResourceUsage; + /** + * The initial value of `process.throwDeprecation` indicates whether the `--throw-deprecation` flag is set on the current Node.js process. `process.throwDeprecation` + * is mutable, so whether or not deprecation warnings result in errors may be altered at runtime. See the documentation for the 'warning' event and the emitWarning() + * method for more information. + * + * ```bash + * $ node --throw-deprecation -p "process.throwDeprecation" + * true + * $ node -p "process.throwDeprecation" + * undefined + * $ node + * > process.emitWarning('test', 'DeprecationWarning'); + * undefined + * > (node:26598) DeprecationWarning: test + * > process.throwDeprecation = true; + * true + * > process.emitWarning('test', 'DeprecationWarning'); + * Thrown: + * [DeprecationWarning: test] { name: 'DeprecationWarning' } + * ``` + * @since v0.9.12 + */ + throwDeprecation: boolean; + /** + * The `process.traceDeprecation` property indicates whether the `--trace-deprecation` flag is set on the current Node.js process. See the + * documentation for the `'warning' event` and the `emitWarning() method` for more information about this + * flag's behavior. + * @since v0.8.0 + */ + traceDeprecation: boolean; + /** + * An object is "refable" if it implements the Node.js "Refable protocol". + * Specifically, this means that the object implements the `Symbol.for('nodejs.ref')` + * and `Symbol.for('nodejs.unref')` methods. "Ref'd" objects will keep the Node.js + * event loop alive, while "unref'd" objects will not. Historically, this was + * implemented by using `ref()` and `unref()` methods directly on the objects. + * This pattern, however, is being deprecated in favor of the "Refable protocol" + * in order to better support Web Platform API types whose APIs cannot be modified + * to add `ref()` and `unref()` methods but still need to support that behavior. + * @since v22.14.0 + * @experimental + * @param maybeRefable An object that may be "refable". + */ + ref(maybeRefable: any): void; + /** + * An object is "unrefable" if it implements the Node.js "Refable protocol". + * Specifically, this means that the object implements the `Symbol.for('nodejs.ref')` + * and `Symbol.for('nodejs.unref')` methods. "Ref'd" objects will keep the Node.js + * event loop alive, while "unref'd" objects will not. Historically, this was + * implemented by using `ref()` and `unref()` methods directly on the objects. + * This pattern, however, is being deprecated in favor of the "Refable protocol" + * in order to better support Web Platform API types whose APIs cannot be modified + * to add `ref()` and `unref()` methods but still need to support that behavior. + * @since v22.14.0 + * @experimental + * @param maybeRefable An object that may be "unref'd". + */ + unref(maybeRefable: any): void; + /** + * Replaces the current process with a new process. + * + * This is achieved by using the `execve` POSIX function and therefore no memory or other + * resources from the current process are preserved, except for the standard input, + * standard output and standard error file descriptor. + * + * All other resources are discarded by the system when the processes are swapped, without triggering + * any exit or close events and without running any cleanup handler. + * + * This function will never return, unless an error occurred. + * + * This function is not available on Windows or IBM i. + * @since v22.15.0 + * @experimental + * @param file The name or path of the executable file to run. + * @param args List of string arguments. No argument can contain a null-byte (`\u0000`). + * @param env Environment key-value pairs. + * No key or value can contain a null-byte (`\u0000`). + * **Default:** `process.env`. + */ + execve?(file: string, args?: readonly string[], env?: ProcessEnv): never; + } + } + } + export = process; +} +declare module "process" { + import process = require("node:process"); + export = process; +} diff --git a/backend/node_modules/@types/node/punycode.d.ts b/backend/node_modules/@types/node/punycode.d.ts new file mode 100644 index 0000000..d293553 --- /dev/null +++ b/backend/node_modules/@types/node/punycode.d.ts @@ -0,0 +1,117 @@ +/** + * **The version of the punycode module bundled in Node.js is being deprecated. **In a future major version of Node.js this module will be removed. Users + * currently depending on the `punycode` module should switch to using the + * userland-provided [Punycode.js](https://github.com/bestiejs/punycode.js) module instead. For punycode-based URL + * encoding, see `url.domainToASCII` or, more generally, the `WHATWG URL API`. + * + * The `punycode` module is a bundled version of the [Punycode.js](https://github.com/bestiejs/punycode.js) module. It + * can be accessed using: + * + * ```js + * import punycode from 'node:punycode'; + * ``` + * + * [Punycode](https://tools.ietf.org/html/rfc3492) is a character encoding scheme defined by RFC 3492 that is + * primarily intended for use in Internationalized Domain Names. Because host + * names in URLs are limited to ASCII characters only, Domain Names that contain + * non-ASCII characters must be converted into ASCII using the Punycode scheme. + * For instance, the Japanese character that translates into the English word, `'example'` is `'例'`. The Internationalized Domain Name, `'例.com'` (equivalent + * to `'example.com'`) is represented by Punycode as the ASCII string `'xn--fsq.com'`. + * + * The `punycode` module provides a simple implementation of the Punycode standard. + * + * The `punycode` module is a third-party dependency used by Node.js and + * made available to developers as a convenience. Fixes or other modifications to + * the module must be directed to the [Punycode.js](https://github.com/bestiejs/punycode.js) project. + * @deprecated + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/punycode.js) + */ +declare module "node:punycode" { + /** + * The `punycode.decode()` method converts a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only + * characters to the equivalent string of Unicode codepoints. + * + * ```js + * punycode.decode('maana-pta'); // 'mañana' + * punycode.decode('--dqo34k'); // '☃-⌘' + * ``` + * @since v0.5.1 + */ + function decode(string: string): string; + /** + * The `punycode.encode()` method converts a string of Unicode codepoints to a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only characters. + * + * ```js + * punycode.encode('mañana'); // 'maana-pta' + * punycode.encode('☃-⌘'); // '--dqo34k' + * ``` + * @since v0.5.1 + */ + function encode(string: string): string; + /** + * The `punycode.toUnicode()` method converts a string representing a domain name + * containing [Punycode](https://tools.ietf.org/html/rfc3492) encoded characters into Unicode. Only the [Punycode](https://tools.ietf.org/html/rfc3492) encoded parts of the domain name are be + * converted. + * + * ```js + * // decode domain names + * punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com' + * punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com' + * punycode.toUnicode('example.com'); // 'example.com' + * ``` + * @since v0.6.1 + */ + function toUnicode(domain: string): string; + /** + * The `punycode.toASCII()` method converts a Unicode string representing an + * Internationalized Domain Name to [Punycode](https://tools.ietf.org/html/rfc3492). Only the non-ASCII parts of the + * domain name will be converted. Calling `punycode.toASCII()` on a string that + * already only contains ASCII characters will have no effect. + * + * ```js + * // encode domain names + * punycode.toASCII('mañana.com'); // 'xn--maana-pta.com' + * punycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com' + * punycode.toASCII('example.com'); // 'example.com' + * ``` + * @since v0.6.1 + */ + function toASCII(domain: string): string; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const ucs2: ucs2; + interface ucs2 { + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + decode(string: string): number[]; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + encode(codePoints: readonly number[]): string; + } + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const version: string; +} +declare module "punycode" { + export * from "node:punycode"; +} diff --git a/backend/node_modules/@types/node/querystring.d.ts b/backend/node_modules/@types/node/querystring.d.ts new file mode 100644 index 0000000..dc421bc --- /dev/null +++ b/backend/node_modules/@types/node/querystring.d.ts @@ -0,0 +1,152 @@ +/** + * The `node:querystring` module provides utilities for parsing and formatting URL + * query strings. It can be accessed using: + * + * ```js + * import querystring from 'node:querystring'; + * ``` + * + * `querystring` is more performant than `URLSearchParams` but is not a + * standardized API. Use `URLSearchParams` when performance is not critical or + * when compatibility with browser code is desirable. + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/querystring.js) + */ +declare module "node:querystring" { + interface StringifyOptions { + /** + * The function to use when converting URL-unsafe characters to percent-encoding in the query string. + * @default `querystring.escape()` + */ + encodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParseOptions { + /** + * Specifies the maximum number of keys to parse. Specify `0` to remove key counting limitations. + * @default 1000 + */ + maxKeys?: number | undefined; + /** + * The function to use when decoding percent-encoded characters in the query string. + * @default `querystring.unescape()` + */ + decodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParsedUrlQuery extends NodeJS.Dict {} + interface ParsedUrlQueryInput extends + NodeJS.Dict< + | string + | number + | boolean + | bigint + | ReadonlyArray + | null + > + {} + /** + * The `querystring.stringify()` method produces a URL query string from a + * given `obj` by iterating through the object's "own properties". + * + * It serializes the following types of values passed in `obj`: [string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | + * [string\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [number\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [bigint\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [boolean\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The numeric values must be finite. Any other input values will be coerced to + * empty strings. + * + * ```js + * querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' }); + * // Returns 'foo=bar&baz=qux&baz=quux&corge=' + * + * querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':'); + * // Returns 'foo:bar;baz:qux' + * ``` + * + * By default, characters requiring percent-encoding within the query string will + * be encoded as UTF-8\. If an alternative encoding is required, then an alternative `encodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkEncodeURIComponent function already exists, + * + * querystring.stringify({ w: '中文', foo: 'bar' }, null, null, + * { encodeURIComponent: gbkEncodeURIComponent }); + * ``` + * @since v0.1.25 + * @param obj The object to serialize into a URL query string + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] . The substring used to delimit keys and values in the query string. + */ + function stringify(obj?: ParsedUrlQueryInput, sep?: string, eq?: string, options?: StringifyOptions): string; + /** + * The `querystring.parse()` method parses a URL query string (`str`) into a + * collection of key and value pairs. + * + * For example, the query string `'foo=bar&abc=xyz&abc=123'` is parsed into: + * + * ```json + * { + * "foo": "bar", + * "abc": ["xyz", "123"] + * } + * ``` + * + * The object returned by the `querystring.parse()` method _does not_ prototypically inherit from the JavaScript `Object`. This means that typical `Object` methods such as `obj.toString()`, + * `obj.hasOwnProperty()`, and others + * are not defined and _will not work_. + * + * By default, percent-encoded characters within the query string will be assumed + * to use UTF-8 encoding. If an alternative character encoding is used, then an + * alternative `decodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkDecodeURIComponent function already exists... + * + * querystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null, + * { decodeURIComponent: gbkDecodeURIComponent }); + * ``` + * @since v0.1.25 + * @param str The URL query string to parse + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] The substring used to delimit keys and values in the query string. + */ + function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery; + /** + * The querystring.encode() function is an alias for querystring.stringify(). + */ + const encode: typeof stringify; + /** + * The querystring.decode() function is an alias for querystring.parse(). + */ + const decode: typeof parse; + /** + * The `querystring.escape()` method performs URL percent-encoding on the given `str` in a manner that is optimized for the specific requirements of URL + * query strings. + * + * The `querystring.escape()` method is used by `querystring.stringify()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement percent-encoding implementation if + * necessary by assigning `querystring.escape` to an alternative function. + * @since v0.1.25 + */ + function escape(str: string): string; + /** + * The `querystring.unescape()` method performs decoding of URL percent-encoded + * characters on the given `str`. + * + * The `querystring.unescape()` method is used by `querystring.parse()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement decoding implementation if + * necessary by assigning `querystring.unescape` to an alternative function. + * + * By default, the `querystring.unescape()` method will attempt to use the + * JavaScript built-in `decodeURIComponent()` method to decode. If that fails, + * a safer equivalent that does not throw on malformed URLs will be used. + * @since v0.1.25 + */ + function unescape(str: string): string; +} +declare module "querystring" { + export * from "node:querystring"; +} diff --git a/backend/node_modules/@types/node/quic.d.ts b/backend/node_modules/@types/node/quic.d.ts new file mode 100644 index 0000000..9a6fd97 --- /dev/null +++ b/backend/node_modules/@types/node/quic.d.ts @@ -0,0 +1,910 @@ +/** + * The 'node:quic' module provides an implementation of the QUIC protocol. + * To access it, start Node.js with the `--experimental-quic` option and: + * + * ```js + * import quic from 'node:quic'; + * ``` + * + * The module is only available under the `node:` scheme. + * @since v23.8.0 + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/quic.js) + */ +declare module "node:quic" { + import { KeyObject, webcrypto } from "node:crypto"; + import { SocketAddress } from "node:net"; + import { ReadableStream } from "node:stream/web"; + /** + * @since v23.8.0 + */ + type OnSessionCallback = (this: QuicEndpoint, session: QuicSession) => void; + /** + * @since v23.8.0 + */ + type OnStreamCallback = (this: QuicSession, stream: QuicStream) => void; + /** + * @since v23.8.0 + */ + type OnDatagramCallback = (this: QuicSession, datagram: Uint8Array, early: boolean) => void; + /** + * @since v23.8.0 + */ + type OnDatagramStatusCallback = (this: QuicSession, id: bigint, status: "lost" | "acknowledged") => void; + /** + * @since v23.8.0 + */ + type OnPathValidationCallback = ( + this: QuicSession, + result: "success" | "failure" | "aborted", + newLocalAddress: SocketAddress, + newRemoteAddress: SocketAddress, + oldLocalAddress: SocketAddress, + oldRemoteAddress: SocketAddress, + preferredAddress: boolean, + ) => void; + /** + * @since v23.8.0 + */ + type OnSessionTicketCallback = (this: QuicSession, ticket: object) => void; + /** + * @since v23.8.0 + */ + type OnVersionNegotiationCallback = ( + this: QuicSession, + version: number, + requestedVersions: number[], + supportedVersions: number[], + ) => void; + /** + * @since v23.8.0 + */ + type OnHandshakeCallback = ( + this: QuicSession, + sni: string, + alpn: string, + cipher: string, + cipherVersion: string, + validationErrorReason: string, + validationErrorCode: number, + earlyDataAccepted: boolean, + ) => void; + /** + * @since v23.8.0 + */ + type OnBlockedCallback = (this: QuicStream) => void; + /** + * @since v23.8.0 + */ + type OnStreamErrorCallback = (this: QuicStream, error: any) => void; + /** + * @since v23.8.0 + */ + interface TransportParams { + /** + * The preferred IPv4 address to advertise. + * @since v23.8.0 + */ + preferredAddressIpv4?: SocketAddress | undefined; + /** + * The preferred IPv6 address to advertise. + * @since v23.8.0 + */ + preferredAddressIpv6?: SocketAddress | undefined; + /** + * @since v23.8.0 + */ + initialMaxStreamDataBidiLocal?: bigint | number | undefined; + /** + * @since v23.8.0 + */ + initialMaxStreamDataBidiRemote?: bigint | number | undefined; + /** + * @since v23.8.0 + */ + initialMaxStreamDataUni?: bigint | number | undefined; + /** + * @since v23.8.0 + */ + initialMaxData?: bigint | number | undefined; + /** + * @since v23.8.0 + */ + initialMaxStreamsBidi?: bigint | number | undefined; + /** + * @since v23.8.0 + */ + initialMaxStreamsUni?: bigint | number | undefined; + /** + * @since v23.8.0 + */ + maxIdleTimeout?: bigint | number | undefined; + /** + * @since v23.8.0 + */ + activeConnectionIDLimit?: bigint | number | undefined; + /** + * @since v23.8.0 + */ + ackDelayExponent?: bigint | number | undefined; + /** + * @since v23.8.0 + */ + maxAckDelay?: bigint | number | undefined; + /** + * @since v23.8.0 + */ + maxDatagramFrameSize?: bigint | number | undefined; + } + /** + * @since v23.8.0 + */ + interface SessionOptions { + /** + * An endpoint to use. + * @since v23.8.0 + */ + endpoint?: EndpointOptions | QuicEndpoint | undefined; + /** + * The ALPN protocol identifier. + * @since v23.8.0 + */ + alpn?: string | undefined; + /** + * The CA certificates to use for sessions. + * @since v23.8.0 + */ + ca?: ArrayBuffer | NodeJS.ArrayBufferView | ReadonlyArray | undefined; + /** + * Specifies the congestion control algorithm that will be used. + * Must be set to one of either `'reno'`, `'cubic'`, or `'bbr'`. + * + * This is an advanced option that users typically won't have need to specify. + * @since v23.8.0 + */ + cc?: `${constants.cc}` | undefined; + /** + * The TLS certificates to use for sessions. + * @since v23.8.0 + */ + certs?: ArrayBuffer | NodeJS.ArrayBufferView | ReadonlyArray | undefined; + /** + * The list of supported TLS 1.3 cipher algorithms. + * @since v23.8.0 + */ + ciphers?: string | undefined; + /** + * The CRL to use for sessions. + * @since v23.8.0 + */ + crl?: ArrayBuffer | NodeJS.ArrayBufferView | ReadonlyArray | undefined; + /** + * The list of support TLS 1.3 cipher groups. + * @since v23.8.0 + */ + groups?: string | undefined; + /** + * True to enable TLS keylogging output. + * @since v23.8.0 + */ + keylog?: boolean | undefined; + /** + * The TLS crypto keys to use for sessions. + * @since v23.8.0 + */ + keys?: KeyObject | webcrypto.CryptoKey | ReadonlyArray | undefined; + /** + * Specifies the maximum UDP packet payload size. + * @since v23.8.0 + */ + maxPayloadSize?: bigint | number | undefined; + /** + * Specifies the maximum stream flow-control window size. + * @since v23.8.0 + */ + maxStreamWindow?: bigint | number | undefined; + /** + * Specifies the maximum session flow-control window size. + * @since v23.8.0 + */ + maxWindow?: bigint | number | undefined; + /** + * The minimum QUIC version number to allow. This is an advanced option that users + * typically won't have need to specify. + * @since v23.8.0 + */ + minVersion?: number | undefined; + /** + * When the remote peer advertises a preferred address, this option specifies whether + * to use it or ignore it. + * @since v23.8.0 + */ + preferredAddressPolicy?: "use" | "ignore" | "default" | undefined; + /** + * True if qlog output should be enabled. + * @since v23.8.0 + */ + qlog?: boolean | undefined; + /** + * A session ticket to use for 0RTT session resumption. + * @since v23.8.0 + */ + sessionTicket?: NodeJS.ArrayBufferView | undefined; + /** + * Specifies the maximum number of milliseconds a TLS handshake is permitted to take + * to complete before timing out. + * @since v23.8.0 + */ + handshakeTimeout?: bigint | number | undefined; + /** + * The peer server name to target. + * @since v23.8.0 + */ + sni?: string | undefined; + /** + * True to enable TLS tracing output. + * @since v23.8.0 + */ + tlsTrace?: boolean | undefined; + /** + * The QUIC transport parameters to use for the session. + * @since v23.8.0 + */ + transportParams?: TransportParams | undefined; + /** + * Specifies the maximum number of unacknowledged packets a session should allow. + * @since v23.8.0 + */ + unacknowledgedPacketThreshold?: bigint | number | undefined; + /** + * True to require verification of TLS client certificate. + * @since v23.8.0 + */ + verifyClient?: boolean | undefined; + /** + * True to require private key verification. + * @since v23.8.0 + */ + verifyPrivateKey?: boolean | undefined; + /** + * The QUIC version number to use. This is an advanced option that users typically + * won't have need to specify. + * @since v23.8.0 + */ + version?: number | undefined; + } + /** + * Initiate a new client-side session. + * + * ```js + * import { connect } from 'node:quic'; + * import { Buffer } from 'node:buffer'; + * + * const enc = new TextEncoder(); + * const alpn = 'foo'; + * const client = await connect('123.123.123.123:8888', { alpn }); + * await client.createUnidirectionalStream({ + * body: enc.encode('hello world'), + * }); + * ``` + * + * By default, every call to `connect(...)` will create a new local + * `QuicEndpoint` instance bound to a new random local IP port. To + * specify the exact local address to use, or to multiplex multiple + * QUIC sessions over a single local port, pass the `endpoint` option + * with either a `QuicEndpoint` or `EndpointOptions` as the argument. + * + * ```js + * import { QuicEndpoint, connect } from 'node:quic'; + * + * const endpoint = new QuicEndpoint({ + * address: '127.0.0.1:1234', + * }); + * + * const client = await connect('123.123.123.123:8888', { endpoint }); + * ``` + * @since v23.8.0 + */ + function connect(address: string | SocketAddress, options?: SessionOptions): Promise; + /** + * Configures the endpoint to listen as a server. When a new session is initiated by + * a remote peer, the given `onsession` callback will be invoked with the created + * session. + * + * ```js + * import { listen } from 'node:quic'; + * + * const endpoint = await listen((session) => { + * // ... handle the session + * }); + * + * // Closing the endpoint allows any sessions open when close is called + * // to complete naturally while preventing new sessions from being + * // initiated. Once all existing sessions have finished, the endpoint + * // will be destroyed. The call returns a promise that is resolved once + * // the endpoint is destroyed. + * await endpoint.close(); + * ``` + * + * By default, every call to `listen(...)` will create a new local + * `QuicEndpoint` instance bound to a new random local IP port. To + * specify the exact local address to use, or to multiplex multiple + * QUIC sessions over a single local port, pass the `endpoint` option + * with either a `QuicEndpoint` or `EndpointOptions` as the argument. + * + * At most, any single `QuicEndpoint` can only be configured to listen as + * a server once. + * @since v23.8.0 + */ + function listen(onsession: OnSessionCallback, options?: SessionOptions): Promise; + /** + * The endpoint configuration options passed when constructing a new `QuicEndpoint` instance. + * @since v23.8.0 + */ + interface EndpointOptions { + /** + * If not specified the endpoint will bind to IPv4 `localhost` on a random port. + * @since v23.8.0 + */ + address?: SocketAddress | string | undefined; + /** + * The endpoint maintains an internal cache of validated socket addresses as a + * performance optimization. This option sets the maximum number of addresses + * that are cache. This is an advanced option that users typically won't have + * need to specify. + * @since v23.8.0 + */ + addressLRUSize?: bigint | number | undefined; + /** + * When `true`, indicates that the endpoint should bind only to IPv6 addresses. + * @since v23.8.0 + */ + ipv6Only?: boolean | undefined; + /** + * Specifies the maximum number of concurrent sessions allowed per remote peer address. + * @since v23.8.0 + */ + maxConnectionsPerHost?: bigint | number | undefined; + /** + * Specifies the maximum total number of concurrent sessions. + * @since v23.8.0 + */ + maxConnectionsTotal?: bigint | number | undefined; + /** + * Specifies the maximum number of QUIC retry attempts allowed per remote peer address. + * @since v23.8.0 + */ + maxRetries?: bigint | number | undefined; + /** + * Specifies the maximum number of stateless resets that are allowed per remote peer address. + * @since v23.8.0 + */ + maxStatelessResetsPerHost?: bigint | number | undefined; + /** + * Specifies the length of time a QUIC retry token is considered valid. + * @since v23.8.0 + */ + retryTokenExpiration?: bigint | number | undefined; + /** + * Specifies the 16-byte secret used to generate QUIC retry tokens. + * @since v23.8.0 + */ + resetTokenSecret?: NodeJS.ArrayBufferView | undefined; + /** + * Specifies the length of time a QUIC token is considered valid. + * @since v23.8.0 + */ + tokenExpiration?: bigint | number | undefined; + /** + * Specifies the 16-byte secret used to generate QUIC tokens. + * @since v23.8.0 + */ + tokenSecret?: NodeJS.ArrayBufferView | undefined; + /** + * @since v23.8.0 + */ + udpReceiveBufferSize?: number | undefined; + /** + * @since v23.8.0 + */ + udpSendBufferSize?: number | undefined; + /** + * @since v23.8.0 + */ + udpTTL?: number | undefined; + /** + * When `true`, requires that the endpoint validate peer addresses using retry packets + * while establishing a new connection. + * @since v23.8.0 + */ + validateAddress?: boolean | undefined; + } + /** + * A `QuicEndpoint` encapsulates the local UDP-port binding for QUIC. It can be + * used as both a client and a server. + * @since v23.8.0 + */ + class QuicEndpoint implements AsyncDisposable { + constructor(options?: EndpointOptions); + /** + * The local UDP socket address to which the endpoint is bound, if any. + * + * If the endpoint is not currently bound then the value will be `undefined`. Read only. + * @since v23.8.0 + */ + readonly address: SocketAddress | undefined; + /** + * When `endpoint.busy` is set to true, the endpoint will temporarily reject + * new sessions from being created. Read/write. + * + * ```js + * // Mark the endpoint busy. New sessions will be prevented. + * endpoint.busy = true; + * + * // Mark the endpoint free. New session will be allowed. + * endpoint.busy = false; + * ``` + * + * The `busy` property is useful when the endpoint is under heavy load and needs to + * temporarily reject new sessions while it catches up. + * @since v23.8.0 + */ + busy: boolean; + /** + * Gracefully close the endpoint. The endpoint will close and destroy itself when + * all currently open sessions close. Once called, new sessions will be rejected. + * + * Returns a promise that is fulfilled when the endpoint is destroyed. + * @since v23.8.0 + */ + close(): Promise; + /** + * A promise that is fulfilled when the endpoint is destroyed. This will be the same promise that is + * returned by the `endpoint.close()` function. Read only. + * @since v23.8.0 + */ + readonly closed: Promise; + /** + * True if `endpoint.close()` has been called and closing the endpoint has not yet completed. + * Read only. + * @since v23.8.0 + */ + readonly closing: boolean; + /** + * Forcefully closes the endpoint by forcing all open sessions to be immediately + * closed. + * @since v23.8.0 + */ + destroy(error?: any): void; + /** + * True if `endpoint.destroy()` has been called. Read only. + * @since v23.8.0 + */ + readonly destroyed: boolean; + /** + * The statistics collected for an active session. Read only. + * @since v23.8.0 + */ + readonly stats: QuicEndpoint.Stats; + /** + * Calls `endpoint.close()` and returns a promise that fulfills when the + * endpoint has closed. + * @since v23.8.0 + */ + [Symbol.asyncDispose](): Promise; + } + namespace QuicEndpoint { + /** + * A view of the collected statistics for an endpoint. + * @since v23.8.0 + */ + class Stats { + private constructor(); + /** + * A timestamp indicating the moment the endpoint was created. Read only. + * @since v23.8.0 + */ + readonly createdAt: bigint; + /** + * A timestamp indicating the moment the endpoint was destroyed. Read only. + * @since v23.8.0 + */ + readonly destroyedAt: bigint; + /** + * The total number of bytes received by this endpoint. Read only. + * @since v23.8.0 + */ + readonly bytesReceived: bigint; + /** + * The total number of bytes sent by this endpoint. Read only. + * @since v23.8.0 + */ + readonly bytesSent: bigint; + /** + * The total number of QUIC packets successfully received by this endpoint. Read only. + * @since v23.8.0 + */ + readonly packetsReceived: bigint; + /** + * The total number of QUIC packets successfully sent by this endpoint. Read only. + * @since v23.8.0 + */ + readonly packetsSent: bigint; + /** + * The total number of peer-initiated sessions received by this endpoint. Read only. + * @since v23.8.0 + */ + readonly serverSessions: bigint; + /** + * The total number of sessions initiated by this endpoint. Read only. + * @since v23.8.0 + */ + readonly clientSessions: bigint; + /** + * The total number of times an initial packet was rejected due to the + * endpoint being marked busy. Read only. + * @since v23.8.0 + */ + readonly serverBusyCount: bigint; + /** + * The total number of QUIC retry attempts on this endpoint. Read only. + * @since v23.8.0 + */ + readonly retryCount: bigint; + /** + * The total number sessions rejected due to QUIC version mismatch. Read only. + * @since v23.8.0 + */ + readonly versionNegotiationCount: bigint; + /** + * The total number of stateless resets handled by this endpoint. Read only. + * @since v23.8.0 + */ + readonly statelessResetCount: bigint; + /** + * The total number of sessions that were closed before handshake completed. Read only. + * @since v23.8.0 + */ + readonly immediateCloseCount: bigint; + } + } + interface CreateStreamOptions { + body?: ArrayBuffer | NodeJS.ArrayBufferView | Blob | undefined; + sendOrder?: number | undefined; + } + interface SessionPath { + local: SocketAddress; + remote: SocketAddress; + } + /** + * A `QuicSession` represents the local side of a QUIC connection. + * @since v23.8.0 + */ + class QuicSession implements AsyncDisposable { + private constructor(); + /** + * Initiate a graceful close of the session. Existing streams will be allowed + * to complete but no new streams will be opened. Once all streams have closed, + * the session will be destroyed. The returned promise will be fulfilled once + * the session has been destroyed. + * @since v23.8.0 + */ + close(): Promise; + /** + * A promise that is fulfilled once the session is destroyed. + * @since v23.8.0 + */ + readonly closed: Promise; + /** + * Immediately destroy the session. All streams will be destroys and the + * session will be closed. + * @since v23.8.0 + */ + destroy(error?: any): void; + /** + * True if `session.destroy()` has been called. Read only. + * @since v23.8.0 + */ + readonly destroyed: boolean; + /** + * The endpoint that created this session. Read only. + * @since v23.8.0 + */ + readonly endpoint: QuicEndpoint; + /** + * The callback to invoke when a new stream is initiated by a remote peer. Read/write. + * @since v23.8.0 + */ + onstream: OnStreamCallback | undefined; + /** + * The callback to invoke when a new datagram is received from a remote peer. Read/write. + * @since v23.8.0 + */ + ondatagram: OnDatagramCallback | undefined; + /** + * The callback to invoke when the status of a datagram is updated. Read/write. + * @since v23.8.0 + */ + ondatagramstatus: OnDatagramStatusCallback | undefined; + /** + * The callback to invoke when the path validation is updated. Read/write. + * @since v23.8.0 + */ + onpathvalidation: OnPathValidationCallback | undefined; + /** + * The callback to invoke when a new session ticket is received. Read/write. + * @since v23.8.0 + */ + onsessionticket: OnSessionTicketCallback | undefined; + /** + * The callback to invoke when a version negotiation is initiated. Read/write. + * @since v23.8.0 + */ + onversionnegotiation: OnVersionNegotiationCallback | undefined; + /** + * The callback to invoke when the TLS handshake is completed. Read/write. + * @since v23.8.0 + */ + onhandshake: OnHandshakeCallback | undefined; + /** + * Open a new bidirectional stream. If the `body` option is not specified, + * the outgoing stream will be half-closed. + * @since v23.8.0 + */ + createBidirectionalStream(options?: CreateStreamOptions): Promise; + /** + * Open a new unidirectional stream. If the `body` option is not specified, + * the outgoing stream will be closed. + * @since v23.8.0 + */ + createUnidirectionalStream(options?: CreateStreamOptions): Promise; + /** + * The local and remote socket addresses associated with the session. Read only. + * @since v23.8.0 + */ + path: SessionPath | undefined; + /** + * Sends an unreliable datagram to the remote peer, returning the datagram ID. + * If the datagram payload is specified as an `ArrayBufferView`, then ownership of + * that view will be transfered to the underlying stream. + * @since v23.8.0 + */ + sendDatagram(datagram: string | NodeJS.ArrayBufferView): bigint; + /** + * Return the current statistics for the session. Read only. + * @since v23.8.0 + */ + readonly stats: QuicSession.Stats; + /** + * Initiate a key update for the session. + * @since v23.8.0 + */ + updateKey(): void; + /** + * Calls `session.close()` and returns a promise that fulfills when the + * session has closed. + * @since v23.8.0 + */ + [Symbol.asyncDispose](): Promise; + } + namespace QuicSession { + /** + * @since v23.8.0 + */ + class Stats { + private constructor(); + /** + * @since v23.8.0 + */ + readonly createdAt: bigint; + /** + * @since v23.8.0 + */ + readonly closingAt: bigint; + /** + * @since v23.8.0 + */ + readonly handshakeCompletedAt: bigint; + /** + * @since v23.8.0 + */ + readonly handshakeConfirmedAt: bigint; + /** + * @since v23.8.0 + */ + readonly bytesReceived: bigint; + /** + * @since v23.8.0 + */ + readonly bytesSent: bigint; + /** + * @since v23.8.0 + */ + readonly bidiInStreamCount: bigint; + /** + * @since v23.8.0 + */ + readonly bidiOutStreamCount: bigint; + /** + * @since v23.8.0 + */ + readonly uniInStreamCount: bigint; + /** + * @since v23.8.0 + */ + readonly uniOutStreamCount: bigint; + /** + * @since v23.8.0 + */ + readonly maxBytesInFlights: bigint; + /** + * @since v23.8.0 + */ + readonly bytesInFlight: bigint; + /** + * @since v23.8.0 + */ + readonly blockCount: bigint; + /** + * @since v23.8.0 + */ + readonly cwnd: bigint; + /** + * @since v23.8.0 + */ + readonly latestRtt: bigint; + /** + * @since v23.8.0 + */ + readonly minRtt: bigint; + /** + * @since v23.8.0 + */ + readonly rttVar: bigint; + /** + * @since v23.8.0 + */ + readonly smoothedRtt: bigint; + /** + * @since v23.8.0 + */ + readonly ssthresh: bigint; + /** + * @since v23.8.0 + */ + readonly datagramsReceived: bigint; + /** + * @since v23.8.0 + */ + readonly datagramsSent: bigint; + /** + * @since v23.8.0 + */ + readonly datagramsAcknowledged: bigint; + /** + * @since v23.8.0 + */ + readonly datagramsLost: bigint; + } + } + /** + * @since v23.8.0 + */ + class QuicStream { + private constructor(); + /** + * A promise that is fulfilled when the stream is fully closed. + * @since v23.8.0 + */ + readonly closed: Promise; + /** + * Immediately and abruptly destroys the stream. + * @since v23.8.0 + */ + destroy(error?: any): void; + /** + * True if `stream.destroy()` has been called. + * @since v23.8.0 + */ + readonly destroyed: boolean; + /** + * The directionality of the stream. Read only. + * @since v23.8.0 + */ + readonly direction: "bidi" | "uni"; + /** + * The stream ID. Read only. + * @since v23.8.0 + */ + readonly id: bigint; + /** + * The callback to invoke when the stream is blocked. Read/write. + * @since v23.8.0 + */ + onblocked: OnBlockedCallback | undefined; + /** + * The callback to invoke when the stream is reset. Read/write. + * @since v23.8.0 + */ + onreset: OnStreamErrorCallback | undefined; + /** + * @since v23.8.0 + */ + readonly readable: ReadableStream; + /** + * The session that created this stream. Read only. + * @since v23.8.0 + */ + readonly session: QuicSession; + /** + * The current statistics for the stream. Read only. + * @since v23.8.0 + */ + readonly stats: QuicStream.Stats; + } + namespace QuicStream { + /** + * @since v23.8.0 + */ + class Stats { + private constructor(); + /** + * @since v23.8.0 + */ + readonly ackedAt: bigint; + /** + * @since v23.8.0 + */ + readonly bytesReceived: bigint; + /** + * @since v23.8.0 + */ + readonly bytesSent: bigint; + /** + * @since v23.8.0 + */ + readonly createdAt: bigint; + /** + * @since v23.8.0 + */ + readonly destroyedAt: bigint; + /** + * @since v23.8.0 + */ + readonly finalSize: bigint; + /** + * @since v23.8.0 + */ + readonly isConnected: bigint; + /** + * @since v23.8.0 + */ + readonly maxOffset: bigint; + /** + * @since v23.8.0 + */ + readonly maxOffsetAcknowledged: bigint; + /** + * @since v23.8.0 + */ + readonly maxOffsetReceived: bigint; + /** + * @since v23.8.0 + */ + readonly openedAt: bigint; + /** + * @since v23.8.0 + */ + readonly receivedAt: bigint; + } + } + namespace constants { + enum cc { + RENO = "reno", + CUBIC = "cubic", + BBR = "bbr", + } + const DEFAULT_CIPHERS: string; + const DEFAULT_GROUPS: string; + } +} diff --git a/backend/node_modules/@types/node/readline.d.ts b/backend/node_modules/@types/node/readline.d.ts new file mode 100644 index 0000000..a47e185 --- /dev/null +++ b/backend/node_modules/@types/node/readline.d.ts @@ -0,0 +1,541 @@ +/** + * The `node:readline` module provides an interface for reading data from a [Readable](https://nodejs.org/docs/latest-v25.x/api/stream.html#readable-streams) stream + * (such as [`process.stdin`](https://nodejs.org/docs/latest-v25.x/api/process.html#processstdin)) one line at a time. + * + * To use the promise-based APIs: + * + * ```js + * import * as readline from 'node:readline/promises'; + * ``` + * + * To use the callback and sync APIs: + * + * ```js + * import * as readline from 'node:readline'; + * ``` + * + * The following simple example illustrates the basic use of the `node:readline` module. + * + * ```js + * import * as readline from 'node:readline/promises'; + * import { stdin as input, stdout as output } from 'node:process'; + * + * const rl = readline.createInterface({ input, output }); + * + * const answer = await rl.question('What do you think of Node.js? '); + * + * console.log(`Thank you for your valuable feedback: ${answer}`); + * + * rl.close(); + * ``` + * + * Once this code is invoked, the Node.js application will not terminate until the `readline.Interface` is closed because the interface waits for data to be + * received on the `input` stream. + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/readline.js) + */ +declare module "node:readline" { + import { Abortable, EventEmitter, InternalEventEmitter } from "node:events"; + interface Key { + sequence?: string | undefined; + name?: string | undefined; + ctrl?: boolean | undefined; + meta?: boolean | undefined; + shift?: boolean | undefined; + } + interface InterfaceEventMap { + "close": []; + "history": [history: string[]]; + "line": [input: string]; + "pause": []; + "resume": []; + "SIGCONT": []; + "SIGINT": []; + "SIGTSTP": []; + } + /** + * Instances of the `readline.Interface` class are constructed using the `readline.createInterface()` method. Every instance is associated with a + * single `input` [Readable](https://nodejs.org/docs/latest-v25.x/api/stream.html#readable-streams) stream and a single `output` [Writable](https://nodejs.org/docs/latest-v25.x/api/stream.html#writable-streams) stream. + * The `output` stream is used to print prompts for user input that arrives on, + * and is read from, the `input` stream. + * @since v0.1.104 + */ + class Interface implements EventEmitter, Disposable { + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v25.x/docs/api/readline.html#class-interfaceconstructor + */ + protected constructor( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer | AsyncCompleter, + terminal?: boolean, + ); + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v25.x/docs/api/readline.html#class-interfaceconstructor + */ + protected constructor(options: ReadLineOptions); + readonly terminal: boolean; + /** + * The current input data being processed by node. + * + * This can be used when collecting input from a TTY stream to retrieve the + * current value that has been processed thus far, prior to the `line` event + * being emitted. Once the `line` event has been emitted, this property will + * be an empty string. + * + * Be aware that modifying the value during the instance runtime may have + * unintended consequences if `rl.cursor` is not also controlled. + * + * **If not using a TTY stream for input, use the `'line'` event.** + * + * One possible use case would be as follows: + * + * ```js + * const values = ['lorem ipsum', 'dolor sit amet']; + * const rl = readline.createInterface(process.stdin); + * const showResults = debounce(() => { + * console.log( + * '\n', + * values.filter((val) => val.startsWith(rl.line)).join(' '), + * ); + * }, 300); + * process.stdin.on('keypress', (c, k) => { + * showResults(); + * }); + * ``` + * @since v0.1.98 + */ + readonly line: string; + /** + * The cursor position relative to `rl.line`. + * + * This will track where the current cursor lands in the input string, when + * reading input from a TTY stream. The position of cursor determines the + * portion of the input string that will be modified as input is processed, + * as well as the column where the terminal caret will be rendered. + * @since v0.1.98 + */ + readonly cursor: number; + /** + * The `rl.getPrompt()` method returns the current prompt used by `rl.prompt()`. + * @since v15.3.0, v14.17.0 + * @return the current prompt string + */ + getPrompt(): string; + /** + * The `rl.setPrompt()` method sets the prompt that will be written to `output` whenever `rl.prompt()` is called. + * @since v0.1.98 + */ + setPrompt(prompt: string): void; + /** + * The `rl.prompt()` method writes the `Interface` instances configured`prompt` to a new line in `output` in order to provide a user with a new + * location at which to provide input. + * + * When called, `rl.prompt()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the prompt is not written. + * @since v0.1.98 + * @param preserveCursor If `true`, prevents the cursor placement from being reset to `0`. + */ + prompt(preserveCursor?: boolean): void; + /** + * The `rl.question()` method displays the `query` by writing it to the `output`, + * waits for user input to be provided on `input`, then invokes the `callback` function passing the provided input as the first argument. + * + * When called, `rl.question()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the `query` is not written. + * + * The `callback` function passed to `rl.question()` does not follow the typical + * pattern of accepting an `Error` object or `null` as the first argument. + * The `callback` is called with the provided answer as the only argument. + * + * An error will be thrown if calling `rl.question()` after `rl.close()`. + * + * Example usage: + * + * ```js + * rl.question('What is your favorite food? ', (answer) => { + * console.log(`Oh, so your favorite food is ${answer}`); + * }); + * ``` + * + * Using an `AbortController` to cancel a question. + * + * ```js + * const ac = new AbortController(); + * const signal = ac.signal; + * + * rl.question('What is your favorite food? ', { signal }, (answer) => { + * console.log(`Oh, so your favorite food is ${answer}`); + * }); + * + * signal.addEventListener('abort', () => { + * console.log('The food question timed out'); + * }, { once: true }); + * + * setTimeout(() => ac.abort(), 10000); + * ``` + * @since v0.3.3 + * @param query A statement or query to write to `output`, prepended to the prompt. + * @param callback A callback function that is invoked with the user's input in response to the `query`. + */ + question(query: string, callback: (answer: string) => void): void; + question(query: string, options: Abortable, callback: (answer: string) => void): void; + /** + * The `rl.pause()` method pauses the `input` stream, allowing it to be resumed + * later if necessary. + * + * Calling `rl.pause()` does not immediately pause other events (including `'line'`) from being emitted by the `Interface` instance. + * @since v0.3.4 + */ + pause(): this; + /** + * The `rl.resume()` method resumes the `input` stream if it has been paused. + * @since v0.3.4 + */ + resume(): this; + /** + * The `rl.close()` method closes the `Interface` instance and + * relinquishes control over the `input` and `output` streams. When called, + * the `'close'` event will be emitted. + * + * Calling `rl.close()` does not immediately stop other events (including `'line'`) + * from being emitted by the `Interface` instance. + * @since v0.1.98 + */ + close(): void; + /** + * Alias for `rl.close()`. + * @since v22.15.0 + */ + [Symbol.dispose](): void; + /** + * The `rl.write()` method will write either `data` or a key sequence identified + * by `key` to the `output`. The `key` argument is supported only if `output` is + * a `TTY` text terminal. See `TTY keybindings` for a list of key + * combinations. + * + * If `key` is specified, `data` is ignored. + * + * When called, `rl.write()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the `data` and `key` are not written. + * + * ```js + * rl.write('Delete this!'); + * // Simulate Ctrl+U to delete the line written previously + * rl.write(null, { ctrl: true, name: 'u' }); + * ``` + * + * The `rl.write()` method will write the data to the `readline` `Interface`'s `input` _as if it were provided by the user_. + * @since v0.1.98 + */ + write(data: string | Buffer, key?: Key): void; + write(data: undefined | null | string | Buffer, key: Key): void; + /** + * Returns the real position of the cursor in relation to the input + * prompt + string. Long input (wrapping) strings, as well as multiple + * line prompts are included in the calculations. + * @since v13.5.0, v12.16.0 + */ + getCursorPos(): CursorPos; + [Symbol.asyncIterator](): NodeJS.AsyncIterator; + } + interface Interface extends InternalEventEmitter {} + type ReadLine = Interface; // type forwarded for backwards compatibility + type Completer = (line: string) => CompleterResult; + type AsyncCompleter = ( + line: string, + callback: (err?: null | Error, result?: CompleterResult) => void, + ) => void; + type CompleterResult = [string[], string]; + interface ReadLineOptions { + /** + * The [`Readable`](https://nodejs.org/docs/latest-v25.x/api/stream.html#readable-streams) stream to listen to + */ + input: NodeJS.ReadableStream; + /** + * The [`Writable`](https://nodejs.org/docs/latest-v25.x/api/stream.html#writable-streams) stream to write readline data to. + */ + output?: NodeJS.WritableStream | undefined; + /** + * An optional function used for Tab autocompletion. + */ + completer?: Completer | AsyncCompleter | undefined; + /** + * `true` if the `input` and `output` streams should be treated like a TTY, + * and have ANSI/VT100 escape codes written to it. + * Default: checking `isTTY` on the `output` stream upon instantiation. + */ + terminal?: boolean | undefined; + /** + * Initial list of history lines. + * This option makes sense only if `terminal` is set to `true` by the user or by an internal `output` check, + * otherwise the history caching mechanism is not initialized at all. + * @default [] + */ + history?: string[] | undefined; + /** + * Maximum number of history lines retained. + * To disable the history set this value to `0`. + * This option makes sense only if `terminal` is set to `true` by the user or by an internal `output` check, + * otherwise the history caching mechanism is not initialized at all. + * @default 30 + */ + historySize?: number | undefined; + /** + * If `true`, when a new input line added to the history list duplicates an older one, + * this removes the older line from the list. + * @default false + */ + removeHistoryDuplicates?: boolean | undefined; + /** + * The prompt string to use. + * @default "> " + */ + prompt?: string | undefined; + /** + * If the delay between `\r` and `\n` exceeds `crlfDelay` milliseconds, + * both `\r` and `\n` will be treated as separate end-of-line input. + * `crlfDelay` will be coerced to a number no less than `100`. + * It can be set to `Infinity`, in which case + * `\r` followed by `\n` will always be considered a single newline + * (which may be reasonable for [reading files](https://nodejs.org/docs/latest-v25.x/api/readline.html#example-read-file-stream-line-by-line) with `\r\n` line delimiter). + * @default 100 + */ + crlfDelay?: number | undefined; + /** + * The duration `readline` will wait for a character + * (when reading an ambiguous key sequence in milliseconds + * one that can both form a complete key sequence using the input read so far + * and can take additional input to complete a longer key sequence). + * @default 500 + */ + escapeCodeTimeout?: number | undefined; + /** + * The number of spaces a tab is equal to (minimum 1). + * @default 8 + */ + tabSize?: number | undefined; + /** + * Allows closing the interface using an AbortSignal. + * Aborting the signal will internally call `close` on the interface. + */ + signal?: AbortSignal | undefined; + } + /** + * The `readline.createInterface()` method creates a new `readline.Interface` instance. + * + * ```js + * import readline from 'node:readline'; + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout, + * }); + * ``` + * + * Once the `readline.Interface` instance is created, the most common case is to + * listen for the `'line'` event: + * + * ```js + * rl.on('line', (line) => { + * console.log(`Received: ${line}`); + * }); + * ``` + * + * If `terminal` is `true` for this instance then the `output` stream will get + * the best compatibility if it defines an `output.columns` property and emits + * a `'resize'` event on the `output` if or when the columns ever change + * (`process.stdout` does this automatically when it is a TTY). + * + * When creating a `readline.Interface` using `stdin` as input, the program + * will not terminate until it receives an [EOF character](https://en.wikipedia.org/wiki/End-of-file#EOF_character). To exit without + * waiting for user input, call `process.stdin.unref()`. + * @since v0.1.98 + */ + function createInterface( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer | AsyncCompleter, + terminal?: boolean, + ): Interface; + function createInterface(options: ReadLineOptions): Interface; + /** + * The `readline.emitKeypressEvents()` method causes the given `Readable` stream to begin emitting `'keypress'` events corresponding to received input. + * + * Optionally, `interface` specifies a `readline.Interface` instance for which + * autocompletion is disabled when copy-pasted input is detected. + * + * If the `stream` is a `TTY`, then it must be in raw mode. + * + * This is automatically called by any readline instance on its `input` if the `input` is a terminal. Closing the `readline` instance does not stop + * the `input` from emitting `'keypress'` events. + * + * ```js + * readline.emitKeypressEvents(process.stdin); + * if (process.stdin.isTTY) + * process.stdin.setRawMode(true); + * ``` + * + * ## Example: Tiny CLI + * + * The following example illustrates the use of `readline.Interface` class to + * implement a small command-line interface: + * + * ```js + * import readline from 'node:readline'; + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout, + * prompt: 'OHAI> ', + * }); + * + * rl.prompt(); + * + * rl.on('line', (line) => { + * switch (line.trim()) { + * case 'hello': + * console.log('world!'); + * break; + * default: + * console.log(`Say what? I might have heard '${line.trim()}'`); + * break; + * } + * rl.prompt(); + * }).on('close', () => { + * console.log('Have a great day!'); + * process.exit(0); + * }); + * ``` + * + * ## Example: Read file stream line-by-Line + * + * A common use case for `readline` is to consume an input file one line at a + * time. The easiest way to do so is leveraging the `fs.ReadStream` API as + * well as a `for await...of` loop: + * + * ```js + * import fs from 'node:fs'; + * import readline from 'node:readline'; + * + * async function processLineByLine() { + * const fileStream = fs.createReadStream('input.txt'); + * + * const rl = readline.createInterface({ + * input: fileStream, + * crlfDelay: Infinity, + * }); + * // Note: we use the crlfDelay option to recognize all instances of CR LF + * // ('\r\n') in input.txt as a single line break. + * + * for await (const line of rl) { + * // Each line in input.txt will be successively available here as `line`. + * console.log(`Line from file: ${line}`); + * } + * } + * + * processLineByLine(); + * ``` + * + * Alternatively, one could use the `'line'` event: + * + * ```js + * import fs from 'node:fs'; + * import readline from 'node:readline'; + * + * const rl = readline.createInterface({ + * input: fs.createReadStream('sample.txt'), + * crlfDelay: Infinity, + * }); + * + * rl.on('line', (line) => { + * console.log(`Line from file: ${line}`); + * }); + * ``` + * + * Currently, `for await...of` loop can be a bit slower. If `async` / `await` flow and speed are both essential, a mixed approach can be applied: + * + * ```js + * import { once } from 'node:events'; + * import { createReadStream } from 'node:fs'; + * import { createInterface } from 'node:readline'; + * + * (async function processLineByLine() { + * try { + * const rl = createInterface({ + * input: createReadStream('big-file.txt'), + * crlfDelay: Infinity, + * }); + * + * rl.on('line', (line) => { + * // Process the line. + * }); + * + * await once(rl, 'close'); + * + * console.log('File processed.'); + * } catch (err) { + * console.error(err); + * } + * })(); + * ``` + * @since v0.7.7 + */ + function emitKeypressEvents(stream: NodeJS.ReadableStream, readlineInterface?: Interface): void; + type Direction = -1 | 0 | 1; + interface CursorPos { + rows: number; + cols: number; + } + /** + * The `readline.clearLine()` method clears current line of given [TTY](https://nodejs.org/docs/latest-v25.x/api/tty.html) stream + * in a specified direction identified by `dir`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + function clearLine(stream: NodeJS.WritableStream, dir: Direction, callback?: () => void): boolean; + /** + * The `readline.clearScreenDown()` method clears the given [TTY](https://nodejs.org/docs/latest-v25.x/api/tty.html) stream from + * the current position of the cursor down. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + function clearScreenDown(stream: NodeJS.WritableStream, callback?: () => void): boolean; + /** + * The `readline.cursorTo()` method moves cursor to the specified position in a + * given [TTY](https://nodejs.org/docs/latest-v25.x/api/tty.html) `stream`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number, callback?: () => void): boolean; + /** + * The `readline.moveCursor()` method moves the cursor _relative_ to its current + * position in a given [TTY](https://nodejs.org/docs/latest-v25.x/api/tty.html) `stream`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + function moveCursor(stream: NodeJS.WritableStream, dx: number, dy: number, callback?: () => void): boolean; +} +declare module "node:readline" { + export * as promises from "node:readline/promises"; +} +declare module "readline" { + export * from "node:readline"; +} diff --git a/backend/node_modules/@types/node/readline/promises.d.ts b/backend/node_modules/@types/node/readline/promises.d.ts new file mode 100644 index 0000000..f449e1b --- /dev/null +++ b/backend/node_modules/@types/node/readline/promises.d.ts @@ -0,0 +1,161 @@ +/** + * @since v17.0.0 + */ +declare module "node:readline/promises" { + import { Abortable } from "node:events"; + import { + CompleterResult, + Direction, + Interface as _Interface, + ReadLineOptions as _ReadLineOptions, + } from "node:readline"; + /** + * Instances of the `readlinePromises.Interface` class are constructed using the `readlinePromises.createInterface()` method. Every instance is associated with a + * single `input` `Readable` stream and a single `output` `Writable` stream. + * The `output` stream is used to print prompts for user input that arrives on, + * and is read from, the `input` stream. + * @since v17.0.0 + */ + class Interface extends _Interface { + /** + * The `rl.question()` method displays the `query` by writing it to the `output`, + * waits for user input to be provided on `input`, then invokes the `callback` function passing the provided input as the first argument. + * + * When called, `rl.question()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the `query` is not written. + * + * If the question is called after `rl.close()`, it returns a rejected promise. + * + * Example usage: + * + * ```js + * const answer = await rl.question('What is your favorite food? '); + * console.log(`Oh, so your favorite food is ${answer}`); + * ``` + * + * Using an `AbortSignal` to cancel a question. + * + * ```js + * const signal = AbortSignal.timeout(10_000); + * + * signal.addEventListener('abort', () => { + * console.log('The food question timed out'); + * }, { once: true }); + * + * const answer = await rl.question('What is your favorite food? ', { signal }); + * console.log(`Oh, so your favorite food is ${answer}`); + * ``` + * @since v17.0.0 + * @param query A statement or query to write to `output`, prepended to the prompt. + * @return A promise that is fulfilled with the user's input in response to the `query`. + */ + question(query: string): Promise; + question(query: string, options: Abortable): Promise; + } + /** + * @since v17.0.0 + */ + class Readline { + /** + * @param stream A TTY stream. + */ + constructor( + stream: NodeJS.WritableStream, + options?: { + autoCommit?: boolean | undefined; + }, + ); + /** + * The `rl.clearLine()` method adds to the internal list of pending action an + * action that clears current line of the associated `stream` in a specified + * direction identified by `dir`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + clearLine(dir: Direction): this; + /** + * The `rl.clearScreenDown()` method adds to the internal list of pending action an + * action that clears the associated stream from the current position of the + * cursor down. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + clearScreenDown(): this; + /** + * The `rl.commit()` method sends all the pending actions to the associated `stream` and clears the internal list of pending actions. + * @since v17.0.0 + */ + commit(): Promise; + /** + * The `rl.cursorTo()` method adds to the internal list of pending action an action + * that moves cursor to the specified position in the associated `stream`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + cursorTo(x: number, y?: number): this; + /** + * The `rl.moveCursor()` method adds to the internal list of pending action an + * action that moves the cursor _relative_ to its current position in the + * associated `stream`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + moveCursor(dx: number, dy: number): this; + /** + * The `rl.rollback` methods clears the internal list of pending actions without + * sending it to the associated `stream`. + * @since v17.0.0 + * @return this + */ + rollback(): this; + } + type Completer = (line: string) => CompleterResult | Promise; + interface ReadLineOptions extends Omit<_ReadLineOptions, "completer"> { + /** + * An optional function used for Tab autocompletion. + */ + completer?: Completer | undefined; + } + /** + * The `readlinePromises.createInterface()` method creates a new `readlinePromises.Interface` instance. + * + * ```js + * import readlinePromises from 'node:readline/promises'; + * const rl = readlinePromises.createInterface({ + * input: process.stdin, + * output: process.stdout, + * }); + * ``` + * + * Once the `readlinePromises.Interface` instance is created, the most common case + * is to listen for the `'line'` event: + * + * ```js + * rl.on('line', (line) => { + * console.log(`Received: ${line}`); + * }); + * ``` + * + * If `terminal` is `true` for this instance then the `output` stream will get + * the best compatibility if it defines an `output.columns` property and emits + * a `'resize'` event on the `output` if or when the columns ever change + * (`process.stdout` does this automatically when it is a TTY). + * @since v17.0.0 + */ + function createInterface( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer, + terminal?: boolean, + ): Interface; + function createInterface(options: ReadLineOptions): Interface; +} +declare module "readline/promises" { + export * from "node:readline/promises"; +} diff --git a/backend/node_modules/@types/node/repl.d.ts b/backend/node_modules/@types/node/repl.d.ts new file mode 100644 index 0000000..2d06294 --- /dev/null +++ b/backend/node_modules/@types/node/repl.d.ts @@ -0,0 +1,415 @@ +/** + * The `node:repl` module provides a Read-Eval-Print-Loop (REPL) implementation + * that is available both as a standalone program or includible in other + * applications. It can be accessed using: + * + * ```js + * import repl from 'node:repl'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/repl.js) + */ +declare module "node:repl" { + import { AsyncCompleter, Completer, Interface, InterfaceEventMap } from "node:readline"; + import { InspectOptions } from "node:util"; + import { Context } from "node:vm"; + interface ReplOptions { + /** + * The input prompt to display. + * @default "> " + */ + prompt?: string | undefined; + /** + * The `Readable` stream from which REPL input will be read. + * @default process.stdin + */ + input?: NodeJS.ReadableStream | undefined; + /** + * The `Writable` stream to which REPL output will be written. + * @default process.stdout + */ + output?: NodeJS.WritableStream | undefined; + /** + * If `true`, specifies that the output should be treated as a TTY terminal, and have + * ANSI/VT100 escape codes written to it. + * Default: checking the value of the `isTTY` property on the output stream upon + * instantiation. + */ + terminal?: boolean | undefined; + /** + * The function to be used when evaluating each given line of input. + * **Default:** an async wrapper for the JavaScript `eval()` function. An `eval` function can + * error with `repl.Recoverable` to indicate the input was incomplete and prompt for + * additional lines. See the [custom evaluation functions](https://nodejs.org/dist/latest-v25.x/docs/api/repl.html#custom-evaluation-functions) + * section for more details. + */ + eval?: REPLEval | undefined; + /** + * Defines if the repl prints output previews or not. + * @default `true` Always `false` in case `terminal` is falsy. + */ + preview?: boolean | undefined; + /** + * If `true`, specifies that the default `writer` function should include ANSI color + * styling to REPL output. If a custom `writer` function is provided then this has no + * effect. + * @default the REPL instance's `terminal` value + */ + useColors?: boolean | undefined; + /** + * If `true`, specifies that the default evaluation function will use the JavaScript + * `global` as the context as opposed to creating a new separate context for the REPL + * instance. The node CLI REPL sets this value to `true`. + * @default false + */ + useGlobal?: boolean | undefined; + /** + * If `true`, specifies that the default writer will not output the return value of a + * command if it evaluates to `undefined`. + * @default false + */ + ignoreUndefined?: boolean | undefined; + /** + * The function to invoke to format the output of each command before writing to `output`. + * @default a wrapper for `util.inspect` + * + * @see https://nodejs.org/dist/latest-v25.x/docs/api/repl.html#repl_customizing_repl_output + */ + writer?: REPLWriter | undefined; + /** + * An optional function used for custom Tab auto completion. + * + * @see https://nodejs.org/dist/latest-v25.x/docs/api/readline.html#readline_use_of_the_completer_function + */ + completer?: Completer | AsyncCompleter | undefined; + /** + * A flag that specifies whether the default evaluator executes all JavaScript commands in + * strict mode or default (sloppy) mode. + * Accepted values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + replMode?: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT | undefined; + /** + * Stop evaluating the current piece of code when `SIGINT` is received, i.e. `Ctrl+C` is + * pressed. This cannot be used together with a custom `eval` function. + * @default false + */ + breakEvalOnSigint?: boolean | undefined; + } + type REPLEval = ( + this: REPLServer, + evalCmd: string, + context: Context, + file: string, + cb: (err: Error | null, result: any) => void, + ) => void; + type REPLWriter = (this: REPLServer, obj: any) => string; + /** + * This is the default "writer" value, if none is passed in the REPL options, + * and it can be overridden by custom print functions. + */ + const writer: REPLWriter & { + options: InspectOptions; + }; + type REPLCommandAction = (this: REPLServer, text: string) => void; + interface REPLCommand { + /** + * Help text to be displayed when `.help` is entered. + */ + help?: string | undefined; + /** + * The function to execute, optionally accepting a single string argument. + */ + action: REPLCommandAction; + } + interface REPLServerSetupHistoryOptions { + filePath?: string | undefined; + size?: number | undefined; + removeHistoryDuplicates?: boolean | undefined; + onHistoryFileLoaded?: ((err: Error | null, repl: REPLServer) => void) | undefined; + } + interface REPLServerEventMap extends InterfaceEventMap { + "exit": []; + "reset": [context: Context]; + } + /** + * Instances of `repl.REPLServer` are created using the {@link start} method + * or directly using the JavaScript `new` keyword. + * + * ```js + * import repl from 'node:repl'; + * + * const options = { useColors: true }; + * + * const firstInstance = repl.start(options); + * const secondInstance = new repl.REPLServer(options); + * ``` + * @since v0.1.91 + */ + class REPLServer extends Interface { + /** + * NOTE: According to the documentation: + * + * > Instances of `repl.REPLServer` are created using the `repl.start()` method and + * > _should not_ be created directly using the JavaScript `new` keyword. + * + * `REPLServer` cannot be subclassed due to implementation specifics in NodeJS. + * + * @see https://nodejs.org/dist/latest-v25.x/docs/api/repl.html#repl_class_replserver + */ + private constructor(); + /** + * The `vm.Context` provided to the `eval` function to be used for JavaScript + * evaluation. + */ + readonly context: Context; + /** + * @deprecated since v14.3.0 - Use `input` instead. + */ + readonly inputStream: NodeJS.ReadableStream; + /** + * @deprecated since v14.3.0 - Use `output` instead. + */ + readonly outputStream: NodeJS.WritableStream; + /** + * The `Readable` stream from which REPL input will be read. + */ + readonly input: NodeJS.ReadableStream; + /** + * The `Writable` stream to which REPL output will be written. + */ + readonly output: NodeJS.WritableStream; + /** + * The commands registered via `replServer.defineCommand()`. + */ + readonly commands: NodeJS.ReadOnlyDict; + /** + * A value indicating whether the REPL is currently in "editor mode". + * + * @see https://nodejs.org/dist/latest-v25.x/docs/api/repl.html#repl_commands_and_special_keys + */ + readonly editorMode: boolean; + /** + * A value indicating whether the `_` variable has been assigned. + * + * @see https://nodejs.org/dist/latest-v25.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreAssigned: boolean; + /** + * The last evaluation result from the REPL (assigned to the `_` variable inside of the REPL). + * + * @see https://nodejs.org/dist/latest-v25.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly last: any; + /** + * A value indicating whether the `_error` variable has been assigned. + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v25.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreErrAssigned: boolean; + /** + * The last error raised inside the REPL (assigned to the `_error` variable inside of the REPL). + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v25.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly lastError: any; + /** + * Specified in the REPL options, this is the function to be used when evaluating each + * given line of input. If not specified in the REPL options, this is an async wrapper + * for the JavaScript `eval()` function. + */ + readonly eval: REPLEval; + /** + * Specified in the REPL options, this is a value indicating whether the default + * `writer` function should include ANSI color styling to REPL output. + */ + readonly useColors: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `eval` + * function will use the JavaScript `global` as the context as opposed to creating a new + * separate context for the REPL instance. + */ + readonly useGlobal: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `writer` + * function should output the result of a command if it evaluates to `undefined`. + */ + readonly ignoreUndefined: boolean; + /** + * Specified in the REPL options, this is the function to invoke to format the output of + * each command before writing to `outputStream`. If not specified in the REPL options, + * this will be a wrapper for `util.inspect`. + */ + readonly writer: REPLWriter; + /** + * Specified in the REPL options, this is the function to use for custom Tab auto-completion. + */ + readonly completer: Completer | AsyncCompleter; + /** + * Specified in the REPL options, this is a flag that specifies whether the default `eval` + * function should execute all JavaScript commands in strict mode or default (sloppy) mode. + * Possible values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + readonly replMode: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; + /** + * The `replServer.defineCommand()` method is used to add new `.`\-prefixed commands + * to the REPL instance. Such commands are invoked by typing a `.` followed by the `keyword`. The `cmd` is either a `Function` or an `Object` with the following + * properties: + * + * The following example shows two new commands added to the REPL instance: + * + * ```js + * import repl from 'node:repl'; + * + * const replServer = repl.start({ prompt: '> ' }); + * replServer.defineCommand('sayhello', { + * help: 'Say hello', + * action(name) { + * this.clearBufferedCommand(); + * console.log(`Hello, ${name}!`); + * this.displayPrompt(); + * }, + * }); + * replServer.defineCommand('saybye', function saybye() { + * console.log('Goodbye!'); + * this.close(); + * }); + * ``` + * + * The new commands can then be used from within the REPL instance: + * + * ```console + * > .sayhello Node.js User + * Hello, Node.js User! + * > .saybye + * Goodbye! + * ``` + * @since v0.3.0 + * @param keyword The command keyword (_without_ a leading `.` character). + * @param cmd The function to invoke when the command is processed. + */ + defineCommand(keyword: string, cmd: REPLCommandAction | REPLCommand): void; + /** + * The `replServer.displayPrompt()` method readies the REPL instance for input + * from the user, printing the configured `prompt` to a new line in the `output` and resuming the `input` to accept new input. + * + * When multi-line input is being entered, a pipe `'|'` is printed rather than the + * 'prompt'. + * + * When `preserveCursor` is `true`, the cursor placement will not be reset to `0`. + * + * The `replServer.displayPrompt` method is primarily intended to be called from + * within the action function for commands registered using the `replServer.defineCommand()` method. + * @since v0.1.91 + */ + displayPrompt(preserveCursor?: boolean): void; + /** + * The `replServer.clearBufferedCommand()` method clears any command that has been + * buffered but not yet executed. This method is primarily intended to be + * called from within the action function for commands registered using the `replServer.defineCommand()` method. + * @since v9.0.0 + */ + clearBufferedCommand(): void; + /** + * Initializes a history log file for the REPL instance. When executing the + * Node.js binary and using the command-line REPL, a history file is initialized + * by default. However, this is not the case when creating a REPL + * programmatically. Use this method to initialize a history log file when working + * with REPL instances programmatically. + * @since v11.10.0 + * @param historyPath the path to the history file + * @param callback called when history writes are ready or upon error + */ + setupHistory(historyPath: string, callback: (err: Error | null, repl: this) => void): void; + setupHistory( + historyConfig?: REPLServerSetupHistoryOptions, + callback?: (err: Error | null, repl: this) => void, + ): void; + // #region InternalEventEmitter + addListener( + eventName: E, + listener: (...args: REPLServerEventMap[E]) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: REPLServerEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: REPLServerEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners(eventName: E): ((...args: REPLServerEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off(eventName: E, listener: (...args: REPLServerEventMap[E]) => void): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on(eventName: E, listener: (...args: REPLServerEventMap[E]) => void): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: (...args: REPLServerEventMap[E]) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: REPLServerEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: REPLServerEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners(eventName: E): ((...args: REPLServerEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: REPLServerEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + /** + * A flag passed in the REPL options. Evaluates expressions in sloppy mode. + */ + const REPL_MODE_SLOPPY: unique symbol; + /** + * A flag passed in the REPL options. Evaluates expressions in strict mode. + * This is equivalent to prefacing every repl statement with `'use strict'`. + */ + const REPL_MODE_STRICT: unique symbol; + /** + * The `repl.start()` method creates and starts a {@link REPLServer} instance. + * + * If `options` is a string, then it specifies the input prompt: + * + * ```js + * import repl from 'node:repl'; + * + * // a Unix style prompt + * repl.start('$ '); + * ``` + * @since v0.1.91 + */ + function start(options?: string | ReplOptions): REPLServer; + /** + * Indicates a recoverable error that a `REPLServer` can use to support multi-line input. + * + * @see https://nodejs.org/dist/latest-v25.x/docs/api/repl.html#repl_recoverable_errors + */ + class Recoverable extends SyntaxError { + err: Error; + constructor(err: Error); + } +} +declare module "repl" { + export * from "node:repl"; +} diff --git a/backend/node_modules/@types/node/sea.d.ts b/backend/node_modules/@types/node/sea.d.ts new file mode 100644 index 0000000..2930c82 --- /dev/null +++ b/backend/node_modules/@types/node/sea.d.ts @@ -0,0 +1,162 @@ +/** + * This feature allows the distribution of a Node.js application conveniently to a + * system that does not have Node.js installed. + * + * Node.js supports the creation of [single executable applications](https://github.com/nodejs/single-executable) by allowing + * the injection of a blob prepared by Node.js, which can contain a bundled script, + * into the `node` binary. During start up, the program checks if anything has been + * injected. If the blob is found, it executes the script in the blob. Otherwise + * Node.js operates as it normally does. + * + * The single executable application feature currently only supports running a + * single embedded script using the `CommonJS` module system. + * + * Users can create a single executable application from their bundled script + * with the `node` binary itself and any tool which can inject resources into the + * binary. + * + * Here are the steps for creating a single executable application using one such + * tool, [postject](https://github.com/nodejs/postject): + * + * 1. Create a JavaScript file: + * ```bash + * echo 'console.log(`Hello, ${process.argv[2]}!`);' > hello.js + * ``` + * 2. Create a configuration file building a blob that can be injected into the + * single executable application (see `Generating single executable preparation blobs` for details): + * ```bash + * echo '{ "main": "hello.js", "output": "sea-prep.blob" }' > sea-config.json + * ``` + * 3. Generate the blob to be injected: + * ```bash + * node --experimental-sea-config sea-config.json + * ``` + * 4. Create a copy of the `node` executable and name it according to your needs: + * * On systems other than Windows: + * ```bash + * cp $(command -v node) hello + * ``` + * * On Windows: + * ```text + * node -e "require('fs').copyFileSync(process.execPath, 'hello.exe')" + * ``` + * The `.exe` extension is necessary. + * 5. Remove the signature of the binary (macOS and Windows only): + * * On macOS: + * ```bash + * codesign --remove-signature hello + * ``` + * * On Windows (optional): + * [signtool](https://learn.microsoft.com/en-us/windows/win32/seccrypto/signtool) can be used from the installed [Windows SDK](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/). + * If this step is + * skipped, ignore any signature-related warning from postject. + * ```powershell + * signtool remove /s hello.exe + * ``` + * 6. Inject the blob into the copied binary by running `postject` with + * the following options: + * * `hello` / `hello.exe` \- The name of the copy of the `node` executable + * created in step 4. + * * `NODE_SEA_BLOB` \- The name of the resource / note / section in the binary + * where the contents of the blob will be stored. + * * `sea-prep.blob` \- The name of the blob created in step 1. + * * `--sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2` \- The [fuse](https://www.electronjs.org/docs/latest/tutorial/fuses) used by the Node.js project to detect if a file has been + * injected. + * * `--macho-segment-name NODE_SEA` (only needed on macOS) - The name of the + * segment in the binary where the contents of the blob will be + * stored. + * To summarize, here is the required command for each platform: + * * On Linux: + * ```bash + * npx postject hello NODE_SEA_BLOB sea-prep.blob \ + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 + * ``` + * * On Windows - PowerShell: + * ```powershell + * npx postject hello.exe NODE_SEA_BLOB sea-prep.blob ` + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 + * ``` + * * On Windows - Command Prompt: + * ```text + * npx postject hello.exe NODE_SEA_BLOB sea-prep.blob ^ + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 + * ``` + * * On macOS: + * ```bash + * npx postject hello NODE_SEA_BLOB sea-prep.blob \ + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 \ + * --macho-segment-name NODE_SEA + * ``` + * 7. Sign the binary (macOS and Windows only): + * * On macOS: + * ```bash + * codesign --sign - hello + * ``` + * * On Windows (optional): + * A certificate needs to be present for this to work. However, the unsigned + * binary would still be runnable. + * ```powershell + * signtool sign /fd SHA256 hello.exe + * ``` + * 8. Run the binary: + * * On systems other than Windows + * ```console + * $ ./hello world + * Hello, world! + * ``` + * * On Windows + * ```console + * $ .\hello.exe world + * Hello, world! + * ``` + * @since v19.7.0, v18.16.0 + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v25.x/src/node_sea.cc) + */ +declare module "node:sea" { + type AssetKey = string; + /** + * @since v20.12.0 + * @return Whether this script is running inside a single-executable application. + */ + function isSea(): boolean; + /** + * This method can be used to retrieve the assets configured to be bundled into the + * single-executable application at build time. + * An error is thrown when no matching asset can be found. + * @since v20.12.0 + */ + function getAsset(key: AssetKey): ArrayBuffer; + function getAsset(key: AssetKey, encoding: string): string; + /** + * Similar to `sea.getAsset()`, but returns the result in a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob). + * An error is thrown when no matching asset can be found. + * @since v20.12.0 + */ + function getAssetAsBlob(key: AssetKey, options?: { + type: string; + }): Blob; + /** + * This method can be used to retrieve the assets configured to be bundled into the + * single-executable application at build time. + * An error is thrown when no matching asset can be found. + * + * Unlike `sea.getRawAsset()` or `sea.getAssetAsBlob()`, this method does not + * return a copy. Instead, it returns the raw asset bundled inside the executable. + * + * For now, users should avoid writing to the returned array buffer. If the + * injected section is not marked as writable or not aligned properly, + * writes to the returned array buffer is likely to result in a crash. + * @since v20.12.0 + */ + function getRawAsset(key: AssetKey): ArrayBuffer; + /** + * This method can be used to retrieve an array of all the keys of assets + * embedded into the single-executable application. + * An error is thrown when not running inside a single-executable application. + * @since v24.8.0 + * @returns An array containing all the keys of the assets + * embedded in the executable. If no assets are embedded, returns an empty array. + */ + function getAssetKeys(): string[]; +} diff --git a/backend/node_modules/@types/node/sqlite.d.ts b/backend/node_modules/@types/node/sqlite.d.ts new file mode 100644 index 0000000..76e585f --- /dev/null +++ b/backend/node_modules/@types/node/sqlite.d.ts @@ -0,0 +1,937 @@ +/** + * The `node:sqlite` module facilitates working with SQLite databases. + * To access it: + * + * ```js + * import sqlite from 'node:sqlite'; + * ``` + * + * This module is only available under the `node:` scheme. The following will not + * work: + * + * ```js + * import sqlite from 'sqlite'; + * ``` + * + * The following example shows the basic usage of the `node:sqlite` module to open + * an in-memory database, write data to the database, and then read the data back. + * + * ```js + * import { DatabaseSync } from 'node:sqlite'; + * const database = new DatabaseSync(':memory:'); + * + * // Execute SQL statements from strings. + * database.exec(` + * CREATE TABLE data( + * key INTEGER PRIMARY KEY, + * value TEXT + * ) STRICT + * `); + * // Create a prepared statement to insert data into the database. + * const insert = database.prepare('INSERT INTO data (key, value) VALUES (?, ?)'); + * // Execute the prepared statement with bound values. + * insert.run(1, 'hello'); + * insert.run(2, 'world'); + * // Create a prepared statement to read data from the database. + * const query = database.prepare('SELECT * FROM data ORDER BY key'); + * // Execute the prepared statement and log the result set. + * console.log(query.all()); + * // Prints: [ { key: 1, value: 'hello' }, { key: 2, value: 'world' } ] + * ``` + * @since v22.5.0 + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/sqlite.js) + */ +declare module "node:sqlite" { + import { PathLike } from "node:fs"; + type SQLInputValue = null | number | bigint | string | NodeJS.ArrayBufferView; + type SQLOutputValue = null | number | bigint | string | NodeJS.NonSharedUint8Array; + interface DatabaseSyncOptions { + /** + * If `true`, the database is opened by the constructor. When + * this value is `false`, the database must be opened via the `open()` method. + * @since v22.5.0 + * @default true + */ + open?: boolean | undefined; + /** + * If `true`, foreign key constraints + * are enabled. This is recommended but can be disabled for compatibility with + * legacy database schemas. The enforcement of foreign key constraints can be + * enabled and disabled after opening the database using + * [`PRAGMA foreign_keys`](https://www.sqlite.org/pragma.html#pragma_foreign_keys). + * @since v22.10.0 + * @default true + */ + enableForeignKeyConstraints?: boolean | undefined; + /** + * If `true`, SQLite will accept + * [double-quoted string literals](https://www.sqlite.org/quirks.html#dblquote). + * This is not recommended but can be + * enabled for compatibility with legacy database schemas. + * @since v22.10.0 + * @default false + */ + enableDoubleQuotedStringLiterals?: boolean | undefined; + /** + * If `true`, the database is opened in read-only mode. + * If the database does not exist, opening it will fail. + * @since v22.12.0 + * @default false + */ + readOnly?: boolean | undefined; + /** + * If `true`, the `loadExtension` SQL function + * and the `loadExtension()` method are enabled. + * You can call `enableLoadExtension(false)` later to disable this feature. + * @since v22.13.0 + * @default false + */ + allowExtension?: boolean | undefined; + /** + * The [busy timeout](https://sqlite.org/c3ref/busy_timeout.html) in milliseconds. This is the maximum amount of + * time that SQLite will wait for a database lock to be released before + * returning an error. + * @since v24.0.0 + * @default 0 + */ + timeout?: number | undefined; + /** + * If `true`, integer fields are read as JavaScript `BigInt` values. If `false`, + * integer fields are read as JavaScript numbers. + * @since v24.4.0 + * @default false + */ + readBigInts?: boolean | undefined; + /** + * If `true`, query results are returned as arrays instead of objects. + * @since v24.4.0 + * @default false + */ + returnArrays?: boolean | undefined; + /** + * If `true`, allows binding named parameters without the prefix + * character (e.g., `foo` instead of `:foo`). + * @since v24.4.40 + * @default true + */ + allowBareNamedParameters?: boolean | undefined; + /** + * If `true`, unknown named parameters are ignored when binding. + * If `false`, an exception is thrown for unknown named parameters. + * @since v24.4.40 + * @default false + */ + allowUnknownNamedParameters?: boolean | undefined; + } + interface CreateSessionOptions { + /** + * A specific table to track changes for. By default, changes to all tables are tracked. + * @since v22.12.0 + */ + table?: string | undefined; + /** + * Name of the database to track. This is useful when multiple databases have been added using + * [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html). + * @since v22.12.0 + * @default 'main' + */ + db?: string | undefined; + } + interface ApplyChangesetOptions { + /** + * Skip changes that, when targeted table name is supplied to this function, return a truthy value. + * By default, all changes are attempted. + * @since v22.12.0 + */ + filter?: ((tableName: string) => boolean) | undefined; + /** + * A function that determines how to handle conflicts. The function receives one argument, + * which can be one of the following values: + * + * * `SQLITE_CHANGESET_DATA`: A `DELETE` or `UPDATE` change does not contain the expected "before" values. + * * `SQLITE_CHANGESET_NOTFOUND`: A row matching the primary key of the `DELETE` or `UPDATE` change does not exist. + * * `SQLITE_CHANGESET_CONFLICT`: An `INSERT` change results in a duplicate primary key. + * * `SQLITE_CHANGESET_FOREIGN_KEY`: Applying a change would result in a foreign key violation. + * * `SQLITE_CHANGESET_CONSTRAINT`: Applying a change results in a `UNIQUE`, `CHECK`, or `NOT NULL` constraint + * violation. + * + * The function should return one of the following values: + * + * * `SQLITE_CHANGESET_OMIT`: Omit conflicting changes. + * * `SQLITE_CHANGESET_REPLACE`: Replace existing values with conflicting changes (only valid with + `SQLITE_CHANGESET_DATA` or `SQLITE_CHANGESET_CONFLICT` conflicts). + * * `SQLITE_CHANGESET_ABORT`: Abort on conflict and roll back the database. + * + * When an error is thrown in the conflict handler or when any other value is returned from the handler, + * applying the changeset is aborted and the database is rolled back. + * + * **Default**: A function that returns `SQLITE_CHANGESET_ABORT`. + * @since v22.12.0 + */ + onConflict?: ((conflictType: number) => number) | undefined; + } + interface FunctionOptions { + /** + * If `true`, the [`SQLITE_DETERMINISTIC`](https://www.sqlite.org/c3ref/c_deterministic.html) flag is + * set on the created function. + * @default false + */ + deterministic?: boolean | undefined; + /** + * If `true`, the [`SQLITE_DIRECTONLY`](https://www.sqlite.org/c3ref/c_directonly.html) flag is set on + * the created function. + * @default false + */ + directOnly?: boolean | undefined; + /** + * If `true`, integer arguments to `function` + * are converted to `BigInt`s. If `false`, integer arguments are passed as + * JavaScript numbers. + * @default false + */ + useBigIntArguments?: boolean | undefined; + /** + * If `true`, `function` may be invoked with any number of + * arguments (between zero and + * [`SQLITE_MAX_FUNCTION_ARG`](https://www.sqlite.org/limits.html#max_function_arg)). If `false`, + * `function` must be invoked with exactly `function.length` arguments. + * @default false + */ + varargs?: boolean | undefined; + } + interface AggregateOptions extends FunctionOptions { + /** + * The identity value for the aggregation function. This value is used when the aggregation + * function is initialized. When a `Function` is passed the identity will be its return value. + */ + start: T | (() => T); + /** + * The function to call for each row in the aggregation. The + * function receives the current state and the row value. The return value of + * this function should be the new state. + */ + step: (accumulator: T, ...args: SQLOutputValue[]) => T; + /** + * The function to call to get the result of the + * aggregation. The function receives the final state and should return the + * result of the aggregation. + */ + result?: ((accumulator: T) => SQLInputValue) | undefined; + /** + * When this function is provided, the `aggregate` method will work as a window function. + * The function receives the current state and the dropped row value. The return value of this function should be the + * new state. + */ + inverse?: ((accumulator: T, ...args: SQLOutputValue[]) => T) | undefined; + } + /** + * This class represents a single [connection](https://www.sqlite.org/c3ref/sqlite3.html) to a SQLite database. All APIs + * exposed by this class execute synchronously. + * @since v22.5.0 + */ + class DatabaseSync implements Disposable { + /** + * Constructs a new `DatabaseSync` instance. + * @param path The path of the database. + * A SQLite database can be stored in a file or completely [in memory](https://www.sqlite.org/inmemorydb.html). + * To use a file-backed database, the path should be a file path. + * To use an in-memory database, the path should be the special name `':memory:'`. + * @param options Configuration options for the database connection. + */ + constructor(path: PathLike, options?: DatabaseSyncOptions); + /** + * Registers a new aggregate function with the SQLite database. This method is a wrapper around + * [`sqlite3_create_window_function()`](https://www.sqlite.org/c3ref/create_function.html). + * + * When used as a window function, the `result` function will be called multiple times. + * + * ```js + * import { DatabaseSync } from 'node:sqlite'; + * + * const db = new DatabaseSync(':memory:'); + * db.exec(` + * CREATE TABLE t3(x, y); + * INSERT INTO t3 VALUES ('a', 4), + * ('b', 5), + * ('c', 3), + * ('d', 8), + * ('e', 1); + * `); + * + * db.aggregate('sumint', { + * start: 0, + * step: (acc, value) => acc + value, + * }); + * + * db.prepare('SELECT sumint(y) as total FROM t3').get(); // { total: 21 } + * ``` + * @since v24.0.0 + * @param name The name of the SQLite function to create. + * @param options Function configuration settings. + */ + aggregate(name: string, options: AggregateOptions): void; + aggregate(name: string, options: AggregateOptions): void; + /** + * Closes the database connection. An exception is thrown if the database is not + * open. This method is a wrapper around [`sqlite3_close_v2()`](https://www.sqlite.org/c3ref/close.html). + * @since v22.5.0 + */ + close(): void; + /** + * Loads a shared library into the database connection. This method is a wrapper + * around [`sqlite3_load_extension()`](https://www.sqlite.org/c3ref/load_extension.html). It is required to enable the + * `allowExtension` option when constructing the `DatabaseSync` instance. + * @since v22.13.0 + * @param path The path to the shared library to load. + */ + loadExtension(path: string): void; + /** + * Enables or disables the `loadExtension` SQL function, and the `loadExtension()` + * method. When `allowExtension` is `false` when constructing, you cannot enable + * loading extensions for security reasons. + * @since v22.13.0 + * @param allow Whether to allow loading extensions. + */ + enableLoadExtension(allow: boolean): void; + /** + * This method is a wrapper around [`sqlite3_db_filename()`](https://sqlite.org/c3ref/db_filename.html) + * @since v24.0.0 + * @param dbName Name of the database. This can be `'main'` (the default primary database) or any other + * database that has been added with [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html) **Default:** `'main'`. + * @returns The location of the database file. When using an in-memory database, + * this method returns null. + */ + location(dbName?: string): string | null; + /** + * This method allows one or more SQL statements to be executed without returning + * any results. This method is useful when executing SQL statements read from a + * file. This method is a wrapper around [`sqlite3_exec()`](https://www.sqlite.org/c3ref/exec.html). + * @since v22.5.0 + * @param sql A SQL string to execute. + */ + exec(sql: string): void; + /** + * This method is used to create SQLite user-defined functions. This method is a + * wrapper around [`sqlite3_create_function_v2()`](https://www.sqlite.org/c3ref/create_function.html). + * @since v22.13.0 + * @param name The name of the SQLite function to create. + * @param options Optional configuration settings for the function. + * @param func The JavaScript function to call when the SQLite + * function is invoked. The return value of this function should be a valid + * SQLite data type: see + * [Type conversion between JavaScript and SQLite](https://nodejs.org/docs/latest-v25.x/api/sqlite.html#type-conversion-between-javascript-and-sqlite). + * The result defaults to `NULL` if the return value is `undefined`. + */ + function( + name: string, + options: FunctionOptions, + func: (...args: SQLOutputValue[]) => SQLInputValue, + ): void; + function(name: string, func: (...args: SQLOutputValue[]) => SQLInputValue): void; + /** + * Sets an authorizer callback that SQLite will invoke whenever it attempts to + * access data or modify the database schema through prepared statements. + * This can be used to implement security policies, audit access, or restrict certain operations. + * This method is a wrapper around [`sqlite3_set_authorizer()`](https://sqlite.org/c3ref/set_authorizer.html). + * + * When invoked, the callback receives five arguments: + * + * * `actionCode` {number} The type of operation being performed (e.g., + * `SQLITE_INSERT`, `SQLITE_UPDATE`, `SQLITE_SELECT`). + * * `arg1` {string|null} The first argument (context-dependent, often a table name). + * * `arg2` {string|null} The second argument (context-dependent, often a column name). + * * `dbName` {string|null} The name of the database. + * * `triggerOrView` {string|null} The name of the trigger or view causing the access. + * + * The callback must return one of the following constants: + * + * * `SQLITE_OK` - Allow the operation. + * * `SQLITE_DENY` - Deny the operation (causes an error). + * * `SQLITE_IGNORE` - Ignore the operation (silently skip). + * + * ```js + * import { DatabaseSync, constants } from 'node:sqlite'; + * const db = new DatabaseSync(':memory:'); + * + * // Set up an authorizer that denies all table creation + * db.setAuthorizer((actionCode) => { + * if (actionCode === constants.SQLITE_CREATE_TABLE) { + * return constants.SQLITE_DENY; + * } + * return constants.SQLITE_OK; + * }); + * + * // This will work + * db.prepare('SELECT 1').get(); + * + * // This will throw an error due to authorization denial + * try { + * db.exec('CREATE TABLE blocked (id INTEGER)'); + * } catch (err) { + * console.log('Operation blocked:', err.message); + * } + * ``` + * @since v24.10.0 + * @param callback The authorizer function to set, or `null` to + * clear the current authorizer. + */ + setAuthorizer( + callback: + | (( + actionCode: number, + arg1: string | null, + arg2: string | null, + dbName: string | null, + triggerOrView: string | null, + ) => number) + | null, + ): void; + /** + * Whether the database is currently open or not. + * @since v22.15.0 + */ + readonly isOpen: boolean; + /** + * Whether the database is currently within a transaction. This method + * is a wrapper around [`sqlite3_get_autocommit()`](https://sqlite.org/c3ref/get_autocommit.html). + * @since v24.0.0 + */ + readonly isTransaction: boolean; + /** + * Opens the database specified in the `path` argument of the `DatabaseSync`constructor. This method should only be used when the database is not opened via + * the constructor. An exception is thrown if the database is already open. + * @since v22.5.0 + */ + open(): void; + /** + * Compiles a SQL statement into a [prepared statement](https://www.sqlite.org/c3ref/stmt.html). This method is a wrapper + * around [`sqlite3_prepare_v2()`](https://www.sqlite.org/c3ref/prepare.html). + * @since v22.5.0 + * @param sql A SQL string to compile to a prepared statement. + * @return The prepared statement. + */ + prepare(sql: string): StatementSync; + /** + * Creates a new `SQLTagStore`, which is an LRU (Least Recently Used) cache for + * storing prepared statements. This allows for the efficient reuse of prepared + * statements by tagging them with a unique identifier. + * + * When a tagged SQL literal is executed, the `SQLTagStore` checks if a prepared + * statement for that specific SQL string already exists in the cache. If it does, + * the cached statement is used. If not, a new prepared statement is created, + * executed, and then stored in the cache for future use. This mechanism helps to + * avoid the overhead of repeatedly parsing and preparing the same SQL statements. + * + * ```js + * import { DatabaseSync } from 'node:sqlite'; + * + * const db = new DatabaseSync(':memory:'); + * const sql = db.createSQLTagStore(); + * + * db.exec('CREATE TABLE users (id INT, name TEXT)'); + * + * // Using the 'run' method to insert data. + * // The tagged literal is used to identify the prepared statement. + * sql.run`INSERT INTO users VALUES (1, 'Alice')`; + * sql.run`INSERT INTO users VALUES (2, 'Bob')`; + * + * // Using the 'get' method to retrieve a single row. + * const id = 1; + * const user = sql.get`SELECT * FROM users WHERE id = ${id}`; + * console.log(user); // { id: 1, name: 'Alice' } + * + * // Using the 'all' method to retrieve all rows. + * const allUsers = sql.all`SELECT * FROM users ORDER BY id`; + * console.log(allUsers); + * // [ + * // { id: 1, name: 'Alice' }, + * // { id: 2, name: 'Bob' } + * // ] + * ``` + * @since v24.9.0 + * @returns A new SQL tag store for caching prepared statements. + */ + createTagStore(maxSize?: number): SQLTagStore; + /** + * Creates and attaches a session to the database. This method is a wrapper around + * [`sqlite3session_create()`](https://www.sqlite.org/session/sqlite3session_create.html) and + * [`sqlite3session_attach()`](https://www.sqlite.org/session/sqlite3session_attach.html). + * @param options The configuration options for the session. + * @returns A session handle. + * @since v22.12.0 + */ + createSession(options?: CreateSessionOptions): Session; + /** + * An exception is thrown if the database is not + * open. This method is a wrapper around + * [`sqlite3changeset_apply()`](https://www.sqlite.org/session/sqlite3changeset_apply.html). + * + * ```js + * const sourceDb = new DatabaseSync(':memory:'); + * const targetDb = new DatabaseSync(':memory:'); + * + * sourceDb.exec('CREATE TABLE data(key INTEGER PRIMARY KEY, value TEXT)'); + * targetDb.exec('CREATE TABLE data(key INTEGER PRIMARY KEY, value TEXT)'); + * + * const session = sourceDb.createSession(); + * + * const insert = sourceDb.prepare('INSERT INTO data (key, value) VALUES (?, ?)'); + * insert.run(1, 'hello'); + * insert.run(2, 'world'); + * + * const changeset = session.changeset(); + * targetDb.applyChangeset(changeset); + * // Now that the changeset has been applied, targetDb contains the same data as sourceDb. + * ``` + * @param changeset A binary changeset or patchset. + * @param options The configuration options for how the changes will be applied. + * @returns Whether the changeset was applied successfully without being aborted. + * @since v22.12.0 + */ + applyChangeset(changeset: Uint8Array, options?: ApplyChangesetOptions): boolean; + /** + * Closes the database connection. If the database connection is already closed + * then this is a no-op. + * @since v22.15.0 + */ + [Symbol.dispose](): void; + } + /** + * @since v22.12.0 + */ + interface Session { + /** + * Retrieves a changeset containing all changes since the changeset was created. Can be called multiple times. + * An exception is thrown if the database or the session is not open. This method is a wrapper around + * [`sqlite3session_changeset()`](https://www.sqlite.org/session/sqlite3session_changeset.html). + * @returns Binary changeset that can be applied to other databases. + * @since v22.12.0 + */ + changeset(): NodeJS.NonSharedUint8Array; + /** + * Similar to the method above, but generates a more compact patchset. See + * [Changesets and Patchsets](https://www.sqlite.org/sessionintro.html#changesets_and_patchsets) + * in the documentation of SQLite. An exception is thrown if the database or the session is not open. This method is a + * wrapper around + * [`sqlite3session_patchset()`](https://www.sqlite.org/session/sqlite3session_patchset.html). + * @returns Binary patchset that can be applied to other databases. + * @since v22.12.0 + */ + patchset(): NodeJS.NonSharedUint8Array; + /** + * Closes the session. An exception is thrown if the database or the session is not open. This method is a + * wrapper around + * [`sqlite3session_delete()`](https://www.sqlite.org/session/sqlite3session_delete.html). + */ + close(): void; + } + /** + * This class represents a single LRU (Least Recently Used) cache for storing + * prepared statements. + * + * Instances of this class are created via the database.createSQLTagStore() method, + * not by using a constructor. The store caches prepared statements based on the + * provided SQL query string. When the same query is seen again, the store + * retrieves the cached statement and safely applies the new values through + * parameter binding, thereby preventing attacks like SQL injection. + * + * The cache has a maxSize that defaults to 1000 statements, but a custom size can + * be provided (e.g., database.createSQLTagStore(100)). All APIs exposed by this + * class execute synchronously. + * @since v24.9.0 + */ + interface SQLTagStore { + /** + * Executes the given SQL query and returns all resulting rows as an array of objects. + * @since v24.9.0 + */ + all( + stringElements: TemplateStringsArray, + ...boundParameters: SQLInputValue[] + ): Record[]; + /** + * Executes the given SQL query and returns the first resulting row as an object. + * @since v24.9.0 + */ + get( + stringElements: TemplateStringsArray, + ...boundParameters: SQLInputValue[] + ): Record | undefined; + /** + * Executes the given SQL query and returns an iterator over the resulting rows. + * @since v24.9.0 + */ + iterate( + stringElements: TemplateStringsArray, + ...boundParameters: SQLInputValue[] + ): NodeJS.Iterator>; + /** + * Executes the given SQL query, which is expected to not return any rows (e.g., INSERT, UPDATE, DELETE). + * @since v24.9.0 + */ + run(stringElements: TemplateStringsArray, ...boundParameters: SQLInputValue[]): StatementResultingChanges; + /** + * A read-only property that returns the number of prepared statements currently in the cache. + * @since v24.9.0 + * @returns The maximum number of prepared statements the cache can hold. + */ + size(): number; + /** + * A read-only property that returns the maximum number of prepared statements the cache can hold. + * @since v24.9.0 + */ + readonly capacity: number; + /** + * A read-only property that returns the `DatabaseSync` object associated with this `SQLTagStore`. + * @since v24.9.0 + */ + readonly db: DatabaseSync; + /** + * Resets the LRU cache, clearing all stored prepared statements. + * @since v24.9.0 + */ + clear(): void; + } + interface StatementColumnMetadata { + /** + * The unaliased name of the column in the origin + * table, or `null` if the column is the result of an expression or subquery. + * This property is the result of [`sqlite3_column_origin_name()`](https://www.sqlite.org/c3ref/column_database_name.html). + */ + column: string | null; + /** + * The unaliased name of the origin database, or + * `null` if the column is the result of an expression or subquery. This + * property is the result of [`sqlite3_column_database_name()`](https://www.sqlite.org/c3ref/column_database_name.html). + */ + database: string | null; + /** + * The name assigned to the column in the result set of a + * `SELECT` statement. This property is the result of + * [`sqlite3_column_name()`](https://www.sqlite.org/c3ref/column_name.html). + */ + name: string; + /** + * The unaliased name of the origin table, or `null` if + * the column is the result of an expression or subquery. This property is the + * result of [`sqlite3_column_table_name()`](https://www.sqlite.org/c3ref/column_database_name.html). + */ + table: string | null; + /** + * The declared data type of the column, or `null` if the + * column is the result of an expression or subquery. This property is the + * result of [`sqlite3_column_decltype()`](https://www.sqlite.org/c3ref/column_decltype.html). + */ + type: string | null; + } + interface StatementResultingChanges { + /** + * The number of rows modified, inserted, or deleted by the most recently completed `INSERT`, `UPDATE`, or `DELETE` statement. + * This field is either a number or a `BigInt` depending on the prepared statement's configuration. + * This property is the result of [`sqlite3_changes64()`](https://www.sqlite.org/c3ref/changes.html). + */ + changes: number | bigint; + /** + * The most recently inserted rowid. + * This field is either a number or a `BigInt` depending on the prepared statement's configuration. + * This property is the result of [`sqlite3_last_insert_rowid()`](https://www.sqlite.org/c3ref/last_insert_rowid.html). + */ + lastInsertRowid: number | bigint; + } + /** + * This class represents a single [prepared statement](https://www.sqlite.org/c3ref/stmt.html). This class cannot be + * instantiated via its constructor. Instead, instances are created via the`database.prepare()` method. All APIs exposed by this class execute + * synchronously. + * + * A prepared statement is an efficient binary representation of the SQL used to + * create it. Prepared statements are parameterizable, and can be invoked multiple + * times with different bound values. Parameters also offer protection against [SQL injection](https://en.wikipedia.org/wiki/SQL_injection) attacks. For these reasons, prepared statements are + * preferred + * over hand-crafted SQL strings when handling user input. + * @since v22.5.0 + */ + class StatementSync { + private constructor(); + /** + * This method executes a prepared statement and returns all results as an array of + * objects. If the prepared statement does not return any results, this method + * returns an empty array. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using + * the values in `namedParameters` and `anonymousParameters`. + * @since v22.5.0 + * @param namedParameters An optional object used to bind named parameters. The keys of this object are used to configure the mapping. + * @param anonymousParameters Zero or more values to bind to anonymous parameters. + * @return An array of objects. Each object corresponds to a row returned by executing the prepared statement. The keys and values of each object correspond to the column names and values of + * the row. + */ + all(...anonymousParameters: SQLInputValue[]): Record[]; + all( + namedParameters: Record, + ...anonymousParameters: SQLInputValue[] + ): Record[]; + /** + * This method is used to retrieve information about the columns returned by the + * prepared statement. + * @since v23.11.0 + * @returns An array of objects. Each object corresponds to a column + * in the prepared statement, and contains the following properties: + */ + columns(): StatementColumnMetadata[]; + /** + * The source SQL text of the prepared statement with parameter + * placeholders replaced by the values that were used during the most recent + * execution of this prepared statement. This property is a wrapper around + * [`sqlite3_expanded_sql()`](https://www.sqlite.org/c3ref/expanded_sql.html). + * @since v22.5.0 + */ + readonly expandedSQL: string; + /** + * This method executes a prepared statement and returns the first result as an + * object. If the prepared statement does not return any results, this method + * returns `undefined`. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using the + * values in `namedParameters` and `anonymousParameters`. + * @since v22.5.0 + * @param namedParameters An optional object used to bind named parameters. The keys of this object are used to configure the mapping. + * @param anonymousParameters Zero or more values to bind to anonymous parameters. + * @return An object corresponding to the first row returned by executing the prepared statement. The keys and values of the object correspond to the column names and values of the row. If no + * rows were returned from the database then this method returns `undefined`. + */ + get(...anonymousParameters: SQLInputValue[]): Record | undefined; + get( + namedParameters: Record, + ...anonymousParameters: SQLInputValue[] + ): Record | undefined; + /** + * This method executes a prepared statement and returns an iterator of + * objects. If the prepared statement does not return any results, this method + * returns an empty iterator. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using + * the values in `namedParameters` and `anonymousParameters`. + * @since v22.13.0 + * @param namedParameters An optional object used to bind named parameters. + * The keys of this object are used to configure the mapping. + * @param anonymousParameters Zero or more values to bind to anonymous parameters. + * @returns An iterable iterator of objects. Each object corresponds to a row + * returned by executing the prepared statement. The keys and values of each + * object correspond to the column names and values of the row. + */ + iterate(...anonymousParameters: SQLInputValue[]): NodeJS.Iterator>; + iterate( + namedParameters: Record, + ...anonymousParameters: SQLInputValue[] + ): NodeJS.Iterator>; + /** + * This method executes a prepared statement and returns an object summarizing the + * resulting changes. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using the + * values in `namedParameters` and `anonymousParameters`. + * @since v22.5.0 + * @param namedParameters An optional object used to bind named parameters. The keys of this object are used to configure the mapping. + * @param anonymousParameters Zero or more values to bind to anonymous parameters. + */ + run(...anonymousParameters: SQLInputValue[]): StatementResultingChanges; + run( + namedParameters: Record, + ...anonymousParameters: SQLInputValue[] + ): StatementResultingChanges; + /** + * The names of SQLite parameters begin with a prefix character. By default,`node:sqlite` requires that this prefix character is present when binding + * parameters. However, with the exception of dollar sign character, these + * prefix characters also require extra quoting when used in object keys. + * + * To improve ergonomics, this method can be used to also allow bare named + * parameters, which do not require the prefix character in JavaScript code. There + * are several caveats to be aware of when enabling bare named parameters: + * + * * The prefix character is still required in SQL. + * * The prefix character is still allowed in JavaScript. In fact, prefixed names + * will have slightly better binding performance. + * * Using ambiguous named parameters, such as `$k` and `@k`, in the same prepared + * statement will result in an exception as it cannot be determined how to bind + * a bare name. + * @since v22.5.0 + * @param enabled Enables or disables support for binding named parameters without the prefix character. + */ + setAllowBareNamedParameters(enabled: boolean): void; + /** + * By default, if an unknown name is encountered while binding parameters, an + * exception is thrown. This method allows unknown named parameters to be ignored. + * @since v22.15.0 + * @param enabled Enables or disables support for unknown named parameters. + */ + setAllowUnknownNamedParameters(enabled: boolean): void; + /** + * When enabled, query results returned by the `all()`, `get()`, and `iterate()` methods will be returned as arrays instead + * of objects. + * @since v24.0.0 + * @param enabled Enables or disables the return of query results as arrays. + */ + setReturnArrays(enabled: boolean): void; + /** + * When reading from the database, SQLite `INTEGER`s are mapped to JavaScript + * numbers by default. However, SQLite `INTEGER`s can store values larger than + * JavaScript numbers are capable of representing. In such cases, this method can + * be used to read `INTEGER` data using JavaScript `BigInt`s. This method has no + * impact on database write operations where numbers and `BigInt`s are both + * supported at all times. + * @since v22.5.0 + * @param enabled Enables or disables the use of `BigInt`s when reading `INTEGER` fields from the database. + */ + setReadBigInts(enabled: boolean): void; + /** + * The source SQL text of the prepared statement. This property is a + * wrapper around [`sqlite3_sql()`](https://www.sqlite.org/c3ref/expanded_sql.html). + * @since v22.5.0 + */ + readonly sourceSQL: string; + } + interface BackupOptions { + /** + * Name of the source database. This can be `'main'` (the default primary database) or any other + * database that have been added with [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html) + * @default 'main' + */ + source?: string | undefined; + /** + * Name of the target database. This can be `'main'` (the default primary database) or any other + * database that have been added with [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html) + * @default 'main' + */ + target?: string | undefined; + /** + * Number of pages to be transmitted in each batch of the backup. + * @default 100 + */ + rate?: number | undefined; + /** + * An optional callback function that will be called after each backup step. The argument passed + * to this callback is an `Object` with `remainingPages` and `totalPages` properties, describing the current progress + * of the backup operation. + */ + progress?: ((progressInfo: BackupProgressInfo) => void) | undefined; + } + interface BackupProgressInfo { + totalPages: number; + remainingPages: number; + } + /** + * This method makes a database backup. This method abstracts the + * [`sqlite3_backup_init()`](https://www.sqlite.org/c3ref/backup_finish.html#sqlite3backupinit), + * [`sqlite3_backup_step()`](https://www.sqlite.org/c3ref/backup_finish.html#sqlite3backupstep) + * and [`sqlite3_backup_finish()`](https://www.sqlite.org/c3ref/backup_finish.html#sqlite3backupfinish) functions. + * + * The backed-up database can be used normally during the backup process. Mutations coming from the same connection - same + * `DatabaseSync` - object will be reflected in the backup right away. However, mutations from other connections will cause + * the backup process to restart. + * + * ```js + * import { backup, DatabaseSync } from 'node:sqlite'; + * + * const sourceDb = new DatabaseSync('source.db'); + * const totalPagesTransferred = await backup(sourceDb, 'backup.db', { + * rate: 1, // Copy one page at a time. + * progress: ({ totalPages, remainingPages }) => { + * console.log('Backup in progress', { totalPages, remainingPages }); + * }, + * }); + * + * console.log('Backup completed', totalPagesTransferred); + * ``` + * @since v23.8.0 + * @param sourceDb The database to backup. The source database must be open. + * @param path The path where the backup will be created. If the file already exists, + * the contents will be overwritten. + * @param options Optional configuration for the backup. The + * following properties are supported: + * @returns A promise that fulfills with the total number of backed-up pages upon completion, or rejects if an + * error occurs. + */ + function backup(sourceDb: DatabaseSync, path: PathLike, options?: BackupOptions): Promise; + /** + * @since v22.13.0 + */ + namespace constants { + /** + * The conflict handler is invoked with this constant when processing a DELETE or UPDATE change if a row with the required PRIMARY KEY fields is present in the database, but one or more other (non primary-key) fields modified by the update do not contain the expected "before" values. + * @since v22.14.0 + */ + const SQLITE_CHANGESET_DATA: number; + /** + * The conflict handler is invoked with this constant when processing a DELETE or UPDATE change if a row with the required PRIMARY KEY fields is not present in the database. + * @since v22.14.0 + */ + const SQLITE_CHANGESET_NOTFOUND: number; + /** + * This constant is passed to the conflict handler while processing an INSERT change if the operation would result in duplicate primary key values. + * @since v22.14.0 + */ + const SQLITE_CHANGESET_CONFLICT: number; + /** + * If foreign key handling is enabled, and applying a changeset leaves the database in a state containing foreign key violations, the conflict handler is invoked with this constant exactly once before the changeset is committed. If the conflict handler returns `SQLITE_CHANGESET_OMIT`, the changes, including those that caused the foreign key constraint violation, are committed. Or, if it returns `SQLITE_CHANGESET_ABORT`, the changeset is rolled back. + * @since v22.14.0 + */ + const SQLITE_CHANGESET_FOREIGN_KEY: number; + /** + * Conflicting changes are omitted. + * @since v22.12.0 + */ + const SQLITE_CHANGESET_OMIT: number; + /** + * Conflicting changes replace existing values. Note that this value can only be returned when the type of conflict is either `SQLITE_CHANGESET_DATA` or `SQLITE_CHANGESET_CONFLICT`. + * @since v22.12.0 + */ + const SQLITE_CHANGESET_REPLACE: number; + /** + * Abort when a change encounters a conflict and roll back database. + * @since v22.12.0 + */ + const SQLITE_CHANGESET_ABORT: number; + /** + * Deny the operation and cause an error to be returned. + * @since v24.10.0 + */ + const SQLITE_DENY: number; + /** + * Ignore the operation and continue as if it had never been requested. + * @since 24.10.0 + */ + const SQLITE_IGNORE: number; + /** + * Allow the operation to proceed normally. + * @since v24.10.0 + */ + const SQLITE_OK: number; + const SQLITE_CREATE_INDEX: number; + const SQLITE_CREATE_TABLE: number; + const SQLITE_CREATE_TEMP_INDEX: number; + const SQLITE_CREATE_TEMP_TABLE: number; + const SQLITE_CREATE_TEMP_TRIGGER: number; + const SQLITE_CREATE_TEMP_VIEW: number; + const SQLITE_CREATE_TRIGGER: number; + const SQLITE_CREATE_VIEW: number; + const SQLITE_DELETE: number; + const SQLITE_DROP_INDEX: number; + const SQLITE_DROP_TABLE: number; + const SQLITE_DROP_TEMP_INDEX: number; + const SQLITE_DROP_TEMP_TABLE: number; + const SQLITE_DROP_TEMP_TRIGGER: number; + const SQLITE_DROP_TEMP_VIEW: number; + const SQLITE_DROP_TRIGGER: number; + const SQLITE_DROP_VIEW: number; + const SQLITE_INSERT: number; + const SQLITE_PRAGMA: number; + const SQLITE_READ: number; + const SQLITE_SELECT: number; + const SQLITE_TRANSACTION: number; + const SQLITE_UPDATE: number; + const SQLITE_ATTACH: number; + const SQLITE_DETACH: number; + const SQLITE_ALTER_TABLE: number; + const SQLITE_REINDEX: number; + const SQLITE_ANALYZE: number; + const SQLITE_CREATE_VTABLE: number; + const SQLITE_DROP_VTABLE: number; + const SQLITE_FUNCTION: number; + const SQLITE_SAVEPOINT: number; + const SQLITE_COPY: number; + const SQLITE_RECURSIVE: number; + } +} diff --git a/backend/node_modules/@types/node/stream.d.ts b/backend/node_modules/@types/node/stream.d.ts new file mode 100644 index 0000000..79ad890 --- /dev/null +++ b/backend/node_modules/@types/node/stream.d.ts @@ -0,0 +1,1760 @@ +/** + * A stream is an abstract interface for working with streaming data in Node.js. + * The `node:stream` module provides an API for implementing the stream interface. + * + * There are many stream objects provided by Node.js. For instance, a [request to an HTTP server](https://nodejs.org/docs/latest-v25.x/api/http.html#class-httpincomingmessage) + * and [`process.stdout`](https://nodejs.org/docs/latest-v25.x/api/process.html#processstdout) are both stream instances. + * + * Streams can be readable, writable, or both. All streams are instances of [`EventEmitter`](https://nodejs.org/docs/latest-v25.x/api/events.html#class-eventemitter). + * + * To access the `node:stream` module: + * + * ```js + * import stream from 'node:stream'; + * ``` + * + * The `node:stream` module is useful for creating new types of stream instances. + * It is usually not necessary to use the `node:stream` module to consume streams. + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/stream.js) + */ +declare module "node:stream" { + import { Blob } from "node:buffer"; + import { Abortable, EventEmitter } from "node:events"; + import * as promises from "node:stream/promises"; + import * as web from "node:stream/web"; + class Stream extends EventEmitter { + /** + * @since v0.9.4 + */ + pipe( + destination: T, + options?: Stream.PipeOptions, + ): T; + } + namespace Stream { + export { promises, Stream }; + } + namespace Stream { + interface PipeOptions { + /** + * End the writer when the reader ends. + * @default true + */ + end?: boolean | undefined; + } + interface StreamOptions extends Abortable { + emitClose?: boolean | undefined; + highWaterMark?: number | undefined; + objectMode?: boolean | undefined; + construct?: ((this: T, callback: (error?: Error | null) => void) => void) | undefined; + destroy?: ((this: T, error: Error | null, callback: (error?: Error | null) => void) => void) | undefined; + autoDestroy?: boolean | undefined; + } + interface ReadableOptions extends StreamOptions { + encoding?: BufferEncoding | undefined; + read?: ((this: T, size: number) => void) | undefined; + } + interface ReadableIteratorOptions { + /** + * When set to `false`, calling `return` on the async iterator, + * or exiting a `for await...of` iteration using a `break`, + * `return`, or `throw` will not destroy the stream. + * @default true + */ + destroyOnReturn?: boolean | undefined; + } + interface ReadableOperatorOptions extends Abortable { + /** + * The maximum concurrent invocations of `fn` to call + * on the stream at once. + * @default 1 + */ + concurrency?: number | undefined; + /** + * How many items to buffer while waiting for user consumption + * of the output. + * @default concurrency * 2 - 1 + */ + highWaterMark?: number | undefined; + } + /** @deprecated Use `ReadableOperatorOptions` instead. */ + interface ArrayOptions extends ReadableOperatorOptions {} + interface ReadableToWebOptions { + strategy?: web.QueuingStrategy | undefined; + } + interface ReadableEventMap { + "close": []; + "data": [chunk: any]; + "end": []; + "error": [err: Error]; + "pause": []; + "readable": []; + "resume": []; + } + /** + * @since v0.9.4 + */ + class Readable extends Stream implements NodeJS.ReadableStream { + constructor(options?: ReadableOptions); + /** + * A utility method for creating Readable Streams out of iterators. + * @since v12.3.0, v10.17.0 + * @param iterable Object implementing the `Symbol.asyncIterator` or `Symbol.iterator` iterable protocol. Emits an 'error' event if a null value is passed. + * @param options Options provided to `new stream.Readable([options])`. By default, `Readable.from()` will set `options.objectMode` to `true`, unless this is explicitly opted out by setting `options.objectMode` to `false`. + */ + static from(iterable: Iterable | AsyncIterable, options?: ReadableOptions): Readable; + /** + * A utility method for creating a `Readable` from a web `ReadableStream`. + * @since v17.0.0 + */ + static fromWeb( + readableStream: web.ReadableStream, + options?: Pick, + ): Readable; + /** + * A utility method for creating a web `ReadableStream` from a `Readable`. + * @since v17.0.0 + */ + static toWeb( + streamReadable: NodeJS.ReadableStream, + options?: ReadableToWebOptions, + ): web.ReadableStream; + /** + * Returns whether the stream has been read from or cancelled. + * @since v16.8.0 + */ + static isDisturbed(stream: NodeJS.ReadableStream | web.ReadableStream): boolean; + /** + * Returns whether the stream was destroyed or errored before emitting `'end'`. + * @since v16.8.0 + */ + readonly readableAborted: boolean; + /** + * Is `true` if it is safe to call {@link read}, which means + * the stream has not been destroyed or emitted `'error'` or `'end'`. + * @since v11.4.0 + */ + readable: boolean; + /** + * Returns whether `'data'` has been emitted. + * @since v16.7.0, v14.18.0 + */ + readonly readableDidRead: boolean; + /** + * Getter for the property `encoding` of a given `Readable` stream. The `encoding` property can be set using the {@link setEncoding} method. + * @since v12.7.0 + */ + readonly readableEncoding: BufferEncoding | null; + /** + * Becomes `true` when [`'end'`](https://nodejs.org/docs/latest-v25.x/api/stream.html#event-end) event is emitted. + * @since v12.9.0 + */ + readonly readableEnded: boolean; + /** + * This property reflects the current state of a `Readable` stream as described + * in the [Three states](https://nodejs.org/docs/latest-v25.x/api/stream.html#three-states) section. + * @since v9.4.0 + */ + readableFlowing: boolean | null; + /** + * Returns the value of `highWaterMark` passed when creating this `Readable`. + * @since v9.3.0 + */ + readonly readableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be read. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ + readonly readableLength: number; + /** + * Getter for the property `objectMode` of a given `Readable` stream. + * @since v12.3.0 + */ + readonly readableObjectMode: boolean; + /** + * Is `true` after `readable.destroy()` has been called. + * @since v8.0.0 + */ + destroyed: boolean; + /** + * Is `true` after `'close'` has been emitted. + * @since v18.0.0 + */ + readonly closed: boolean; + /** + * Returns error if the stream has been destroyed with an error. + * @since v18.0.0 + */ + readonly errored: Error | null; + _construct?(callback: (error?: Error | null) => void): void; + _read(size: number): void; + /** + * The `readable.read()` method reads data out of the internal buffer and + * returns it. If no data is available to be read, `null` is returned. By default, + * the data is returned as a `Buffer` object unless an encoding has been + * specified using the `readable.setEncoding()` method or the stream is operating + * in object mode. + * + * The optional `size` argument specifies a specific number of bytes to read. If + * `size` bytes are not available to be read, `null` will be returned _unless_ the + * stream has ended, in which case all of the data remaining in the internal buffer + * will be returned. + * + * If the `size` argument is not specified, all of the data contained in the + * internal buffer will be returned. + * + * The `size` argument must be less than or equal to 1 GiB. + * + * The `readable.read()` method should only be called on `Readable` streams + * operating in paused mode. In flowing mode, `readable.read()` is called + * automatically until the internal buffer is fully drained. + * + * ```js + * const readable = getReadableStreamSomehow(); + * + * // 'readable' may be triggered multiple times as data is buffered in + * readable.on('readable', () => { + * let chunk; + * console.log('Stream is readable (new data received in buffer)'); + * // Use a loop to make sure we read all currently available data + * while (null !== (chunk = readable.read())) { + * console.log(`Read ${chunk.length} bytes of data...`); + * } + * }); + * + * // 'end' will be triggered once when there is no more data available + * readable.on('end', () => { + * console.log('Reached end of stream.'); + * }); + * ``` + * + * Each call to `readable.read()` returns a chunk of data, or `null`. The chunks + * are not concatenated. A `while` loop is necessary to consume all data + * currently in the buffer. When reading a large file `.read()` may return `null`, + * having consumed all buffered content so far, but there is still more data to + * come not yet buffered. In this case a new `'readable'` event will be emitted + * when there is more data in the buffer. Finally the `'end'` event will be + * emitted when there is no more data to come. + * + * Therefore to read a file's whole contents from a `readable`, it is necessary + * to collect chunks across multiple `'readable'` events: + * + * ```js + * const chunks = []; + * + * readable.on('readable', () => { + * let chunk; + * while (null !== (chunk = readable.read())) { + * chunks.push(chunk); + * } + * }); + * + * readable.on('end', () => { + * const content = chunks.join(''); + * }); + * ``` + * + * A `Readable` stream in object mode will always return a single item from + * a call to `readable.read(size)`, regardless of the value of the `size` argument. + * + * If the `readable.read()` method returns a chunk of data, a `'data'` event will + * also be emitted. + * + * Calling {@link read} after the `'end'` event has + * been emitted will return `null`. No runtime error will be raised. + * @since v0.9.4 + * @param size Optional argument to specify how much data to read. + */ + read(size?: number): any; + /** + * The `readable.setEncoding()` method sets the character encoding for + * data read from the `Readable` stream. + * + * By default, no encoding is assigned and stream data will be returned as `Buffer` objects. Setting an encoding causes the stream data + * to be returned as strings of the specified encoding rather than as `Buffer` objects. For instance, calling `readable.setEncoding('utf8')` will cause the + * output data to be interpreted as UTF-8 data, and passed as strings. Calling `readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal + * string format. + * + * The `Readable` stream will properly handle multi-byte characters delivered + * through the stream that would otherwise become improperly decoded if simply + * pulled from the stream as `Buffer` objects. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.setEncoding('utf8'); + * readable.on('data', (chunk) => { + * assert.equal(typeof chunk, 'string'); + * console.log('Got %d characters of string data:', chunk.length); + * }); + * ``` + * @since v0.9.4 + * @param encoding The encoding to use. + */ + setEncoding(encoding: BufferEncoding): this; + /** + * The `readable.pause()` method will cause a stream in flowing mode to stop + * emitting `'data'` events, switching out of flowing mode. Any data that + * becomes available will remain in the internal buffer. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.on('data', (chunk) => { + * console.log(`Received ${chunk.length} bytes of data.`); + * readable.pause(); + * console.log('There will be no additional data for 1 second.'); + * setTimeout(() => { + * console.log('Now data will start flowing again.'); + * readable.resume(); + * }, 1000); + * }); + * ``` + * + * The `readable.pause()` method has no effect if there is a `'readable'` event listener. + * @since v0.9.4 + */ + pause(): this; + /** + * The `readable.resume()` method causes an explicitly paused `Readable` stream to + * resume emitting `'data'` events, switching the stream into flowing mode. + * + * The `readable.resume()` method can be used to fully consume the data from a + * stream without actually processing any of that data: + * + * ```js + * getReadableStreamSomehow() + * .resume() + * .on('end', () => { + * console.log('Reached the end, but did not read anything.'); + * }); + * ``` + * + * The `readable.resume()` method has no effect if there is a `'readable'` event listener. + * @since v0.9.4 + */ + resume(): this; + /** + * The `readable.isPaused()` method returns the current operating state of the `Readable`. + * This is used primarily by the mechanism that underlies the `readable.pipe()` method. + * In most typical cases, there will be no reason to use this method directly. + * + * ```js + * const readable = new stream.Readable(); + * + * readable.isPaused(); // === false + * readable.pause(); + * readable.isPaused(); // === true + * readable.resume(); + * readable.isPaused(); // === false + * ``` + * @since v0.11.14 + */ + isPaused(): boolean; + /** + * The `readable.unpipe()` method detaches a `Writable` stream previously attached + * using the {@link pipe} method. + * + * If the `destination` is not specified, then _all_ pipes are detached. + * + * If the `destination` is specified, but no pipe is set up for it, then + * the method does nothing. + * + * ```js + * import fs from 'node:fs'; + * const readable = getReadableStreamSomehow(); + * const writable = fs.createWriteStream('file.txt'); + * // All the data from readable goes into 'file.txt', + * // but only for the first second. + * readable.pipe(writable); + * setTimeout(() => { + * console.log('Stop writing to file.txt.'); + * readable.unpipe(writable); + * console.log('Manually close the file stream.'); + * writable.end(); + * }, 1000); + * ``` + * @since v0.9.4 + * @param destination Optional specific stream to unpipe + */ + unpipe(destination?: NodeJS.WritableStream): this; + /** + * Passing `chunk` as `null` signals the end of the stream (EOF) and behaves the + * same as `readable.push(null)`, after which no more data can be written. The EOF + * signal is put at the end of the buffer and any buffered data will still be + * flushed. + * + * The `readable.unshift()` method pushes a chunk of data back into the internal + * buffer. This is useful in certain situations where a stream is being consumed by + * code that needs to "un-consume" some amount of data that it has optimistically + * pulled out of the source, so that the data can be passed on to some other party. + * + * The `stream.unshift(chunk)` method cannot be called after the `'end'` event + * has been emitted or a runtime error will be thrown. + * + * Developers using `stream.unshift()` often should consider switching to + * use of a `Transform` stream instead. See the `API for stream implementers` section for more information. + * + * ```js + * // Pull off a header delimited by \n\n. + * // Use unshift() if we get too much. + * // Call the callback with (error, header, stream). + * import { StringDecoder } from 'node:string_decoder'; + * function parseHeader(stream, callback) { + * stream.on('error', callback); + * stream.on('readable', onReadable); + * const decoder = new StringDecoder('utf8'); + * let header = ''; + * function onReadable() { + * let chunk; + * while (null !== (chunk = stream.read())) { + * const str = decoder.write(chunk); + * if (str.includes('\n\n')) { + * // Found the header boundary. + * const split = str.split(/\n\n/); + * header += split.shift(); + * const remaining = split.join('\n\n'); + * const buf = Buffer.from(remaining, 'utf8'); + * stream.removeListener('error', callback); + * // Remove the 'readable' listener before unshifting. + * stream.removeListener('readable', onReadable); + * if (buf.length) + * stream.unshift(buf); + * // Now the body of the message can be read from the stream. + * callback(null, header, stream); + * return; + * } + * // Still reading the header. + * header += str; + * } + * } + * } + * ``` + * + * Unlike {@link push}, `stream.unshift(chunk)` will not + * end the reading process by resetting the internal reading state of the stream. + * This can cause unexpected results if `readable.unshift()` is called during a + * read (i.e. from within a {@link _read} implementation on a + * custom stream). Following the call to `readable.unshift()` with an immediate {@link push} will reset the reading state appropriately, + * however it is best to simply avoid calling `readable.unshift()` while in the + * process of performing a read. + * @since v0.9.11 + * @param chunk Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must + * be a {string}, {Buffer}, {TypedArray}, {DataView} or `null`. For object mode streams, `chunk` may be any JavaScript value. + * @param encoding Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`. + */ + unshift(chunk: any, encoding?: BufferEncoding): void; + /** + * Prior to Node.js 0.10, streams did not implement the entire `node:stream` module API as it is currently defined. (See `Compatibility` for more + * information.) + * + * When using an older Node.js library that emits `'data'` events and has a {@link pause} method that is advisory only, the `readable.wrap()` method can be used to create a `Readable` + * stream that uses + * the old stream as its data source. + * + * It will rarely be necessary to use `readable.wrap()` but the method has been + * provided as a convenience for interacting with older Node.js applications and + * libraries. + * + * ```js + * import { OldReader } from './old-api-module.js'; + * import { Readable } from 'node:stream'; + * const oreader = new OldReader(); + * const myReader = new Readable().wrap(oreader); + * + * myReader.on('readable', () => { + * myReader.read(); // etc. + * }); + * ``` + * @since v0.9.4 + * @param stream An "old style" readable stream + */ + wrap(stream: NodeJS.ReadableStream): this; + push(chunk: any, encoding?: BufferEncoding): boolean; + /** + * ```js + * import { Readable } from 'node:stream'; + * + * async function* splitToWords(source) { + * for await (const chunk of source) { + * const words = String(chunk).split(' '); + * + * for (const word of words) { + * yield word; + * } + * } + * } + * + * const wordsStream = Readable.from(['this is', 'compose as operator']).compose(splitToWords); + * const words = await wordsStream.toArray(); + * + * console.log(words); // prints ['this', 'is', 'compose', 'as', 'operator'] + * ``` + * + * See [`stream.compose`](https://nodejs.org/docs/latest-v25.x/api/stream.html#streamcomposestreams) for more information. + * @since v19.1.0, v18.13.0 + * @returns a stream composed with the stream `stream`. + */ + compose( + stream: NodeJS.WritableStream | web.WritableStream | web.TransformStream | ((source: any) => void), + options?: Abortable, + ): Duplex; + /** + * The iterator created by this method gives users the option to cancel the destruction + * of the stream if the `for await...of` loop is exited by `return`, `break`, or `throw`, + * or if the iterator should destroy the stream if the stream emitted an error during iteration. + * @since v16.3.0 + */ + iterator(options?: ReadableIteratorOptions): NodeJS.AsyncIterator; + /** + * This method allows mapping over the stream. The *fn* function will be called for every chunk in the stream. + * If the *fn* function returns a promise - that promise will be `await`ed before being passed to the result stream. + * @since v17.4.0, v16.14.0 + * @param fn a function to map over every chunk in the stream. Async or not. + * @returns a stream mapped with the function *fn*. + */ + map(fn: (data: any, options?: Abortable) => any, options?: ReadableOperatorOptions): Readable; + /** + * This method allows filtering the stream. For each chunk in the stream the *fn* function will be called + * and if it returns a truthy value, the chunk will be passed to the result stream. + * If the *fn* function returns a promise - that promise will be `await`ed. + * @since v17.4.0, v16.14.0 + * @param fn a function to filter chunks from the stream. Async or not. + * @returns a stream filtered with the predicate *fn*. + */ + filter( + fn: (data: any, options?: Abortable) => boolean | Promise, + options?: ReadableOperatorOptions, + ): Readable; + /** + * This method allows iterating a stream. For each chunk in the stream the *fn* function will be called. + * If the *fn* function returns a promise - that promise will be `await`ed. + * + * This method is different from `for await...of` loops in that it can optionally process chunks concurrently. + * In addition, a `forEach` iteration can only be stopped by having passed a `signal` option + * and aborting the related AbortController while `for await...of` can be stopped with `break` or `return`. + * In either case the stream will be destroyed. + * + * This method is different from listening to the `'data'` event in that it uses the `readable` event + * in the underlying machinary and can limit the number of concurrent *fn* calls. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise for when the stream has finished. + */ + forEach( + fn: (data: any, options?: Abortable) => void | Promise, + options?: Pick, + ): Promise; + /** + * This method allows easily obtaining the contents of a stream. + * + * As this method reads the entire stream into memory, it negates the benefits of streams. It's intended + * for interoperability and convenience, not as the primary way to consume streams. + * @since v17.5.0 + * @returns a promise containing an array with the contents of the stream. + */ + toArray(options?: Abortable): Promise; + /** + * This method is similar to `Array.prototype.some` and calls *fn* on each chunk in the stream + * until the awaited return value is `true` (or any truthy value). Once an *fn* call on a chunk + * `await`ed return value is truthy, the stream is destroyed and the promise is fulfilled with `true`. + * If none of the *fn* calls on the chunks return a truthy value, the promise is fulfilled with `false`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to `true` if *fn* returned a truthy value for at least one of the chunks. + */ + some( + fn: (data: any, options?: Abortable) => boolean | Promise, + options?: Pick, + ): Promise; + /** + * This method is similar to `Array.prototype.find` and calls *fn* on each chunk in the stream + * to find a chunk with a truthy value for *fn*. Once an *fn* call's awaited return value is truthy, + * the stream is destroyed and the promise is fulfilled with value for which *fn* returned a truthy value. + * If all of the *fn* calls on the chunks return a falsy value, the promise is fulfilled with `undefined`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to the first chunk for which *fn* evaluated with a truthy value, + * or `undefined` if no element was found. + */ + find( + fn: (data: any, options?: Abortable) => data is T, + options?: Pick, + ): Promise; + find( + fn: (data: any, options?: Abortable) => boolean | Promise, + options?: Pick, + ): Promise; + /** + * This method is similar to `Array.prototype.every` and calls *fn* on each chunk in the stream + * to check if all awaited return values are truthy value for *fn*. Once an *fn* call on a chunk + * `await`ed return value is falsy, the stream is destroyed and the promise is fulfilled with `false`. + * If all of the *fn* calls on the chunks return a truthy value, the promise is fulfilled with `true`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to `true` if *fn* returned a truthy value for every one of the chunks. + */ + every( + fn: (data: any, options?: Abortable) => boolean | Promise, + options?: Pick, + ): Promise; + /** + * This method returns a new stream by applying the given callback to each chunk of the stream + * and then flattening the result. + * + * It is possible to return a stream or another iterable or async iterable from *fn* and the result streams + * will be merged (flattened) into the returned stream. + * @since v17.5.0 + * @param fn a function to map over every chunk in the stream. May be async. May be a stream or generator. + * @returns a stream flat-mapped with the function *fn*. + */ + flatMap( + fn: (data: any, options?: Abortable) => any, + options?: Pick, + ): Readable; + /** + * This method returns a new stream with the first *limit* chunks dropped from the start. + * @since v17.5.0 + * @param limit the number of chunks to drop from the readable. + * @returns a stream with *limit* chunks dropped from the start. + */ + drop(limit: number, options?: Abortable): Readable; + /** + * This method returns a new stream with the first *limit* chunks. + * @since v17.5.0 + * @param limit the number of chunks to take from the readable. + * @returns a stream with *limit* chunks taken. + */ + take(limit: number, options?: Abortable): Readable; + /** + * This method calls *fn* on each chunk of the stream in order, passing it the result from the calculation + * on the previous element. It returns a promise for the final value of the reduction. + * + * If no *initial* value is supplied the first chunk of the stream is used as the initial value. + * If the stream is empty, the promise is rejected with a `TypeError` with the `ERR_INVALID_ARGS` code property. + * + * The reducer function iterates the stream element-by-element which means that there is no *concurrency* parameter + * or parallelism. To perform a reduce concurrently, you can extract the async function to `readable.map` method. + * @since v17.5.0 + * @param fn a reducer function to call over every chunk in the stream. Async or not. + * @param initial the initial value to use in the reduction. + * @returns a promise for the final value of the reduction. + */ + reduce(fn: (previous: any, data: any, options?: Abortable) => T): Promise; + reduce( + fn: (previous: T, data: any, options?: Abortable) => T, + initial: T, + options?: Abortable, + ): Promise; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'` event (unless `emitClose` is set to `false`). After this call, the readable + * stream will release any internal resources and subsequent calls to `push()` will be ignored. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, but instead implement `readable._destroy()`. + * @since v8.0.0 + * @param error Error which will be passed as payload in `'error'` event + */ + destroy(error?: Error): this; + /** + * @returns `AsyncIterator` to fully consume the stream. + * @since v10.0.0 + */ + [Symbol.asyncIterator](): NodeJS.AsyncIterator; + /** + * Calls `readable.destroy()` with an `AbortError` and returns + * a promise that fulfills when the stream is finished. + * @since v20.4.0 + */ + [Symbol.asyncDispose](): Promise; + // #region InternalEventEmitter + addListener( + eventName: E, + listener: (...args: ReadableEventMap[E]) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: ReadableEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: ReadableEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners(eventName: E): ((...args: ReadableEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off(eventName: E, listener: (...args: ReadableEventMap[E]) => void): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on(eventName: E, listener: (...args: ReadableEventMap[E]) => void): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: (...args: ReadableEventMap[E]) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: ReadableEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: ReadableEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners(eventName: E): ((...args: ReadableEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: ReadableEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + interface WritableOptions extends StreamOptions { + decodeStrings?: boolean | undefined; + defaultEncoding?: BufferEncoding | undefined; + write?: + | (( + this: T, + chunk: any, + encoding: BufferEncoding, + callback: (error?: Error | null) => void, + ) => void) + | undefined; + writev?: + | (( + this: T, + chunks: { + chunk: any; + encoding: BufferEncoding; + }[], + callback: (error?: Error | null) => void, + ) => void) + | undefined; + final?: ((this: T, callback: (error?: Error | null) => void) => void) | undefined; + } + interface WritableEventMap { + "close": []; + "drain": []; + "error": [err: Error]; + "finish": []; + "pipe": [src: Readable]; + "unpipe": [src: Readable]; + } + /** + * @since v0.9.4 + */ + class Writable extends Stream implements NodeJS.WritableStream { + constructor(options?: WritableOptions); + /** + * A utility method for creating a `Writable` from a web `WritableStream`. + * @since v17.0.0 + */ + static fromWeb( + writableStream: web.WritableStream, + options?: Pick, + ): Writable; + /** + * A utility method for creating a web `WritableStream` from a `Writable`. + * @since v17.0.0 + */ + static toWeb(streamWritable: NodeJS.WritableStream): web.WritableStream; + /** + * Is `true` if it is safe to call `writable.write()`, which means + * the stream has not been destroyed, errored, or ended. + * @since v11.4.0 + */ + writable: boolean; + /** + * Returns whether the stream was destroyed or errored before emitting `'finish'`. + * @since v18.0.0, v16.17.0 + */ + readonly writableAborted: boolean; + /** + * Is `true` after `writable.end()` has been called. This property + * does not indicate whether the data has been flushed, for this use `writable.writableFinished` instead. + * @since v12.9.0 + */ + readonly writableEnded: boolean; + /** + * Is set to `true` immediately before the `'finish'` event is emitted. + * @since v12.6.0 + */ + readonly writableFinished: boolean; + /** + * Return the value of `highWaterMark` passed when creating this `Writable`. + * @since v9.3.0 + */ + readonly writableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be written. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ + readonly writableLength: number; + /** + * Getter for the property `objectMode` of a given `Writable` stream. + * @since v12.3.0 + */ + readonly writableObjectMode: boolean; + /** + * Number of times `writable.uncork()` needs to be + * called in order to fully uncork the stream. + * @since v13.2.0, v12.16.0 + */ + readonly writableCorked: number; + /** + * Is `true` after `writable.destroy()` has been called. + * @since v8.0.0 + */ + destroyed: boolean; + /** + * Is `true` after `'close'` has been emitted. + * @since v18.0.0 + */ + readonly closed: boolean; + /** + * Returns error if the stream has been destroyed with an error. + * @since v18.0.0 + */ + readonly errored: Error | null; + /** + * Is `true` if the stream's buffer has been full and stream will emit `'drain'`. + * @since v15.2.0, v14.17.0 + */ + readonly writableNeedDrain: boolean; + _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + _writev?( + chunks: { + chunk: any; + encoding: BufferEncoding; + }[], + callback: (error?: Error | null) => void, + ): void; + _construct?(callback: (error?: Error | null) => void): void; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + /** + * The `writable.write()` method writes some data to the stream, and calls the + * supplied `callback` once the data has been fully handled. If an error + * occurs, the `callback` will be called with the error as its + * first argument. The `callback` is called asynchronously and before `'error'` is + * emitted. + * + * The return value is `true` if the internal buffer is less than the `highWaterMark` configured when the stream was created after admitting `chunk`. + * If `false` is returned, further attempts to write data to the stream should + * stop until the `'drain'` event is emitted. + * + * While a stream is not draining, calls to `write()` will buffer `chunk`, and + * return false. Once all currently buffered chunks are drained (accepted for + * delivery by the operating system), the `'drain'` event will be emitted. + * Once `write()` returns false, do not write more chunks + * until the `'drain'` event is emitted. While calling `write()` on a stream that + * is not draining is allowed, Node.js will buffer all written chunks until + * maximum memory usage occurs, at which point it will abort unconditionally. + * Even before it aborts, high memory usage will cause poor garbage collector + * performance and high RSS (which is not typically released back to the system, + * even after the memory is no longer required). Since TCP sockets may never + * drain if the remote peer does not read the data, writing a socket that is + * not draining may lead to a remotely exploitable vulnerability. + * + * Writing data while the stream is not draining is particularly + * problematic for a `Transform`, because the `Transform` streams are paused + * by default until they are piped or a `'data'` or `'readable'` event handler + * is added. + * + * If the data to be written can be generated or fetched on demand, it is + * recommended to encapsulate the logic into a `Readable` and use {@link pipe}. However, if calling `write()` is preferred, it is + * possible to respect backpressure and avoid memory issues using the `'drain'` event: + * + * ```js + * function write(data, cb) { + * if (!stream.write(data)) { + * stream.once('drain', cb); + * } else { + * process.nextTick(cb); + * } + * } + * + * // Wait for cb to be called before doing any other write. + * write('hello', () => { + * console.log('Write completed, do more writes now.'); + * }); + * ``` + * + * A `Writable` stream in object mode will always ignore the `encoding` argument. + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a {string}, {Buffer}, + * {TypedArray} or {DataView}. For object mode streams, `chunk` may be any JavaScript value other than `null`. + * @param [encoding='utf8'] The encoding, if `chunk` is a string. + * @param callback Callback for when this chunk of data is flushed. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + write(chunk: any, callback?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, encoding: BufferEncoding, callback?: (error: Error | null | undefined) => void): boolean; + /** + * The `writable.setDefaultEncoding()` method sets the default `encoding` for a `Writable` stream. + * @since v0.11.15 + * @param encoding The new default encoding + */ + setDefaultEncoding(encoding: BufferEncoding): this; + /** + * Calling the `writable.end()` method signals that no more data will be written + * to the `Writable`. The optional `chunk` and `encoding` arguments allow one + * final additional chunk of data to be written immediately before closing the + * stream. + * + * Calling the {@link write} method after calling {@link end} will raise an error. + * + * ```js + * // Write 'hello, ' and then end with 'world!'. + * import fs from 'node:fs'; + * const file = fs.createWriteStream('example.txt'); + * file.write('hello, '); + * file.end('world!'); + * // Writing more now is not allowed! + * ``` + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a {string}, {Buffer}, + * {TypedArray} or {DataView}. For object mode streams, `chunk` may be any JavaScript value other than `null`. + * @param encoding The encoding if `chunk` is a string + * @param callback Callback for when the stream is finished. + */ + end(cb?: () => void): this; + end(chunk: any, cb?: () => void): this; + end(chunk: any, encoding: BufferEncoding, cb?: () => void): this; + /** + * The `writable.cork()` method forces all written data to be buffered in memory. + * The buffered data will be flushed when either the {@link uncork} or {@link end} methods are called. + * + * The primary intent of `writable.cork()` is to accommodate a situation in which + * several small chunks are written to the stream in rapid succession. Instead of + * immediately forwarding them to the underlying destination, `writable.cork()` buffers all the chunks until `writable.uncork()` is called, which will pass them + * all to `writable._writev()`, if present. This prevents a head-of-line blocking + * situation where data is being buffered while waiting for the first small chunk + * to be processed. However, use of `writable.cork()` without implementing `writable._writev()` may have an adverse effect on throughput. + * + * See also: `writable.uncork()`, `writable._writev()`. + * @since v0.11.2 + */ + cork(): void; + /** + * The `writable.uncork()` method flushes all data buffered since {@link cork} was called. + * + * When using `writable.cork()` and `writable.uncork()` to manage the buffering + * of writes to a stream, defer calls to `writable.uncork()` using `process.nextTick()`. Doing so allows batching of all `writable.write()` calls that occur within a given Node.js event + * loop phase. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.write('data '); + * process.nextTick(() => stream.uncork()); + * ``` + * + * If the `writable.cork()` method is called multiple times on a stream, the + * same number of calls to `writable.uncork()` must be called to flush the buffered + * data. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.cork(); + * stream.write('data '); + * process.nextTick(() => { + * stream.uncork(); + * // The data will not be flushed until uncork() is called a second time. + * stream.uncork(); + * }); + * ``` + * + * See also: `writable.cork()`. + * @since v0.11.2 + */ + uncork(): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'` event (unless `emitClose` is set to `false`). After this call, the writable + * stream has ended and subsequent calls to `write()` or `end()` will result in + * an `ERR_STREAM_DESTROYED` error. + * This is a destructive and immediate way to destroy a stream. Previous calls to `write()` may not have drained, and may trigger an `ERR_STREAM_DESTROYED` error. + * Use `end()` instead of destroy if data should flush before close, or wait for + * the `'drain'` event before destroying the stream. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, + * but instead implement `writable._destroy()`. + * @since v8.0.0 + * @param error Optional, an error to emit with `'error'` event. + */ + destroy(error?: Error): this; + /** + * Calls `writable.destroy()` with an `AbortError` and returns + * a promise that fulfills when the stream is finished. + * @since v22.4.0, v20.16.0 + */ + [Symbol.asyncDispose](): Promise; + // #region InternalEventEmitter + addListener( + eventName: E, + listener: (...args: WritableEventMap[E]) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: WritableEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: WritableEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners(eventName: E): ((...args: WritableEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off(eventName: E, listener: (...args: WritableEventMap[E]) => void): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on(eventName: E, listener: (...args: WritableEventMap[E]) => void): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: (...args: WritableEventMap[E]) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: WritableEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: WritableEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners(eventName: E): ((...args: WritableEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: WritableEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean | undefined; + readableObjectMode?: boolean | undefined; + writableObjectMode?: boolean | undefined; + readableHighWaterMark?: number | undefined; + writableHighWaterMark?: number | undefined; + writableCorked?: number | undefined; + } + interface DuplexEventMap extends ReadableEventMap, WritableEventMap {} + /** + * Duplex streams are streams that implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Duplex` streams include: + * + * * `TCP sockets` + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ + class Duplex extends Stream implements NodeJS.ReadWriteStream { + constructor(options?: DuplexOptions); + /** + * A utility method for creating duplex streams. + * + * - `Stream` converts writable stream into writable `Duplex` and readable stream + * to `Duplex`. + * - `Blob` converts into readable `Duplex`. + * - `string` converts into readable `Duplex`. + * - `ArrayBuffer` converts into readable `Duplex`. + * - `AsyncIterable` converts into a readable `Duplex`. Cannot yield `null`. + * - `AsyncGeneratorFunction` converts into a readable/writable transform + * `Duplex`. Must take a source `AsyncIterable` as first parameter. Cannot yield + * `null`. + * - `AsyncFunction` converts into a writable `Duplex`. Must return + * either `null` or `undefined` + * - `Object ({ writable, readable })` converts `readable` and + * `writable` into `Stream` and then combines them into `Duplex` where the + * `Duplex` will write to the `writable` and read from the `readable`. + * - `Promise` converts into readable `Duplex`. Value `null` is ignored. + * + * @since v16.8.0 + */ + static from( + src: + | NodeJS.ReadableStream + | NodeJS.WritableStream + | Blob + | string + | Iterable + | AsyncIterable + | ((source: AsyncIterable) => AsyncIterable) + | ((source: AsyncIterable) => Promise) + | Promise + | web.ReadableWritablePair + | web.ReadableStream + | web.WritableStream, + ): Duplex; + /** + * A utility method for creating a web `ReadableStream` and `WritableStream` from a `Duplex`. + * @since v17.0.0 + */ + static toWeb(streamDuplex: NodeJS.ReadWriteStream): web.ReadableWritablePair; + /** + * A utility method for creating a `Duplex` from a web `ReadableStream` and `WritableStream`. + * @since v17.0.0 + */ + static fromWeb( + duplexStream: web.ReadableWritablePair, + options?: Pick< + DuplexOptions, + "allowHalfOpen" | "decodeStrings" | "encoding" | "highWaterMark" | "objectMode" | "signal" + >, + ): Duplex; + /** + * If `false` then the stream will automatically end the writable side when the + * readable side ends. Set initially by the `allowHalfOpen` constructor option, + * which defaults to `true`. + * + * This can be changed manually to change the half-open behavior of an existing + * `Duplex` stream instance, but must be changed before the `'end'` event is emitted. + * @since v0.9.4 + */ + allowHalfOpen: boolean; + // #region InternalEventEmitter + addListener( + eventName: E, + listener: (...args: DuplexEventMap[E]) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: DuplexEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: DuplexEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners(eventName: E): ((...args: DuplexEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off(eventName: E, listener: (...args: DuplexEventMap[E]) => void): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on(eventName: E, listener: (...args: DuplexEventMap[E]) => void): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once(eventName: E, listener: (...args: DuplexEventMap[E]) => void): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: DuplexEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: DuplexEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners(eventName: E): ((...args: DuplexEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: DuplexEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + interface Duplex extends Readable, Writable {} + /** + * The utility function `duplexPair` returns an Array with two items, + * each being a `Duplex` stream connected to the other side: + * + * ```js + * const [ sideA, sideB ] = duplexPair(); + * ``` + * + * Whatever is written to one stream is made readable on the other. It provides + * behavior analogous to a network connection, where the data written by the client + * becomes readable by the server, and vice-versa. + * + * The Duplex streams are symmetrical; one or the other may be used without any + * difference in behavior. + * @param options A value to pass to both {@link Duplex} constructors, + * to set options such as buffering. + * @since v22.6.0 + */ + function duplexPair(options?: DuplexOptions): [Duplex, Duplex]; + type TransformCallback = (error?: Error | null, data?: any) => void; + interface TransformOptions extends DuplexOptions { + transform?: + | ((this: T, chunk: any, encoding: BufferEncoding, callback: TransformCallback) => void) + | undefined; + flush?: ((this: T, callback: TransformCallback) => void) | undefined; + } + /** + * Transform streams are `Duplex` streams where the output is in some way + * related to the input. Like all `Duplex` streams, `Transform` streams + * implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Transform` streams include: + * + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ + class Transform extends Duplex { + constructor(options?: TransformOptions); + _transform(chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; + _flush(callback: TransformCallback): void; + } + /** + * The `stream.PassThrough` class is a trivial implementation of a `Transform` stream that simply passes the input bytes across to the output. Its purpose is + * primarily for examples and testing, but there are some use cases where `stream.PassThrough` is useful as a building block for novel sorts of streams. + */ + class PassThrough extends Transform {} + /** + * A stream to attach a signal to. + * + * Attaches an AbortSignal to a readable or writeable stream. This lets code + * control stream destruction using an `AbortController`. + * + * Calling `abort` on the `AbortController` corresponding to the passed `AbortSignal` will behave the same way as calling `.destroy(new AbortError())` on the + * stream, and `controller.error(new AbortError())` for webstreams. + * + * ```js + * import fs from 'node:fs'; + * + * const controller = new AbortController(); + * const read = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')), + * ); + * // Later, abort the operation closing the stream + * controller.abort(); + * ``` + * + * Or using an `AbortSignal` with a readable stream as an async iterable: + * + * ```js + * const controller = new AbortController(); + * setTimeout(() => controller.abort(), 10_000); // set a timeout + * const stream = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')), + * ); + * (async () => { + * try { + * for await (const chunk of stream) { + * await process(chunk); + * } + * } catch (e) { + * if (e.name === 'AbortError') { + * // The operation was cancelled + * } else { + * throw e; + * } + * } + * })(); + * ``` + * + * Or using an `AbortSignal` with a ReadableStream: + * + * ```js + * const controller = new AbortController(); + * const rs = new ReadableStream({ + * start(controller) { + * controller.enqueue('hello'); + * controller.enqueue('world'); + * controller.close(); + * }, + * }); + * + * addAbortSignal(controller.signal, rs); + * + * finished(rs, (err) => { + * if (err) { + * if (err.name === 'AbortError') { + * // The operation was cancelled + * } + * } + * }); + * + * const reader = rs.getReader(); + * + * reader.read().then(({ value, done }) => { + * console.log(value); // hello + * console.log(done); // false + * controller.abort(); + * }); + * ``` + * @since v15.4.0 + * @param signal A signal representing possible cancellation + * @param stream A stream to attach a signal to. + */ + function addAbortSignal< + T extends NodeJS.ReadableStream | NodeJS.WritableStream | web.ReadableStream | web.WritableStream, + >(signal: AbortSignal, stream: T): T; + /** + * Returns the default highWaterMark used by streams. + * Defaults to `65536` (64 KiB), or `16` for `objectMode`. + * @since v19.9.0 + */ + function getDefaultHighWaterMark(objectMode: boolean): number; + /** + * Sets the default highWaterMark used by streams. + * @since v19.9.0 + * @param value highWaterMark value + */ + function setDefaultHighWaterMark(objectMode: boolean, value: number): void; + interface FinishedOptions extends Abortable { + error?: boolean | undefined; + readable?: boolean | undefined; + writable?: boolean | undefined; + } + /** + * A readable and/or writable stream/webstream. + * + * A function to get notified when a stream is no longer readable, writable + * or has experienced an error or a premature close event. + * + * ```js + * import { finished } from 'node:stream'; + * import fs from 'node:fs'; + * + * const rs = fs.createReadStream('archive.tar'); + * + * finished(rs, (err) => { + * if (err) { + * console.error('Stream failed.', err); + * } else { + * console.log('Stream is done reading.'); + * } + * }); + * + * rs.resume(); // Drain the stream. + * ``` + * + * Especially useful in error handling scenarios where a stream is destroyed + * prematurely (like an aborted HTTP request), and will not emit `'end'` or `'finish'`. + * + * The `finished` API provides [`promise version`](https://nodejs.org/docs/latest-v25.x/api/stream.html#streamfinishedstream-options). + * + * `stream.finished()` leaves dangling event listeners (in particular `'error'`, `'end'`, `'finish'` and `'close'`) after `callback` has been + * invoked. The reason for this is so that unexpected `'error'` events (due to + * incorrect stream implementations) do not cause unexpected crashes. + * If this is unwanted behavior then the returned cleanup function needs to be + * invoked in the callback: + * + * ```js + * const cleanup = finished(rs, (err) => { + * cleanup(); + * // ... + * }); + * ``` + * @since v10.0.0 + * @param stream A readable and/or writable stream. + * @param callback A callback function that takes an optional error argument. + * @returns A cleanup function which removes all registered listeners. + */ + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | web.ReadableStream | web.WritableStream, + options: FinishedOptions, + callback: (err?: NodeJS.ErrnoException | null) => void, + ): () => void; + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | web.ReadableStream | web.WritableStream, + callback: (err?: NodeJS.ErrnoException | null) => void, + ): () => void; + namespace finished { + import __promisify__ = promises.finished; + export { __promisify__ }; + } + type PipelineSourceFunction = (options?: Abortable) => Iterable | AsyncIterable; + type PipelineSource = + | NodeJS.ReadableStream + | web.ReadableStream + | web.TransformStream + | Iterable + | AsyncIterable + | PipelineSourceFunction; + type PipelineSourceArgument = (T extends (...args: any[]) => infer R ? R : T) extends infer S + ? S extends web.TransformStream ? web.ReadableStream : S + : never; + type PipelineTransformGenerator, O> = ( + source: PipelineSourceArgument, + options?: Abortable, + ) => AsyncIterable; + type PipelineTransformStreams = + | NodeJS.ReadWriteStream + | web.TransformStream; + type PipelineTransform, O> = S extends + PipelineSource | PipelineTransformStreams | ((...args: any[]) => infer I) + ? PipelineTransformStreams | PipelineTransformGenerator + : never; + type PipelineTransformSource = PipelineSource | PipelineTransform; + type PipelineDestinationFunction, R> = ( + source: PipelineSourceArgument, + options?: Abortable, + ) => R; + type PipelineDestination, R> = S extends + PipelineSource | PipelineTransform ? + | NodeJS.WritableStream + | web.WritableStream + | web.TransformStream + | PipelineDestinationFunction + : never; + type PipelineCallback> = ( + err: NodeJS.ErrnoException | null, + value: S extends (...args: any[]) => PromiseLike ? R : undefined, + ) => void; + type PipelineResult> = S extends NodeJS.WritableStream ? S : Duplex; + /** + * A module method to pipe between streams and generators forwarding errors and + * properly cleaning up and provide a callback when the pipeline is complete. + * + * ```js + * import { pipeline } from 'node:stream'; + * import fs from 'node:fs'; + * import zlib from 'node:zlib'; + * + * // Use the pipeline API to easily pipe a series of streams + * // together and get notified when the pipeline is fully done. + * + * // A pipeline to gzip a potentially huge tar file efficiently: + * + * pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz'), + * (err) => { + * if (err) { + * console.error('Pipeline failed.', err); + * } else { + * console.log('Pipeline succeeded.'); + * } + * }, + * ); + * ``` + * + * The `pipeline` API provides a [`promise version`](https://nodejs.org/docs/latest-v25.x/api/stream.html#streampipelinesource-transforms-destination-options). + * + * `stream.pipeline()` will call `stream.destroy(err)` on all streams except: + * + * * `Readable` streams which have emitted `'end'` or `'close'`. + * * `Writable` streams which have emitted `'finish'` or `'close'`. + * + * `stream.pipeline()` leaves dangling event listeners on the streams + * after the `callback` has been invoked. In the case of reuse of streams after + * failure, this can cause event listener leaks and swallowed errors. If the last + * stream is readable, dangling event listeners will be removed so that the last + * stream can be consumed later. + * + * `stream.pipeline()` closes all the streams when an error is raised. + * The `IncomingRequest` usage with `pipeline` could lead to an unexpected behavior + * once it would destroy the socket without sending the expected response. + * See the example below: + * + * ```js + * import fs from 'node:fs'; + * import http from 'node:http'; + * import { pipeline } from 'node:stream'; + * + * const server = http.createServer((req, res) => { + * const fileStream = fs.createReadStream('./fileNotExist.txt'); + * pipeline(fileStream, res, (err) => { + * if (err) { + * console.log(err); // No such file + * // this message can't be sent once `pipeline` already destroyed the socket + * return res.end('error!!!'); + * } + * }); + * }); + * ``` + * @since v10.0.0 + * @param callback Called when the pipeline is fully done. + */ + function pipeline, D extends PipelineDestination>( + source: S, + destination: D, + callback: PipelineCallback, + ): PipelineResult; + function pipeline< + S extends PipelineSource, + T extends PipelineTransform, + D extends PipelineDestination, + >( + source: S, + transform: T, + destination: D, + callback: PipelineCallback, + ): PipelineResult; + function pipeline< + S extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + D extends PipelineDestination, + >( + source: S, + transform1: T1, + transform2: T2, + destination: D, + callback: PipelineCallback, + ): PipelineResult; + function pipeline< + S extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + D extends PipelineDestination, + >( + source: S, + transform1: T1, + transform2: T2, + transform3: T3, + destination: D, + callback: PipelineCallback, + ): PipelineResult; + function pipeline< + S extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + D extends PipelineDestination, + >( + source: S, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: D, + callback: PipelineCallback, + ): PipelineResult; + function pipeline( + streams: ReadonlyArray | PipelineTransform | PipelineDestination>, + callback: (err: NodeJS.ErrnoException | null) => void, + ): NodeJS.WritableStream; + function pipeline( + ...streams: [ + ...[PipelineSource, ...PipelineTransform[], PipelineDestination], + callback: ((err: NodeJS.ErrnoException | null) => void), + ] + ): NodeJS.WritableStream; + namespace pipeline { + import __promisify__ = promises.pipeline; + export { __promisify__ }; + } + type ComposeSource = + | NodeJS.ReadableStream + | web.ReadableStream + | Iterable + | AsyncIterable + | (() => AsyncIterable); + type ComposeTransformStreams = NodeJS.ReadWriteStream | web.TransformStream; + type ComposeTransformGenerator = (source: AsyncIterable) => AsyncIterable; + type ComposeTransform, O> = S extends + ComposeSource | ComposeTransformStreams | ComposeTransformGenerator + ? ComposeTransformStreams | ComposeTransformGenerator + : never; + type ComposeTransformSource = ComposeSource | ComposeTransform; + type ComposeDestination> = S extends ComposeTransformSource ? + | NodeJS.WritableStream + | web.WritableStream + | web.TransformStream + | ((source: AsyncIterable) => void) + : never; + /** + * Combines two or more streams into a `Duplex` stream that writes to the + * first stream and reads from the last. Each provided stream is piped into + * the next, using `stream.pipeline`. If any of the streams error then all + * are destroyed, including the outer `Duplex` stream. + * + * Because `stream.compose` returns a new stream that in turn can (and + * should) be piped into other streams, it enables composition. In contrast, + * when passing streams to `stream.pipeline`, typically the first stream is + * a readable stream and the last a writable stream, forming a closed + * circuit. + * + * If passed a `Function` it must be a factory method taking a `source` + * `Iterable`. + * + * ```js + * import { compose, Transform } from 'node:stream'; + * + * const removeSpaces = new Transform({ + * transform(chunk, encoding, callback) { + * callback(null, String(chunk).replace(' ', '')); + * }, + * }); + * + * async function* toUpper(source) { + * for await (const chunk of source) { + * yield String(chunk).toUpperCase(); + * } + * } + * + * let res = ''; + * for await (const buf of compose(removeSpaces, toUpper).end('hello world')) { + * res += buf; + * } + * + * console.log(res); // prints 'HELLOWORLD' + * ``` + * + * `stream.compose` can be used to convert async iterables, generators and + * functions into streams. + * + * * `AsyncIterable` converts into a readable `Duplex`. Cannot yield + * `null`. + * * `AsyncGeneratorFunction` converts into a readable/writable transform `Duplex`. + * Must take a source `AsyncIterable` as first parameter. Cannot yield + * `null`. + * * `AsyncFunction` converts into a writable `Duplex`. Must return + * either `null` or `undefined`. + * + * ```js + * import { compose } from 'node:stream'; + * import { finished } from 'node:stream/promises'; + * + * // Convert AsyncIterable into readable Duplex. + * const s1 = compose(async function*() { + * yield 'Hello'; + * yield 'World'; + * }()); + * + * // Convert AsyncGenerator into transform Duplex. + * const s2 = compose(async function*(source) { + * for await (const chunk of source) { + * yield String(chunk).toUpperCase(); + * } + * }); + * + * let res = ''; + * + * // Convert AsyncFunction into writable Duplex. + * const s3 = compose(async function(source) { + * for await (const chunk of source) { + * res += chunk; + * } + * }); + * + * await finished(compose(s1, s2, s3)); + * + * console.log(res); // prints 'HELLOWORLD' + * ``` + * + * See [`readable.compose(stream)`](https://nodejs.org/docs/latest-v25.x/api/stream.html#readablecomposestream-options) for `stream.compose` as operator. + * @since v16.9.0 + * @experimental + */ + /* eslint-disable @definitelytyped/no-unnecessary-generics */ + function compose(stream: ComposeSource | ComposeDestination): Duplex; + function compose< + S extends ComposeSource | ComposeTransform, + D extends ComposeTransform | ComposeDestination, + >( + source: S, + destination: D, + ): Duplex; + function compose< + S extends ComposeSource | ComposeTransform, + T extends ComposeTransform, + D extends ComposeTransform | ComposeDestination, + >(source: S, transform: T, destination: D): Duplex; + function compose< + S extends ComposeSource | ComposeTransform, + T1 extends ComposeTransform, + T2 extends ComposeTransform, + D extends ComposeTransform | ComposeDestination, + >(source: S, transform1: T1, transform2: T2, destination: D): Duplex; + function compose< + S extends ComposeSource | ComposeTransform, + T1 extends ComposeTransform, + T2 extends ComposeTransform, + T3 extends ComposeTransform, + D extends ComposeTransform | ComposeDestination, + >(source: S, transform1: T1, transform2: T2, transform3: T3, destination: D): Duplex; + function compose< + S extends ComposeSource | ComposeTransform, + T1 extends ComposeTransform, + T2 extends ComposeTransform, + T3 extends ComposeTransform, + T4 extends ComposeTransform, + D extends ComposeTransform | ComposeDestination, + >(source: S, transform1: T1, transform2: T2, transform3: T3, transform4: T4, destination: D): Duplex; + function compose( + ...streams: [ + ComposeSource, + ...ComposeTransform[], + ComposeDestination, + ] + ): Duplex; + /* eslint-enable @definitelytyped/no-unnecessary-generics */ + /** + * Returns whether the stream has encountered an error. + * @since v17.3.0, v16.14.0 + */ + function isErrored( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | web.ReadableStream | web.WritableStream, + ): boolean; + /** + * Returns whether the stream is readable. + * @since v17.4.0, v16.14.0 + * @returns Only returns `null` if `stream` is not a valid `Readable`, `Duplex` or `ReadableStream`. + */ + function isReadable(stream: NodeJS.ReadableStream | web.ReadableStream): boolean | null; + /** + * Returns whether the stream is writable. + * @since v20.0.0 + * @returns Only returns `null` if `stream` is not a valid `Writable`, `Duplex` or `WritableStream`. + */ + function isWritable(stream: NodeJS.WritableStream | web.WritableStream): boolean | null; + } + global { + namespace NodeJS { + // These interfaces are vestigial, and correspond roughly to the "streams2" interfaces + // from early versions of Node.js, but they are still used widely across the ecosystem. + // Accordingly, they are commonly used as "in-types" for @types/node APIs, so that + // eg. streams returned from older libraries will still be considered valid input to + // functions which accept stream arguments. + // It's not possible to change or remove these without astronomical levels of breakage. + interface ReadableStream extends EventEmitter { + readable: boolean; + read(size?: number): string | Buffer; + setEncoding(encoding: BufferEncoding): this; + pause(): this; + resume(): this; + isPaused(): boolean; + pipe(destination: T, options?: { end?: boolean | undefined }): T; + unpipe(destination?: WritableStream): this; + unshift(chunk: string | Uint8Array, encoding?: BufferEncoding): void; + wrap(oldStream: ReadableStream): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + interface WritableStream extends EventEmitter { + writable: boolean; + write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean; + write(str: string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean; + end(cb?: () => void): this; + end(data: string | Uint8Array, cb?: () => void): this; + end(str: string, encoding?: BufferEncoding, cb?: () => void): this; + } + interface ReadWriteStream extends ReadableStream, WritableStream {} + } + } + export = Stream; +} +declare module "stream" { + import stream = require("node:stream"); + export = stream; +} diff --git a/backend/node_modules/@types/node/stream/consumers.d.ts b/backend/node_modules/@types/node/stream/consumers.d.ts new file mode 100644 index 0000000..97f260d --- /dev/null +++ b/backend/node_modules/@types/node/stream/consumers.d.ts @@ -0,0 +1,38 @@ +/** + * The utility consumer functions provide common options for consuming + * streams. + * @since v16.7.0 + */ +declare module "node:stream/consumers" { + import { Blob, NonSharedBuffer } from "node:buffer"; + import { ReadableStream } from "node:stream/web"; + /** + * @since v16.7.0 + * @returns Fulfills with an `ArrayBuffer` containing the full contents of the stream. + */ + function arrayBuffer(stream: ReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; + /** + * @since v16.7.0 + * @returns Fulfills with a `Blob` containing the full contents of the stream. + */ + function blob(stream: ReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; + /** + * @since v16.7.0 + * @returns Fulfills with a `Buffer` containing the full contents of the stream. + */ + function buffer(stream: ReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; + /** + * @since v16.7.0 + * @returns Fulfills with the contents of the stream parsed as a + * UTF-8 encoded string that is then passed through `JSON.parse()`. + */ + function json(stream: ReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; + /** + * @since v16.7.0 + * @returns Fulfills with the contents of the stream parsed as a UTF-8 encoded string. + */ + function text(stream: ReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; +} +declare module "stream/consumers" { + export * from "node:stream/consumers"; +} diff --git a/backend/node_modules/@types/node/stream/promises.d.ts b/backend/node_modules/@types/node/stream/promises.d.ts new file mode 100644 index 0000000..c4bd3ea --- /dev/null +++ b/backend/node_modules/@types/node/stream/promises.d.ts @@ -0,0 +1,211 @@ +declare module "node:stream/promises" { + import { Abortable } from "node:events"; + import { + FinishedOptions as _FinishedOptions, + PipelineDestination, + PipelineSource, + PipelineTransform, + } from "node:stream"; + import { ReadableStream, WritableStream } from "node:stream/web"; + interface FinishedOptions extends _FinishedOptions { + /** + * If true, removes the listeners registered by this function before the promise is fulfilled. + * @default false + */ + cleanup?: boolean | undefined; + } + /** + * ```js + * import { finished } from 'node:stream/promises'; + * import { createReadStream } from 'node:fs'; + * + * const rs = createReadStream('archive.tar'); + * + * async function run() { + * await finished(rs); + * console.log('Stream is done reading.'); + * } + * + * run().catch(console.error); + * rs.resume(); // Drain the stream. + * ``` + * + * The `finished` API also provides a [callback version](https://nodejs.org/docs/latest-v25.x/api/stream.html#streamfinishedstream-options-callback). + * + * `stream.finished()` leaves dangling event listeners (in particular + * `'error'`, `'end'`, `'finish'` and `'close'`) after the returned promise is + * resolved or rejected. The reason for this is so that unexpected `'error'` + * events (due to incorrect stream implementations) do not cause unexpected + * crashes. If this is unwanted behavior then `options.cleanup` should be set to + * `true`: + * + * ```js + * await finished(rs, { cleanup: true }); + * ``` + * @since v15.0.0 + * @returns Fulfills when the stream is no longer readable or writable. + */ + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | ReadableStream | WritableStream, + options?: FinishedOptions, + ): Promise; + interface PipelineOptions extends Abortable { + end?: boolean | undefined; + } + type PipelineResult> = S extends (...args: any[]) => PromiseLike + ? Promise + : Promise; + /** + * ```js + * import { pipeline } from 'node:stream/promises'; + * import { createReadStream, createWriteStream } from 'node:fs'; + * import { createGzip } from 'node:zlib'; + * + * await pipeline( + * createReadStream('archive.tar'), + * createGzip(), + * createWriteStream('archive.tar.gz'), + * ); + * console.log('Pipeline succeeded.'); + * ``` + * + * To use an `AbortSignal`, pass it inside an options object, as the last argument. + * When the signal is aborted, `destroy` will be called on the underlying pipeline, + * with an `AbortError`. + * + * ```js + * import { pipeline } from 'node:stream/promises'; + * import { createReadStream, createWriteStream } from 'node:fs'; + * import { createGzip } from 'node:zlib'; + * + * const ac = new AbortController(); + * const { signal } = ac; + * setImmediate(() => ac.abort()); + * try { + * await pipeline( + * createReadStream('archive.tar'), + * createGzip(), + * createWriteStream('archive.tar.gz'), + * { signal }, + * ); + * } catch (err) { + * console.error(err); // AbortError + * } + * ``` + * + * The `pipeline` API also supports async generators: + * + * ```js + * import { pipeline } from 'node:stream/promises'; + * import { createReadStream, createWriteStream } from 'node:fs'; + * + * await pipeline( + * createReadStream('lowercase.txt'), + * async function* (source, { signal }) { + * source.setEncoding('utf8'); // Work with strings rather than `Buffer`s. + * for await (const chunk of source) { + * yield await processChunk(chunk, { signal }); + * } + * }, + * createWriteStream('uppercase.txt'), + * ); + * console.log('Pipeline succeeded.'); + * ``` + * + * Remember to handle the `signal` argument passed into the async generator. + * Especially in the case where the async generator is the source for the + * pipeline (i.e. first argument) or the pipeline will never complete. + * + * ```js + * import { pipeline } from 'node:stream/promises'; + * import fs from 'node:fs'; + * await pipeline( + * async function* ({ signal }) { + * await someLongRunningfn({ signal }); + * yield 'asd'; + * }, + * fs.createWriteStream('uppercase.txt'), + * ); + * console.log('Pipeline succeeded.'); + * ``` + * + * The `pipeline` API provides [callback version](https://nodejs.org/docs/latest-v25.x/api/stream.html#streampipelinesource-transforms-destination-callback): + * @since v15.0.0 + * @returns Fulfills when the pipeline is complete. + */ + function pipeline, B extends PipelineDestination>( + source: A, + destination: B, + options?: PipelineOptions, + ): PipelineResult; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions, + ): PipelineResult; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions, + ): PipelineResult; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + options?: PipelineOptions, + ): PipelineResult; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + options?: PipelineOptions, + ): PipelineResult; + function pipeline( + streams: readonly [PipelineSource, ...PipelineTransform[], PipelineDestination], + options?: PipelineOptions, + ): Promise; + function pipeline( + ...streams: [PipelineSource, ...PipelineTransform[], PipelineDestination] + ): Promise; + function pipeline( + ...streams: [ + PipelineSource, + ...PipelineTransform[], + PipelineDestination, + options: PipelineOptions, + ] + ): Promise; +} +declare module "stream/promises" { + export * from "node:stream/promises"; +} diff --git a/backend/node_modules/@types/node/stream/web.d.ts b/backend/node_modules/@types/node/stream/web.d.ts new file mode 100644 index 0000000..32ce406 --- /dev/null +++ b/backend/node_modules/@types/node/stream/web.d.ts @@ -0,0 +1,296 @@ +declare module "node:stream/web" { + import { TextDecoderCommon, TextDecoderOptions, TextEncoderCommon } from "node:util"; + type CompressionFormat = "brotli" | "deflate" | "deflate-raw" | "gzip"; + type ReadableStreamController = ReadableStreamDefaultController | ReadableByteStreamController; + type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader; + type ReadableStreamReaderMode = "byob"; + type ReadableStreamReadResult = ReadableStreamReadValueResult | ReadableStreamReadDoneResult; + type ReadableStreamType = "bytes"; + interface GenericTransformStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + interface QueuingStrategy { + highWaterMark?: number; + size?: QueuingStrategySize; + } + interface QueuingStrategyInit { + highWaterMark: number; + } + interface QueuingStrategySize { + (chunk: T): number; + } + interface ReadableStreamBYOBReaderReadOptions { + min?: number; + } + interface ReadableStreamGenericReader { + readonly closed: Promise; + cancel(reason?: any): Promise; + } + interface ReadableStreamGetReaderOptions { + mode?: ReadableStreamReaderMode; + } + interface ReadableStreamIteratorOptions { + preventCancel?: boolean; + } + interface ReadableStreamReadDoneResult { + done: true; + value: T | undefined; + } + interface ReadableStreamReadValueResult { + done: false; + value: T; + } + interface ReadableWritablePair { + readable: ReadableStream; + writable: WritableStream; + } + interface StreamPipeOptions { + preventAbort?: boolean; + preventCancel?: boolean; + preventClose?: boolean; + signal?: AbortSignal; + } + interface Transformer { + flush?: TransformerFlushCallback; + readableType?: undefined; + start?: TransformerStartCallback; + transform?: TransformerTransformCallback; + writableType?: undefined; + } + interface TransformerFlushCallback { + (controller: TransformStreamDefaultController): void | PromiseLike; + } + interface TransformerStartCallback { + (controller: TransformStreamDefaultController): any; + } + interface TransformerTransformCallback { + (chunk: I, controller: TransformStreamDefaultController): void | PromiseLike; + } + interface UnderlyingByteSource { + autoAllocateChunkSize?: number; + cancel?: UnderlyingSourceCancelCallback; + pull?: (controller: ReadableByteStreamController) => void | PromiseLike; + start?: (controller: ReadableByteStreamController) => any; + type: "bytes"; + } + interface UnderlyingDefaultSource { + cancel?: UnderlyingSourceCancelCallback; + pull?: (controller: ReadableStreamDefaultController) => void | PromiseLike; + start?: (controller: ReadableStreamDefaultController) => any; + type?: undefined; + } + interface UnderlyingSink { + abort?: UnderlyingSinkAbortCallback; + close?: UnderlyingSinkCloseCallback; + start?: UnderlyingSinkStartCallback; + type?: undefined; + write?: UnderlyingSinkWriteCallback; + } + interface UnderlyingSinkAbortCallback { + (reason?: any): void | PromiseLike; + } + interface UnderlyingSinkCloseCallback { + (): void | PromiseLike; + } + interface UnderlyingSinkStartCallback { + (controller: WritableStreamDefaultController): any; + } + interface UnderlyingSinkWriteCallback { + (chunk: W, controller: WritableStreamDefaultController): void | PromiseLike; + } + interface UnderlyingSource { + autoAllocateChunkSize?: number; + cancel?: UnderlyingSourceCancelCallback; + pull?: UnderlyingSourcePullCallback; + start?: UnderlyingSourceStartCallback; + type?: ReadableStreamType; + } + interface UnderlyingSourceCancelCallback { + (reason?: any): void | PromiseLike; + } + interface UnderlyingSourcePullCallback { + (controller: ReadableStreamController): void | PromiseLike; + } + interface UnderlyingSourceStartCallback { + (controller: ReadableStreamController): any; + } + interface ByteLengthQueuingStrategy extends QueuingStrategy { + readonly highWaterMark: number; + readonly size: QueuingStrategySize; + } + var ByteLengthQueuingStrategy: { + prototype: ByteLengthQueuingStrategy; + new(init: QueuingStrategyInit): ByteLengthQueuingStrategy; + }; + interface CompressionStream extends GenericTransformStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + var CompressionStream: { + prototype: CompressionStream; + new(format: CompressionFormat): CompressionStream; + }; + interface CountQueuingStrategy extends QueuingStrategy { + readonly highWaterMark: number; + readonly size: QueuingStrategySize; + } + var CountQueuingStrategy: { + prototype: CountQueuingStrategy; + new(init: QueuingStrategyInit): CountQueuingStrategy; + }; + interface DecompressionStream extends GenericTransformStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + var DecompressionStream: { + prototype: DecompressionStream; + new(format: CompressionFormat): DecompressionStream; + }; + interface ReadableByteStreamController { + readonly byobRequest: ReadableStreamBYOBRequest | null; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: NodeJS.NonSharedArrayBufferView): void; + error(e?: any): void; + } + var ReadableByteStreamController: { + prototype: ReadableByteStreamController; + new(): ReadableByteStreamController; + }; + interface ReadableStream { + readonly locked: boolean; + cancel(reason?: any): Promise; + getReader(options: { mode: "byob" }): ReadableStreamBYOBReader; + getReader(): ReadableStreamDefaultReader; + getReader(options?: ReadableStreamGetReaderOptions): ReadableStreamReader; + pipeThrough(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; + pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; + tee(): [ReadableStream, ReadableStream]; + [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator; + values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator; + } + var ReadableStream: { + prototype: ReadableStream; + new( + underlyingSource: UnderlyingByteSource, + strategy?: { highWaterMark?: number }, + ): ReadableStream; + new(underlyingSource: UnderlyingDefaultSource, strategy?: QueuingStrategy): ReadableStream; + new(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; + from(iterable: Iterable | AsyncIterable): ReadableStream; + }; + interface ReadableStreamAsyncIterator extends NodeJS.AsyncIterator { + [Symbol.asyncIterator](): ReadableStreamAsyncIterator; + } + interface ReadableStreamBYOBReader extends ReadableStreamGenericReader { + read( + view: T, + options?: ReadableStreamBYOBReaderReadOptions, + ): Promise>; + releaseLock(): void; + } + var ReadableStreamBYOBReader: { + prototype: ReadableStreamBYOBReader; + new(stream: ReadableStream): ReadableStreamBYOBReader; + }; + interface ReadableStreamBYOBRequest { + readonly view: NodeJS.NonSharedArrayBufferView | null; + respond(bytesWritten: number): void; + respondWithNewView(view: NodeJS.NonSharedArrayBufferView): void; + } + var ReadableStreamBYOBRequest: { + prototype: ReadableStreamBYOBRequest; + new(): ReadableStreamBYOBRequest; + }; + interface ReadableStreamDefaultController { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk?: R): void; + error(e?: any): void; + } + var ReadableStreamDefaultController: { + prototype: ReadableStreamDefaultController; + new(): ReadableStreamDefaultController; + }; + interface ReadableStreamDefaultReader extends ReadableStreamGenericReader { + read(): Promise>; + releaseLock(): void; + } + var ReadableStreamDefaultReader: { + prototype: ReadableStreamDefaultReader; + new(stream: ReadableStream): ReadableStreamDefaultReader; + }; + interface TextDecoderStream extends GenericTransformStream, TextDecoderCommon { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + var TextDecoderStream: { + prototype: TextDecoderStream; + new(label?: string, options?: TextDecoderOptions): TextDecoderStream; + }; + interface TextEncoderStream extends GenericTransformStream, TextEncoderCommon { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + var TextEncoderStream: { + prototype: TextEncoderStream; + new(): TextEncoderStream; + }; + interface TransformStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + var TransformStream: { + prototype: TransformStream; + new( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ): TransformStream; + }; + interface TransformStreamDefaultController { + readonly desiredSize: number | null; + enqueue(chunk?: O): void; + error(reason?: any): void; + terminate(): void; + } + var TransformStreamDefaultController: { + prototype: TransformStreamDefaultController; + new(): TransformStreamDefaultController; + }; + interface WritableStream { + readonly locked: boolean; + abort(reason?: any): Promise; + close(): Promise; + getWriter(): WritableStreamDefaultWriter; + } + var WritableStream: { + prototype: WritableStream; + new(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy): WritableStream; + }; + interface WritableStreamDefaultController { + readonly signal: AbortSignal; + error(e?: any): void; + } + var WritableStreamDefaultController: { + prototype: WritableStreamDefaultController; + new(): WritableStreamDefaultController; + }; + interface WritableStreamDefaultWriter { + readonly closed: Promise; + readonly desiredSize: number | null; + readonly ready: Promise; + abort(reason?: any): Promise; + close(): Promise; + releaseLock(): void; + write(chunk?: W): Promise; + } + var WritableStreamDefaultWriter: { + prototype: WritableStreamDefaultWriter; + new(stream: WritableStream): WritableStreamDefaultWriter; + }; +} +declare module "stream/web" { + export * from "node:stream/web"; +} diff --git a/backend/node_modules/@types/node/string_decoder.d.ts b/backend/node_modules/@types/node/string_decoder.d.ts new file mode 100644 index 0000000..a72c374 --- /dev/null +++ b/backend/node_modules/@types/node/string_decoder.d.ts @@ -0,0 +1,67 @@ +/** + * The `node:string_decoder` module provides an API for decoding `Buffer` objects + * into strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16 + * characters. It can be accessed using: + * + * ```js + * import { StringDecoder } from 'node:string_decoder'; + * ``` + * + * The following example shows the basic use of the `StringDecoder` class. + * + * ```js + * import { StringDecoder } from 'node:string_decoder'; + * const decoder = new StringDecoder('utf8'); + * + * const cent = Buffer.from([0xC2, 0xA2]); + * console.log(decoder.write(cent)); // Prints: ¢ + * + * const euro = Buffer.from([0xE2, 0x82, 0xAC]); + * console.log(decoder.write(euro)); // Prints: € + * ``` + * + * When a `Buffer` instance is written to the `StringDecoder` instance, an + * internal buffer is used to ensure that the decoded string does not contain + * any incomplete multibyte characters. These are held in the buffer until the + * next call to `stringDecoder.write()` or until `stringDecoder.end()` is called. + * + * In the following example, the three UTF-8 encoded bytes of the European Euro + * symbol (`€`) are written over three separate operations: + * + * ```js + * import { StringDecoder } from 'node:string_decoder'; + * const decoder = new StringDecoder('utf8'); + * + * decoder.write(Buffer.from([0xE2])); + * decoder.write(Buffer.from([0x82])); + * console.log(decoder.end(Buffer.from([0xAC]))); // Prints: € + * ``` + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/string_decoder.js) + */ +declare module "node:string_decoder" { + class StringDecoder { + constructor(encoding?: BufferEncoding); + /** + * Returns a decoded string, ensuring that any incomplete multibyte characters at + * the end of the `Buffer`, or `TypedArray`, or `DataView` are omitted from the + * returned string and stored in an internal buffer for the next call to `stringDecoder.write()` or `stringDecoder.end()`. + * @since v0.1.99 + * @param buffer The bytes to decode. + */ + write(buffer: string | NodeJS.ArrayBufferView): string; + /** + * Returns any remaining input stored in the internal buffer as a string. Bytes + * representing incomplete UTF-8 and UTF-16 characters will be replaced with + * substitution characters appropriate for the character encoding. + * + * If the `buffer` argument is provided, one final call to `stringDecoder.write()` is performed before returning the remaining input. + * After `end()` is called, the `stringDecoder` object can be reused for new input. + * @since v0.9.3 + * @param buffer The bytes to decode. + */ + end(buffer?: string | NodeJS.ArrayBufferView): string; + } +} +declare module "string_decoder" { + export * from "node:string_decoder"; +} diff --git a/backend/node_modules/@types/node/test.d.ts b/backend/node_modules/@types/node/test.d.ts new file mode 100644 index 0000000..12d1af3 --- /dev/null +++ b/backend/node_modules/@types/node/test.d.ts @@ -0,0 +1,2239 @@ +/** + * The `node:test` module facilitates the creation of JavaScript tests. + * To access it: + * + * ```js + * import test from 'node:test'; + * ``` + * + * This module is only available under the `node:` scheme. The following will not + * work: + * + * ```js + * import test from 'node:test'; + * ``` + * + * Tests created via the `test` module consist of a single function that is + * processed in one of three ways: + * + * 1. A synchronous function that is considered failing if it throws an exception, + * and is considered passing otherwise. + * 2. A function that returns a `Promise` that is considered failing if the `Promise` rejects, and is considered passing if the `Promise` fulfills. + * 3. A function that receives a callback function. If the callback receives any + * truthy value as its first argument, the test is considered failing. If a + * falsy value is passed as the first argument to the callback, the test is + * considered passing. If the test function receives a callback function and + * also returns a `Promise`, the test will fail. + * + * The following example illustrates how tests are written using the `test` module. + * + * ```js + * test('synchronous passing test', (t) => { + * // This test passes because it does not throw an exception. + * assert.strictEqual(1, 1); + * }); + * + * test('synchronous failing test', (t) => { + * // This test fails because it throws an exception. + * assert.strictEqual(1, 2); + * }); + * + * test('asynchronous passing test', async (t) => { + * // This test passes because the Promise returned by the async + * // function is settled and not rejected. + * assert.strictEqual(1, 1); + * }); + * + * test('asynchronous failing test', async (t) => { + * // This test fails because the Promise returned by the async + * // function is rejected. + * assert.strictEqual(1, 2); + * }); + * + * test('failing test using Promises', (t) => { + * // Promises can be used directly as well. + * return new Promise((resolve, reject) => { + * setImmediate(() => { + * reject(new Error('this will cause the test to fail')); + * }); + * }); + * }); + * + * test('callback passing test', (t, done) => { + * // done() is the callback function. When the setImmediate() runs, it invokes + * // done() with no arguments. + * setImmediate(done); + * }); + * + * test('callback failing test', (t, done) => { + * // When the setImmediate() runs, done() is invoked with an Error object and + * // the test fails. + * setImmediate(() => { + * done(new Error('callback failure')); + * }); + * }); + * ``` + * + * If any tests fail, the process exit code is set to `1`. + * @since v18.0.0, v16.17.0 + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/test.js) + */ +declare module "node:test" { + import { AssertMethodNames } from "node:assert"; + import { Readable, ReadableEventMap } from "node:stream"; + import { TestEvent } from "node:test/reporters"; + import TestFn = test.TestFn; + import TestOptions = test.TestOptions; + /** + * The `test()` function is the value imported from the `test` module. Each + * invocation of this function results in reporting the test to the `TestsStream`. + * + * The `TestContext` object passed to the `fn` argument can be used to perform + * actions related to the current test. Examples include skipping the test, adding + * additional diagnostic information, or creating subtests. + * + * `test()` returns a `Promise` that fulfills once the test completes. + * if `test()` is called within a suite, it fulfills immediately. + * The return value can usually be discarded for top level tests. + * However, the return value from subtests should be used to prevent the parent + * test from finishing first and cancelling the subtest + * as shown in the following example. + * + * ```js + * test('top level test', async (t) => { + * // The setTimeout() in the following subtest would cause it to outlive its + * // parent test if 'await' is removed on the next line. Once the parent test + * // completes, it will cancel any outstanding subtests. + * await t.test('longer running subtest', async (t) => { + * return new Promise((resolve, reject) => { + * setTimeout(resolve, 1000); + * }); + * }); + * }); + * ``` + * + * The `timeout` option can be used to fail the test if it takes longer than `timeout` milliseconds to complete. However, it is not a reliable mechanism for + * canceling tests because a running test might block the application thread and + * thus prevent the scheduled cancellation. + * @since v18.0.0, v16.17.0 + * @param name The name of the test, which is displayed when reporting test results. + * Defaults to the `name` property of `fn`, or `''` if `fn` does not have a name. + * @param options Configuration options for the test. + * @param fn The function under test. The first argument to this function is a {@link TestContext} object. + * If the test uses callbacks, the callback function is passed as the second argument. + * @return Fulfilled with `undefined` once the test completes, or immediately if the test runs within a suite. + */ + function test(name?: string, fn?: TestFn): Promise; + function test(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function test(options?: TestOptions, fn?: TestFn): Promise; + function test(fn?: TestFn): Promise; + namespace test { + export { test }; + export { suite as describe, test as it }; + } + namespace test { + /** + * **Note:** `shard` is used to horizontally parallelize test running across + * machines or processes, ideal for large-scale executions across varied + * environments. It's incompatible with `watch` mode, tailored for rapid + * code iteration by automatically rerunning tests on file changes. + * + * ```js + * import { tap } from 'node:test/reporters'; + * import { run } from 'node:test'; + * import process from 'node:process'; + * import path from 'node:path'; + * + * run({ files: [path.resolve('./tests/test.js')] }) + * .compose(tap) + * .pipe(process.stdout); + * ``` + * @since v18.9.0, v16.19.0 + * @param options Configuration options for running tests. + */ + function run(options?: RunOptions): TestsStream; + /** + * The `suite()` function is imported from the `node:test` module. + * @param name The name of the suite, which is displayed when reporting test results. + * Defaults to the `name` property of `fn`, or `''` if `fn` does not have a name. + * @param options Configuration options for the suite. This supports the same options as {@link test}. + * @param fn The suite function declaring nested tests and suites. The first argument to this function is a {@link SuiteContext} object. + * @return Immediately fulfilled with `undefined`. + * @since v20.13.0 + */ + function suite(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function suite(name?: string, fn?: SuiteFn): Promise; + function suite(options?: TestOptions, fn?: SuiteFn): Promise; + function suite(fn?: SuiteFn): Promise; + namespace suite { + /** + * Shorthand for skipping a suite. This is the same as calling {@link suite} with `options.skip` set to `true`. + * @since v20.13.0 + */ + function skip(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function skip(name?: string, fn?: SuiteFn): Promise; + function skip(options?: TestOptions, fn?: SuiteFn): Promise; + function skip(fn?: SuiteFn): Promise; + /** + * Shorthand for marking a suite as `TODO`. This is the same as calling {@link suite} with `options.todo` set to `true`. + * @since v20.13.0 + */ + function todo(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function todo(name?: string, fn?: SuiteFn): Promise; + function todo(options?: TestOptions, fn?: SuiteFn): Promise; + function todo(fn?: SuiteFn): Promise; + /** + * Shorthand for marking a suite as `only`. This is the same as calling {@link suite} with `options.only` set to `true`. + * @since v20.13.0 + */ + function only(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function only(name?: string, fn?: SuiteFn): Promise; + function only(options?: TestOptions, fn?: SuiteFn): Promise; + function only(fn?: SuiteFn): Promise; + } + /** + * Shorthand for skipping a test. This is the same as calling {@link test} with `options.skip` set to `true`. + * @since v20.2.0 + */ + function skip(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function skip(name?: string, fn?: TestFn): Promise; + function skip(options?: TestOptions, fn?: TestFn): Promise; + function skip(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `TODO`. This is the same as calling {@link test} with `options.todo` set to `true`. + * @since v20.2.0 + */ + function todo(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function todo(name?: string, fn?: TestFn): Promise; + function todo(options?: TestOptions, fn?: TestFn): Promise; + function todo(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `only`. This is the same as calling {@link test} with `options.only` set to `true`. + * @since v20.2.0 + */ + function only(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function only(name?: string, fn?: TestFn): Promise; + function only(options?: TestOptions, fn?: TestFn): Promise; + function only(fn?: TestFn): Promise; + /** + * The type of a function passed to {@link test}. The first argument to this function is a {@link TestContext} object. + * If the test uses callbacks, the callback function is passed as the second argument. + */ + type TestFn = (t: TestContext, done: (result?: any) => void) => void | Promise; + /** + * The type of a suite test function. The argument to this function is a {@link SuiteContext} object. + */ + type SuiteFn = (s: SuiteContext) => void | Promise; + interface TestShard { + /** + * A positive integer between 1 and `total` that specifies the index of the shard to run. + */ + index: number; + /** + * A positive integer that specifies the total number of shards to split the test files to. + */ + total: number; + } + interface RunOptions { + /** + * If a number is provided, then that many test processes would run in parallel, where each process corresponds to one test file. + * If `true`, it would run `os.availableParallelism() - 1` test files in parallel. If `false`, it would only run one test file at a time. + * @default false + */ + concurrency?: number | boolean | undefined; + /** + * Specifies the current working directory to be used by the test runner. + * Serves as the base path for resolving files according to the + * [test runner execution model](https://nodejs.org/docs/latest-v25.x/api/test.html#test-runner-execution-model). + * @since v23.0.0 + * @default process.cwd() + */ + cwd?: string | undefined; + /** + * An array containing the list of files to run. If omitted, files are run according to the + * [test runner execution model](https://nodejs.org/docs/latest-v25.x/api/test.html#test-runner-execution-model). + */ + files?: readonly string[] | undefined; + /** + * Configures the test runner to exit the process once all known + * tests have finished executing even if the event loop would + * otherwise remain active. + * @default false + */ + forceExit?: boolean | undefined; + /** + * An array containing the list of glob patterns to match test files. + * This option cannot be used together with `files`. If omitted, files are run according to the + * [test runner execution model](https://nodejs.org/docs/latest-v25.x/api/test.html#test-runner-execution-model). + * @since v22.6.0 + */ + globPatterns?: readonly string[] | undefined; + /** + * Sets inspector port of test child process. + * This can be a number, or a function that takes no arguments and returns a + * number. If a nullish value is provided, each process gets its own port, + * incremented from the primary's `process.debugPort`. This option is ignored + * if the `isolation` option is set to `'none'` as no child processes are + * spawned. + * @default undefined + */ + inspectPort?: number | (() => number) | undefined; + /** + * Configures the type of test isolation. If set to + * `'process'`, each test file is run in a separate child process. If set to + * `'none'`, all test files run in the current process. + * @default 'process' + * @since v22.8.0 + */ + isolation?: "process" | "none" | undefined; + /** + * If truthy, the test context will only run tests that have the `only` option set + */ + only?: boolean | undefined; + /** + * A function that accepts the `TestsStream` instance and can be used to setup listeners before any tests are run. + * @default undefined + */ + setup?: ((reporter: TestsStream) => void | Promise) | undefined; + /** + * An array of CLI flags to pass to the `node` executable when + * spawning the subprocesses. This option has no effect when `isolation` is `'none`'. + * @since v22.10.0 + * @default [] + */ + execArgv?: readonly string[] | undefined; + /** + * An array of CLI flags to pass to each test file when spawning the + * subprocesses. This option has no effect when `isolation` is `'none'`. + * @since v22.10.0 + * @default [] + */ + argv?: readonly string[] | undefined; + /** + * Allows aborting an in-progress test execution. + */ + signal?: AbortSignal | undefined; + /** + * If provided, only run tests whose name matches the provided pattern. + * Strings are interpreted as JavaScript regular expressions. + * @default undefined + */ + testNamePatterns?: string | RegExp | ReadonlyArray | undefined; + /** + * A String, RegExp or a RegExp Array, that can be used to exclude running tests whose + * name matches the provided pattern. Test name patterns are interpreted as JavaScript + * regular expressions. For each test that is executed, any corresponding test hooks, + * such as `beforeEach()`, are also run. + * @default undefined + * @since v22.1.0 + */ + testSkipPatterns?: string | RegExp | ReadonlyArray | undefined; + /** + * The number of milliseconds after which the test execution will fail. + * If unspecified, subtests inherit this value from their parent. + * @default Infinity + */ + timeout?: number | undefined; + /** + * Whether to run in watch mode or not. + * @default false + */ + watch?: boolean | undefined; + /** + * Running tests in a specific shard. + * @default undefined + */ + shard?: TestShard | undefined; + /** + * A file path where the test runner will + * store the state of the tests to allow rerunning only the failed tests on a next run. + * @since v24.7.0 + * @default undefined + */ + rerunFailuresFilePath?: string | undefined; + /** + * enable [code coverage](https://nodejs.org/docs/latest-v25.x/api/test.html#collecting-code-coverage) collection. + * @since v22.10.0 + * @default false + */ + coverage?: boolean | undefined; + /** + * Excludes specific files from code coverage + * using a glob pattern, which can match both absolute and relative file paths. + * This property is only applicable when `coverage` was set to `true`. + * If both `coverageExcludeGlobs` and `coverageIncludeGlobs` are provided, + * files must meet **both** criteria to be included in the coverage report. + * @since v22.10.0 + * @default undefined + */ + coverageExcludeGlobs?: string | readonly string[] | undefined; + /** + * Includes specific files in code coverage + * using a glob pattern, which can match both absolute and relative file paths. + * This property is only applicable when `coverage` was set to `true`. + * If both `coverageExcludeGlobs` and `coverageIncludeGlobs` are provided, + * files must meet **both** criteria to be included in the coverage report. + * @since v22.10.0 + * @default undefined + */ + coverageIncludeGlobs?: string | readonly string[] | undefined; + /** + * Require a minimum percent of covered lines. If code + * coverage does not reach the threshold specified, the process will exit with code `1`. + * @since v22.10.0 + * @default 0 + */ + lineCoverage?: number | undefined; + /** + * Require a minimum percent of covered branches. If code + * coverage does not reach the threshold specified, the process will exit with code `1`. + * @since v22.10.0 + * @default 0 + */ + branchCoverage?: number | undefined; + /** + * Require a minimum percent of covered functions. If code + * coverage does not reach the threshold specified, the process will exit with code `1`. + * @since v22.10.0 + * @default 0 + */ + functionCoverage?: number | undefined; + } + interface TestsStreamEventMap extends ReadableEventMap { + "data": [data: TestEvent]; + "test:coverage": [data: EventData.TestCoverage]; + "test:complete": [data: EventData.TestComplete]; + "test:dequeue": [data: EventData.TestDequeue]; + "test:diagnostic": [data: EventData.TestDiagnostic]; + "test:enqueue": [data: EventData.TestEnqueue]; + "test:fail": [data: EventData.TestFail]; + "test:pass": [data: EventData.TestPass]; + "test:plan": [data: EventData.TestPlan]; + "test:start": [data: EventData.TestStart]; + "test:stderr": [data: EventData.TestStderr]; + "test:stdout": [data: EventData.TestStdout]; + "test:summary": [data: EventData.TestSummary]; + "test:watch:drained": []; + "test:watch:restarted": []; + } + /** + * A successful call to `run()` will return a new `TestsStream` object, streaming a series of events representing the execution of the tests. + * + * Some of the events are guaranteed to be emitted in the same order as the tests are defined, while others are emitted in the order that the tests execute. + * @since v18.9.0, v16.19.0 + */ + interface TestsStream extends Readable { + // #region InternalEventEmitter + addListener( + eventName: E, + listener: (...args: TestsStreamEventMap[E]) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: TestsStreamEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: TestsStreamEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners(eventName: E): ((...args: TestsStreamEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off( + eventName: E, + listener: (...args: TestsStreamEventMap[E]) => void, + ): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on( + eventName: E, + listener: (...args: TestsStreamEventMap[E]) => void, + ): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: (...args: TestsStreamEventMap[E]) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: TestsStreamEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: TestsStreamEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners( + eventName: E, + ): ((...args: TestsStreamEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: TestsStreamEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + namespace EventData { + interface Error extends globalThis.Error { + cause: globalThis.Error; + } + interface LocationInfo { + /** + * The column number where the test is defined, or + * `undefined` if the test was run through the REPL. + */ + column?: number; + /** + * The path of the test file, `undefined` if test was run through the REPL. + */ + file?: string; + /** + * The line number where the test is defined, or `undefined` if the test was run through the REPL. + */ + line?: number; + } + interface TestDiagnostic extends LocationInfo { + /** + * The diagnostic message. + */ + message: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The severity level of the diagnostic message. + * Possible values are: + * * `'info'`: Informational messages. + * * `'warn'`: Warnings. + * * `'error'`: Errors. + */ + level: "info" | "warn" | "error"; + } + interface TestCoverage { + /** + * An object containing the coverage report. + */ + summary: { + /** + * An array of coverage reports for individual files. + */ + files: Array<{ + /** + * The absolute path of the file. + */ + path: string; + /** + * The total number of lines. + */ + totalLineCount: number; + /** + * The total number of branches. + */ + totalBranchCount: number; + /** + * The total number of functions. + */ + totalFunctionCount: number; + /** + * The number of covered lines. + */ + coveredLineCount: number; + /** + * The number of covered branches. + */ + coveredBranchCount: number; + /** + * The number of covered functions. + */ + coveredFunctionCount: number; + /** + * The percentage of lines covered. + */ + coveredLinePercent: number; + /** + * The percentage of branches covered. + */ + coveredBranchPercent: number; + /** + * The percentage of functions covered. + */ + coveredFunctionPercent: number; + /** + * An array of functions representing function coverage. + */ + functions: Array<{ + /** + * The name of the function. + */ + name: string; + /** + * The line number where the function is defined. + */ + line: number; + /** + * The number of times the function was called. + */ + count: number; + }>; + /** + * An array of branches representing branch coverage. + */ + branches: Array<{ + /** + * The line number where the branch is defined. + */ + line: number; + /** + * The number of times the branch was taken. + */ + count: number; + }>; + /** + * An array of lines representing line numbers and the number of times they were covered. + */ + lines: Array<{ + /** + * The line number. + */ + line: number; + /** + * The number of times the line was covered. + */ + count: number; + }>; + }>; + /** + * An object containing whether or not the coverage for + * each coverage type. + * @since v22.9.0 + */ + thresholds: { + /** + * The function coverage threshold. + */ + function: number; + /** + * The branch coverage threshold. + */ + branch: number; + /** + * The line coverage threshold. + */ + line: number; + }; + /** + * An object containing a summary of coverage for all files. + */ + totals: { + /** + * The total number of lines. + */ + totalLineCount: number; + /** + * The total number of branches. + */ + totalBranchCount: number; + /** + * The total number of functions. + */ + totalFunctionCount: number; + /** + * The number of covered lines. + */ + coveredLineCount: number; + /** + * The number of covered branches. + */ + coveredBranchCount: number; + /** + * The number of covered functions. + */ + coveredFunctionCount: number; + /** + * The percentage of lines covered. + */ + coveredLinePercent: number; + /** + * The percentage of branches covered. + */ + coveredBranchPercent: number; + /** + * The percentage of functions covered. + */ + coveredFunctionPercent: number; + }; + /** + * The working directory when code coverage began. This + * is useful for displaying relative path names in case + * the tests changed the working directory of the Node.js process. + */ + workingDirectory: string; + }; + /** + * The nesting level of the test. + */ + nesting: number; + } + interface TestComplete extends LocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * Whether the test passed or not. + */ + passed: boolean; + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * An error wrapping the error thrown by the test if it did not pass. + */ + error?: Error; + /** + * The type of the test, used to denote whether this is a suite. + */ + type?: "suite" | "test"; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; + } + interface TestDequeue extends LocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The test type. Either `'suite'` or `'test'`. + * @since v22.15.0 + */ + type: "suite" | "test"; + } + interface TestEnqueue extends LocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The test type. Either `'suite'` or `'test'`. + * @since v22.15.0 + */ + type: "suite" | "test"; + } + interface TestFail extends LocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * An error wrapping the error thrown by the test. + */ + error: Error; + /** + * The type of the test, used to denote whether this is a suite. + * @since v20.0.0, v19.9.0, v18.17.0 + */ + type?: "suite" | "test"; + /** + * The attempt number of the test run, + * present only when using the `--test-rerun-failures` flag. + * @since v24.7.0 + */ + attempt?: number; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; + } + interface TestPass extends LocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * The type of the test, used to denote whether this is a suite. + * @since 20.0.0, 19.9.0, 18.17.0 + */ + type?: "suite" | "test"; + /** + * The attempt number of the test run, + * present only when using the `--test-rerun-failures` flag. + * @since v24.7.0 + */ + attempt?: number; + /** + * The attempt number the test passed on, + * present only when using the `--test-rerun-failures` flag. + * @since v24.7.0 + */ + passed_on_attempt?: number; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; + } + interface TestPlan extends LocationInfo { + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The number of subtests that have ran. + */ + count: number; + } + interface TestStart extends LocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + } + interface TestStderr { + /** + * The path of the test file. + */ + file: string; + /** + * The message written to `stderr`. + */ + message: string; + } + interface TestStdout { + /** + * The path of the test file. + */ + file: string; + /** + * The message written to `stdout`. + */ + message: string; + } + interface TestSummary { + /** + * An object containing the counts of various test results. + */ + counts: { + /** + * The total number of cancelled tests. + */ + cancelled: number; + /** + * The total number of passed tests. + */ + passed: number; + /** + * The total number of skipped tests. + */ + skipped: number; + /** + * The total number of suites run. + */ + suites: number; + /** + * The total number of tests run, excluding suites. + */ + tests: number; + /** + * The total number of TODO tests. + */ + todo: number; + /** + * The total number of top level tests and suites. + */ + topLevel: number; + }; + /** + * The duration of the test run in milliseconds. + */ + duration_ms: number; + /** + * The path of the test file that generated the + * summary. If the summary corresponds to multiple files, this value is + * `undefined`. + */ + file: string | undefined; + /** + * Indicates whether or not the test run is considered + * successful or not. If any error condition occurs, such as a failing test or + * unmet coverage threshold, this value will be set to `false`. + */ + success: boolean; + } + } + /** + * An instance of `TestContext` is passed to each test function in order to + * interact with the test runner. However, the `TestContext` constructor is not + * exposed as part of the API. + * @since v18.0.0, v16.17.0 + */ + interface TestContext { + /** + * An object containing assertion methods bound to the test context. + * The top-level functions from the `node:assert` module are exposed here for the purpose of creating test plans. + * + * **Note:** Some of the functions from `node:assert` contain type assertions. If these are called via the + * TestContext `assert` object, then the context parameter in the test's function signature **must be explicitly typed** + * (ie. the parameter must have a type annotation), otherwise an error will be raised by the TypeScript compiler: + * ```ts + * import { test, type TestContext } from 'node:test'; + * + * // The test function's context parameter must have a type annotation. + * test('example', (t: TestContext) => { + * t.assert.deepStrictEqual(actual, expected); + * }); + * + * // Omitting the type annotation will result in a compilation error. + * test('example', t => { + * t.assert.deepStrictEqual(actual, expected); // Error: 't' needs an explicit type annotation. + * }); + * ``` + * @since v22.2.0, v20.15.0 + */ + readonly assert: TestContextAssert; + readonly attempt: number; + /** + * This function is used to create a hook running before subtest of the current test. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v20.1.0, v18.17.0 + */ + before(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to create a hook running before each subtest of the current test. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + beforeEach(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to create a hook that runs after the current test finishes. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v18.13.0 + */ + after(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to create a hook running after each subtest of the current test. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + afterEach(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to write diagnostics to the output. Any diagnostic + * information is included at the end of the test's results. This function does + * not return a value. + * + * ```js + * test('top level test', (t) => { + * t.diagnostic('A diagnostic message'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Message to be reported. + */ + diagnostic(message: string): void; + /** + * The absolute path of the test file that created the current test. If a test file imports + * additional modules that generate tests, the imported tests will return the path of the root test file. + * @since v22.6.0 + */ + readonly filePath: string | undefined; + /** + * The name of the test and each of its ancestors, separated by `>`. + * @since v22.3.0 + */ + readonly fullName: string; + /** + * The name of the test. + * @since v18.8.0, v16.18.0 + */ + readonly name: string; + /** + * This function is used to set the number of assertions and subtests that are expected to run + * within the test. If the number of assertions and subtests that run does not match the + * expected count, the test will fail. + * + * > Note: To make sure assertions are tracked, `t.assert` must be used instead of `assert` directly. + * + * ```js + * test('top level test', (t) => { + * t.plan(2); + * t.assert.ok('some relevant assertion here'); + * t.test('subtest', () => {}); + * }); + * ``` + * + * When working with asynchronous code, the `plan` function can be used to ensure that the + * correct number of assertions are run: + * + * ```js + * test('planning with streams', (t, done) => { + * function* generate() { + * yield 'a'; + * yield 'b'; + * yield 'c'; + * } + * const expected = ['a', 'b', 'c']; + * t.plan(expected.length); + * const stream = Readable.from(generate()); + * stream.on('data', (chunk) => { + * t.assert.strictEqual(chunk, expected.shift()); + * }); + * + * stream.on('end', () => { + * done(); + * }); + * }); + * ``` + * + * When using the `wait` option, you can control how long the test will wait for the expected assertions. + * For example, setting a maximum wait time ensures that the test will wait for asynchronous assertions + * to complete within the specified timeframe: + * + * ```js + * test('plan with wait: 2000 waits for async assertions', (t) => { + * t.plan(1, { wait: 2000 }); // Waits for up to 2 seconds for the assertion to complete. + * + * const asyncActivity = () => { + * setTimeout(() => { + * * t.assert.ok(true, 'Async assertion completed within the wait time'); + * }, 1000); // Completes after 1 second, within the 2-second wait time. + * }; + * + * asyncActivity(); // The test will pass because the assertion is completed in time. + * }); + * ``` + * + * Note: If a `wait` timeout is specified, it begins counting down only after the test function finishes executing. + * @since v22.2.0 + */ + plan(count: number, options?: TestContextPlanOptions): void; + /** + * If `shouldRunOnlyTests` is truthy, the test context will only run tests that + * have the `only` option set. Otherwise, all tests are run. If Node.js was not + * started with the `--test-only` command-line option, this function is a + * no-op. + * + * ```js + * test('top level test', (t) => { + * // The test context can be set to run subtests with the 'only' option. + * t.runOnly(true); + * return Promise.all([ + * t.test('this subtest is now skipped'), + * t.test('this subtest is run', { only: true }), + * ]); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param shouldRunOnlyTests Whether or not to run `only` tests. + */ + runOnly(shouldRunOnlyTests: boolean): void; + /** + * ```js + * test('top level test', async (t) => { + * await fetch('some/uri', { signal: t.signal }); + * }); + * ``` + * @since v18.7.0, v16.17.0 + */ + readonly signal: AbortSignal; + /** + * This function causes the test's output to indicate the test as skipped. If `message` is provided, it is included in the output. Calling `skip()` does + * not terminate execution of the test function. This function does not return a + * value. + * + * ```js + * test('top level test', (t) => { + * // Make sure to return here as well if the test contains additional logic. + * t.skip('this is skipped'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Optional skip message. + */ + skip(message?: string): void; + /** + * This function adds a `TODO` directive to the test's output. If `message` is + * provided, it is included in the output. Calling `todo()` does not terminate + * execution of the test function. This function does not return a value. + * + * ```js + * test('top level test', (t) => { + * // This test is marked as `TODO` + * t.todo('this is a todo'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Optional `TODO` message. + */ + todo(message?: string): void; + /** + * This function is used to create subtests under the current test. This function behaves in + * the same fashion as the top level {@link test} function. + * @since v18.0.0 + * @param name The name of the test, which is displayed when reporting test results. + * Defaults to the `name` property of `fn`, or `''` if `fn` does not have a name. + * @param options Configuration options for the test. + * @param fn The function under test. This first argument to this function is a {@link TestContext} object. + * If the test uses callbacks, the callback function is passed as the second argument. + * @returns A {@link Promise} resolved with `undefined` once the test completes. + */ + test: typeof test; + /** + * This method polls a `condition` function until that function either returns + * successfully or the operation times out. + * @since v22.14.0 + * @param condition An assertion function that is invoked + * periodically until it completes successfully or the defined polling timeout + * elapses. Successful completion is defined as not throwing or rejecting. This + * function does not accept any arguments, and is allowed to return any value. + * @param options An optional configuration object for the polling operation. + * @returns Fulfilled with the value returned by `condition`. + */ + waitFor(condition: () => T, options?: TestContextWaitForOptions): Promise>; + /** + * Each test provides its own MockTracker instance. + */ + readonly mock: MockTracker; + } + interface TestContextAssert extends Pick { + /** + * This function serializes `value` and writes it to the file specified by `path`. + * + * ```js + * test('snapshot test with default serialization', (t) => { + * t.assert.fileSnapshot({ value1: 1, value2: 2 }, './snapshots/snapshot.json'); + * }); + * ``` + * + * This function differs from `context.assert.snapshot()` in the following ways: + * + * * The snapshot file path is explicitly provided by the user. + * * Each snapshot file is limited to a single snapshot value. + * * No additional escaping is performed by the test runner. + * + * These differences allow snapshot files to better support features such as syntax + * highlighting. + * @since v22.14.0 + * @param value A value to serialize to a string. If Node.js was started with + * the [`--test-update-snapshots`](https://nodejs.org/docs/latest-v25.x/api/cli.html#--test-update-snapshots) + * flag, the serialized value is written to + * `path`. Otherwise, the serialized value is compared to the contents of the + * existing snapshot file. + * @param path The file where the serialized `value` is written. + * @param options Optional configuration options. + */ + fileSnapshot(value: any, path: string, options?: AssertSnapshotOptions): void; + /** + * This function implements assertions for snapshot testing. + * ```js + * test('snapshot test with default serialization', (t) => { + * t.assert.snapshot({ value1: 1, value2: 2 }); + * }); + * + * test('snapshot test with custom serialization', (t) => { + * t.assert.snapshot({ value3: 3, value4: 4 }, { + * serializers: [(value) => JSON.stringify(value)] + * }); + * }); + * ``` + * @since v22.3.0 + * @param value A value to serialize to a string. If Node.js was started with + * the [`--test-update-snapshots`](https://nodejs.org/docs/latest-v25.x/api/cli.html#--test-update-snapshots) + * flag, the serialized value is written to + * the snapshot file. Otherwise, the serialized value is compared to the + * corresponding value in the existing snapshot file. + */ + snapshot(value: any, options?: AssertSnapshotOptions): void; + /** + * A custom assertion function registered with `assert.register()`. + */ + [name: string]: (...args: any[]) => void; + } + interface AssertSnapshotOptions { + /** + * An array of synchronous functions used to serialize `value` into a string. + * `value` is passed as the only argument to the first serializer function. + * The return value of each serializer is passed as input to the next serializer. + * Once all serializers have run, the resulting value is coerced to a string. + * + * If no serializers are provided, the test runner's default serializers are used. + */ + serializers?: ReadonlyArray<(value: any) => any> | undefined; + } + interface TestContextPlanOptions { + /** + * The wait time for the plan: + * * If `true`, the plan waits indefinitely for all assertions and subtests to run. + * * If `false`, the plan performs an immediate check after the test function completes, + * without waiting for any pending assertions or subtests. + * Any assertions or subtests that complete after this check will not be counted towards the plan. + * * If a number, it specifies the maximum wait time in milliseconds + * before timing out while waiting for expected assertions and subtests to be matched. + * If the timeout is reached, the test will fail. + * @default false + */ + wait?: boolean | number | undefined; + } + interface TestContextWaitForOptions { + /** + * The number of milliseconds to wait after an unsuccessful + * invocation of `condition` before trying again. + * @default 50 + */ + interval?: number | undefined; + /** + * The poll timeout in milliseconds. If `condition` has not + * succeeded by the time this elapses, an error occurs. + * @default 1000 + */ + timeout?: number | undefined; + } + /** + * An instance of `SuiteContext` is passed to each suite function in order to + * interact with the test runner. However, the `SuiteContext` constructor is not + * exposed as part of the API. + * @since v18.7.0, v16.17.0 + */ + interface SuiteContext { + /** + * The absolute path of the test file that created the current suite. If a test file imports + * additional modules that generate suites, the imported suites will return the path of the root test file. + * @since v22.6.0 + */ + readonly filePath: string | undefined; + /** + * The name of the suite. + * @since v18.8.0, v16.18.0 + */ + readonly name: string; + /** + * Can be used to abort test subtasks when the test has been aborted. + * @since v18.7.0, v16.17.0 + */ + readonly signal: AbortSignal; + } + interface TestOptions { + /** + * If a number is provided, then that many tests would run in parallel. + * If truthy, it would run (number of cpu cores - 1) tests in parallel. + * For subtests, it will be `Infinity` tests in parallel. + * If falsy, it would only run one test at a time. + * If unspecified, subtests inherit this value from their parent. + * @default false + */ + concurrency?: number | boolean | undefined; + /** + * If truthy, and the test context is configured to run `only` tests, then this test will be + * run. Otherwise, the test is skipped. + * @default false + */ + only?: boolean | undefined; + /** + * Allows aborting an in-progress test. + * @since v18.8.0 + */ + signal?: AbortSignal | undefined; + /** + * If truthy, the test is skipped. If a string is provided, that string is displayed in the + * test results as the reason for skipping the test. + * @default false + */ + skip?: boolean | string | undefined; + /** + * A number of milliseconds the test will fail after. If unspecified, subtests inherit this + * value from their parent. + * @default Infinity + * @since v18.7.0 + */ + timeout?: number | undefined; + /** + * If truthy, the test marked as `TODO`. If a string is provided, that string is displayed in + * the test results as the reason why the test is `TODO`. + * @default false + */ + todo?: boolean | string | undefined; + /** + * The number of assertions and subtests expected to be run in the test. + * If the number of assertions run in the test does not match the number + * specified in the plan, the test will fail. + * @default undefined + * @since v22.2.0 + */ + plan?: number | undefined; + } + /** + * This function creates a hook that runs before executing a suite. + * + * ```js + * describe('tests', async () => { + * before(() => console.log('about to run some test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function before(fn?: HookFn, options?: HookOptions): void; + /** + * This function creates a hook that runs after executing a suite. + * + * ```js + * describe('tests', async () => { + * after(() => console.log('finished running tests')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function after(fn?: HookFn, options?: HookOptions): void; + /** + * This function creates a hook that runs before each test in the current suite. + * + * ```js + * describe('tests', async () => { + * beforeEach(() => console.log('about to run a test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function beforeEach(fn?: HookFn, options?: HookOptions): void; + /** + * This function creates a hook that runs after each test in the current suite. + * The `afterEach()` hook is run even if the test fails. + * + * ```js + * describe('tests', async () => { + * afterEach(() => console.log('finished running a test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function afterEach(fn?: HookFn, options?: HookOptions): void; + /** + * The hook function. The first argument is the context in which the hook is called. + * If the hook uses callbacks, the callback function is passed as the second argument. + */ + type HookFn = (c: TestContext | SuiteContext, done: (result?: any) => void) => any; + /** + * The hook function. The first argument is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + */ + type TestContextHookFn = (t: TestContext, done: (result?: any) => void) => any; + /** + * Configuration options for hooks. + * @since v18.8.0 + */ + interface HookOptions { + /** + * Allows aborting an in-progress hook. + */ + signal?: AbortSignal | undefined; + /** + * A number of milliseconds the hook will fail after. If unspecified, subtests inherit this + * value from their parent. + * @default Infinity + */ + timeout?: number | undefined; + } + interface MockFunctionOptions { + /** + * The number of times that the mock will use the behavior of `implementation`. + * Once the mock function has been called `times` times, + * it will automatically restore the behavior of `original`. + * This value must be an integer greater than zero. + * @default Infinity + */ + times?: number | undefined; + } + interface MockMethodOptions extends MockFunctionOptions { + /** + * If `true`, `object[methodName]` is treated as a getter. + * This option cannot be used with the `setter` option. + */ + getter?: boolean | undefined; + /** + * If `true`, `object[methodName]` is treated as a setter. + * This option cannot be used with the `getter` option. + */ + setter?: boolean | undefined; + } + type Mock = F & { + mock: MockFunctionContext; + }; + interface MockModuleOptions { + /** + * If false, each call to `require()` or `import()` generates a new mock module. + * If true, subsequent calls will return the same module mock, and the mock module is inserted into the CommonJS cache. + * @default false + */ + cache?: boolean | undefined; + /** + * The value to use as the mocked module's default export. + * + * If this value is not provided, ESM mocks do not include a default export. + * If the mock is a CommonJS or builtin module, this setting is used as the value of `module.exports`. + * If this value is not provided, CJS and builtin mocks use an empty object as the value of `module.exports`. + */ + defaultExport?: any; + /** + * An object whose keys and values are used to create the named exports of the mock module. + * + * If the mock is a CommonJS or builtin module, these values are copied onto `module.exports`. + * Therefore, if a mock is created with both named exports and a non-object default export, + * the mock will throw an exception when used as a CJS or builtin module. + */ + namedExports?: object | undefined; + } + /** + * The `MockTracker` class is used to manage mocking functionality. The test runner + * module provides a top level `mock` export which is a `MockTracker` instance. + * Each test also provides its own `MockTracker` instance via the test context's `mock` property. + * @since v19.1.0, v18.13.0 + */ + interface MockTracker { + /** + * This function is used to create a mock function. + * + * The following example creates a mock function that increments a counter by one + * on each invocation. The `times` option is used to modify the mock behavior such + * that the first two invocations add two to the counter instead of one. + * + * ```js + * test('mocks a counting function', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne, addTwo, { times: 2 }); + * + * assert.strictEqual(fn(), 2); + * assert.strictEqual(fn(), 4); + * assert.strictEqual(fn(), 5); + * assert.strictEqual(fn(), 6); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param original An optional function to create a mock on. + * @param implementation An optional function used as the mock implementation for `original`. This is useful for creating mocks that exhibit one behavior for a specified number of calls and + * then restore the behavior of `original`. + * @param options Optional configuration options for the mock function. + * @return The mocked function. The mocked function contains a special `mock` property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the + * behavior of the mocked function. + */ + fn undefined>( + original?: F, + options?: MockFunctionOptions, + ): Mock; + fn undefined, Implementation extends Function = F>( + original?: F, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock; + /** + * This function is used to create a mock on an existing object method. The + * following example demonstrates how a mock is created on an existing object + * method. + * + * ```js + * test('spies on an object method', (t) => { + * const number = { + * value: 5, + * subtract(a) { + * return this.value - a; + * }, + * }; + * + * t.mock.method(number, 'subtract'); + * assert.strictEqual(number.subtract.mock.calls.length, 0); + * assert.strictEqual(number.subtract(3), 2); + * assert.strictEqual(number.subtract.mock.calls.length, 1); + * + * const call = number.subtract.mock.calls[0]; + * + * assert.deepStrictEqual(call.arguments, [3]); + * assert.strictEqual(call.result, 2); + * assert.strictEqual(call.error, undefined); + * assert.strictEqual(call.target, undefined); + * assert.strictEqual(call.this, number); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param object The object whose method is being mocked. + * @param methodName The identifier of the method on `object` to mock. If `object[methodName]` is not a function, an error is thrown. + * @param implementation An optional function used as the mock implementation for `object[methodName]`. + * @param options Optional configuration options for the mock method. + * @return The mocked method. The mocked method contains a special `mock` property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the + * behavior of the mocked method. + */ + method< + MockedObject extends object, + MethodName extends FunctionPropertyNames, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): MockedObject[MethodName] extends Function ? Mock + : never; + method< + MockedObject extends object, + MethodName extends FunctionPropertyNames, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation: Implementation, + options?: MockFunctionOptions, + ): MockedObject[MethodName] extends Function ? Mock + : never; + method( + object: MockedObject, + methodName: keyof MockedObject, + options: MockMethodOptions, + ): Mock; + method( + object: MockedObject, + methodName: keyof MockedObject, + implementation: Function, + options: MockMethodOptions, + ): Mock; + /** + * This function is syntax sugar for `MockTracker.method` with `options.getter` set to `true`. + * @since v19.3.0, v18.13.0 + */ + getter< + MockedObject extends object, + MethodName extends keyof MockedObject, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): Mock<() => MockedObject[MethodName]>; + getter< + MockedObject extends object, + MethodName extends keyof MockedObject, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock<(() => MockedObject[MethodName]) | Implementation>; + /** + * This function is syntax sugar for `MockTracker.method` with `options.setter` set to `true`. + * @since v19.3.0, v18.13.0 + */ + setter< + MockedObject extends object, + MethodName extends keyof MockedObject, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): Mock<(value: MockedObject[MethodName]) => void>; + setter< + MockedObject extends object, + MethodName extends keyof MockedObject, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock<((value: MockedObject[MethodName]) => void) | Implementation>; + /** + * This function is used to mock the exports of ECMAScript modules, CommonJS modules, JSON modules, and + * Node.js builtin modules. Any references to the original module prior to mocking are not impacted. In + * order to enable module mocking, Node.js must be started with the + * [`--experimental-test-module-mocks`](https://nodejs.org/docs/latest-v25.x/api/cli.html#--experimental-test-module-mocks) + * command-line flag. + * + * The following example demonstrates how a mock is created for a module. + * + * ```js + * test('mocks a builtin module in both module systems', async (t) => { + * // Create a mock of 'node:readline' with a named export named 'fn', which + * // does not exist in the original 'node:readline' module. + * const mock = t.mock.module('node:readline', { + * namedExports: { fn() { return 42; } }, + * }); + * + * let esmImpl = await import('node:readline'); + * let cjsImpl = require('node:readline'); + * + * // cursorTo() is an export of the original 'node:readline' module. + * assert.strictEqual(esmImpl.cursorTo, undefined); + * assert.strictEqual(cjsImpl.cursorTo, undefined); + * assert.strictEqual(esmImpl.fn(), 42); + * assert.strictEqual(cjsImpl.fn(), 42); + * + * mock.restore(); + * + * // The mock is restored, so the original builtin module is returned. + * esmImpl = await import('node:readline'); + * cjsImpl = require('node:readline'); + * + * assert.strictEqual(typeof esmImpl.cursorTo, 'function'); + * assert.strictEqual(typeof cjsImpl.cursorTo, 'function'); + * assert.strictEqual(esmImpl.fn, undefined); + * assert.strictEqual(cjsImpl.fn, undefined); + * }); + * ``` + * @since v22.3.0 + * @experimental + * @param specifier A string identifying the module to mock. + * @param options Optional configuration options for the mock module. + */ + module(specifier: string, options?: MockModuleOptions): MockModuleContext; + /** + * Creates a mock for a property value on an object. This allows you to track and control access to a specific property, + * including how many times it is read (getter) or written (setter), and to restore the original value after mocking. + * + * ```js + * test('mocks a property value', (t) => { + * const obj = { foo: 42 }; + * const prop = t.mock.property(obj, 'foo', 100); + * + * assert.strictEqual(obj.foo, 100); + * assert.strictEqual(prop.mock.accessCount(), 1); + * assert.strictEqual(prop.mock.accesses[0].type, 'get'); + * assert.strictEqual(prop.mock.accesses[0].value, 100); + * + * obj.foo = 200; + * assert.strictEqual(prop.mock.accessCount(), 2); + * assert.strictEqual(prop.mock.accesses[1].type, 'set'); + * assert.strictEqual(prop.mock.accesses[1].value, 200); + * + * prop.mock.restore(); + * assert.strictEqual(obj.foo, 42); + * }); + * ``` + * @since v24.3.0 + * @param object The object whose value is being mocked. + * @param propertyName The identifier of the property on `object` to mock. + * @param value An optional value used as the mock value + * for `object[propertyName]`. **Default:** The original property value. + * @returns A proxy to the mocked object. The mocked object contains a + * special `mock` property, which is an instance of [`MockPropertyContext`][], and + * can be used for inspecting and changing the behavior of the mocked property. + */ + property< + MockedObject extends object, + PropertyName extends keyof MockedObject, + >( + object: MockedObject, + property: PropertyName, + value?: MockedObject[PropertyName], + ): MockedObject & { mock: MockPropertyContext }; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTracker` and disassociates the mocks from the `MockTracker` instance. Once disassociated, the mocks can still be used, but the `MockTracker` instance can no longer be + * used to reset their behavior or + * otherwise interact with them. + * + * After each test completes, this function is called on the test context's `MockTracker`. If the global `MockTracker` is used extensively, calling this + * function manually is recommended. + * @since v19.1.0, v18.13.0 + */ + reset(): void; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTracker`. Unlike `mock.reset()`, `mock.restoreAll()` does + * not disassociate the mocks from the `MockTracker` instance. + * @since v19.1.0, v18.13.0 + */ + restoreAll(): void; + readonly timers: MockTimers; + } + const mock: MockTracker; + interface MockFunctionCall< + F extends Function, + ReturnType = F extends (...args: any) => infer T ? T + : F extends abstract new(...args: any) => infer T ? T + : unknown, + Args = F extends (...args: infer Y) => any ? Y + : F extends abstract new(...args: infer Y) => any ? Y + : unknown[], + > { + /** + * An array of the arguments passed to the mock function. + */ + arguments: Args; + /** + * If the mocked function threw then this property contains the thrown value. + */ + error: unknown | undefined; + /** + * The value returned by the mocked function. + * + * If the mocked function threw, it will be `undefined`. + */ + result: ReturnType | undefined; + /** + * An `Error` object whose stack can be used to determine the callsite of the mocked function invocation. + */ + stack: Error; + /** + * If the mocked function is a constructor, this field contains the class being constructed. + * Otherwise this will be `undefined`. + */ + target: F extends abstract new(...args: any) => any ? F : undefined; + /** + * The mocked function's `this` value. + */ + this: unknown; + } + /** + * The `MockFunctionContext` class is used to inspect or manipulate the behavior of + * mocks created via the `MockTracker` APIs. + * @since v19.1.0, v18.13.0 + */ + interface MockFunctionContext { + /** + * A getter that returns a copy of the internal array used to track calls to the + * mock. Each entry in the array is an object with the following properties. + * @since v19.1.0, v18.13.0 + */ + readonly calls: MockFunctionCall[]; + /** + * This function returns the number of times that this mock has been invoked. This + * function is more efficient than checking `ctx.calls.length` because `ctx.calls` is a getter that creates a copy of the internal call tracking array. + * @since v19.1.0, v18.13.0 + * @return The number of times that this mock has been invoked. + */ + callCount(): number; + /** + * This function is used to change the behavior of an existing mock. + * + * The following example creates a mock function using `t.mock.fn()`, calls the + * mock function, and then changes the mock implementation to a different function. + * + * ```js + * test('changes a mock behavior', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne); + * + * assert.strictEqual(fn(), 1); + * fn.mock.mockImplementation(addTwo); + * assert.strictEqual(fn(), 3); + * assert.strictEqual(fn(), 5); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param implementation The function to be used as the mock's new implementation. + */ + mockImplementation(implementation: F): void; + /** + * This function is used to change the behavior of an existing mock for a single + * invocation. Once invocation `onCall` has occurred, the mock will revert to + * whatever behavior it would have used had `mockImplementationOnce()` not been + * called. + * + * The following example creates a mock function using `t.mock.fn()`, calls the + * mock function, changes the mock implementation to a different function for the + * next invocation, and then resumes its previous behavior. + * + * ```js + * test('changes a mock behavior once', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne); + * + * assert.strictEqual(fn(), 1); + * fn.mock.mockImplementationOnce(addTwo); + * assert.strictEqual(fn(), 3); + * assert.strictEqual(fn(), 4); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param implementation The function to be used as the mock's implementation for the invocation number specified by `onCall`. + * @param onCall The invocation number that will use `implementation`. If the specified invocation has already occurred then an exception is thrown. + */ + mockImplementationOnce(implementation: F, onCall?: number): void; + /** + * Resets the call history of the mock function. + * @since v19.3.0, v18.13.0 + */ + resetCalls(): void; + /** + * Resets the implementation of the mock function to its original behavior. The + * mock can still be used after calling this function. + * @since v19.1.0, v18.13.0 + */ + restore(): void; + } + /** + * @since v22.3.0 + * @experimental + */ + interface MockModuleContext { + /** + * Resets the implementation of the mock module. + * @since v22.3.0 + */ + restore(): void; + } + /** + * @since v24.3.0 + */ + class MockPropertyContext { + /** + * A getter that returns a copy of the internal array used to track accesses (get/set) to + * the mocked property. Each entry in the array is an object with the following properties: + */ + readonly accesses: Array<{ + type: "get" | "set"; + value: PropertyType; + stack: Error; + }>; + /** + * This function returns the number of times that the property was accessed. + * This function is more efficient than checking `ctx.accesses.length` because + * `ctx.accesses` is a getter that creates a copy of the internal access tracking array. + * @returns The number of times that the property was accessed (read or written). + */ + accessCount(): number; + /** + * This function is used to change the value returned by the mocked property getter. + * @param value The new value to be set as the mocked property value. + */ + mockImplementation(value: PropertyType): void; + /** + * This function is used to change the behavior of an existing mock for a single + * invocation. Once invocation `onAccess` has occurred, the mock will revert to + * whatever behavior it would have used had `mockImplementationOnce()` not been + * called. + * + * The following example creates a mock function using `t.mock.property()`, calls the + * mock property, changes the mock implementation to a different value for the + * next invocation, and then resumes its previous behavior. + * + * ```js + * test('changes a mock behavior once', (t) => { + * const obj = { foo: 1 }; + * + * const prop = t.mock.property(obj, 'foo', 5); + * + * assert.strictEqual(obj.foo, 5); + * prop.mock.mockImplementationOnce(25); + * assert.strictEqual(obj.foo, 25); + * assert.strictEqual(obj.foo, 5); + * }); + * ``` + * @param value The value to be used as the mock's + * implementation for the invocation number specified by `onAccess`. + * @param onAccess The invocation number that will use `value`. If + * the specified invocation has already occurred then an exception is thrown. + * **Default:** The number of the next invocation. + */ + mockImplementationOnce(value: PropertyType, onAccess?: number): void; + /** + * Resets the access history of the mocked property. + */ + resetAccesses(): void; + /** + * Resets the implementation of the mock property to its original behavior. The + * mock can still be used after calling this function. + */ + restore(): void; + } + interface MockTimersOptions { + apis: ReadonlyArray<"setInterval" | "setTimeout" | "setImmediate" | "Date">; + now?: number | Date | undefined; + } + /** + * Mocking timers is a technique commonly used in software testing to simulate and + * control the behavior of timers, such as `setInterval` and `setTimeout`, + * without actually waiting for the specified time intervals. + * + * The MockTimers API also allows for mocking of the `Date` constructor and + * `setImmediate`/`clearImmediate` functions. + * + * The `MockTracker` provides a top-level `timers` export + * which is a `MockTimers` instance. + * @since v20.4.0 + */ + interface MockTimers { + /** + * Enables timer mocking for the specified timers. + * + * **Note:** When you enable mocking for a specific timer, its associated + * clear function will also be implicitly mocked. + * + * **Note:** Mocking `Date` will affect the behavior of the mocked timers + * as they use the same internal clock. + * + * Example usage without setting initial time: + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable({ apis: ['setInterval', 'Date'], now: 1234 }); + * ``` + * + * The above example enables mocking for the `Date` constructor, `setInterval` timer and + * implicitly mocks the `clearInterval` function. Only the `Date` constructor from `globalThis`, + * `setInterval` and `clearInterval` functions from `node:timers`, `node:timers/promises`, and `globalThis` will be mocked. + * + * Example usage with initial time set + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable({ apis: ['Date'], now: 1000 }); + * ``` + * + * Example usage with initial Date object as time set + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable({ apis: ['Date'], now: new Date() }); + * ``` + * + * Alternatively, if you call `mock.timers.enable()` without any parameters: + * + * All timers (`'setInterval'`, `'clearInterval'`, `'Date'`, `'setImmediate'`, `'clearImmediate'`, `'setTimeout'`, and `'clearTimeout'`) + * will be mocked. + * + * The `setInterval`, `clearInterval`, `setTimeout`, and `clearTimeout` functions from `node:timers`, `node:timers/promises`, + * and `globalThis` will be mocked. + * The `Date` constructor from `globalThis` will be mocked. + * + * If there is no initial epoch set, the initial date will be based on 0 in the Unix epoch. This is `January 1st, 1970, 00:00:00 UTC`. You can + * set an initial date by passing a now property to the `.enable()` method. This value will be used as the initial date for the mocked Date + * object. It can either be a positive integer, or another Date object. + * @since v20.4.0 + */ + enable(options?: MockTimersOptions): void; + /** + * You can use the `.setTime()` method to manually move the mocked date to another time. This method only accepts a positive integer. + * Note: This method will execute any mocked timers that are in the past from the new time. + * In the below example we are setting a new time for the mocked date. + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * test('sets the time of a date object', (context) => { + * // Optionally choose what to mock + * context.mock.timers.enable({ apis: ['Date'], now: 100 }); + * assert.strictEqual(Date.now(), 100); + * // Advance in time will also advance the date + * context.mock.timers.setTime(1000); + * context.mock.timers.tick(200); + * assert.strictEqual(Date.now(), 1200); + * }); + * ``` + */ + setTime(time: number): void; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTimers` instance and disassociates the mocks + * from the `MockTracker` instance. + * + * **Note:** After each test completes, this function is called on + * the test context's `MockTracker`. + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.reset(); + * ``` + * @since v20.4.0 + */ + reset(): void; + /** + * Advances time for all mocked timers. + * + * **Note:** This diverges from how `setTimeout` in Node.js behaves and accepts + * only positive numbers. In Node.js, `setTimeout` with negative numbers is + * only supported for web compatibility reasons. + * + * The following example mocks a `setTimeout` function and + * by using `.tick` advances in + * time triggering all pending timers. + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * + * context.mock.timers.enable({ apis: ['setTimeout'] }); + * + * setTimeout(fn, 9999); + * + * assert.strictEqual(fn.mock.callCount(), 0); + * + * // Advance in time + * context.mock.timers.tick(9999); + * + * assert.strictEqual(fn.mock.callCount(), 1); + * }); + * ``` + * + * Alternativelly, the `.tick` function can be called many times + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * context.mock.timers.enable({ apis: ['setTimeout'] }); + * const nineSecs = 9000; + * setTimeout(fn, nineSecs); + * + * const twoSeconds = 3000; + * context.mock.timers.tick(twoSeconds); + * context.mock.timers.tick(twoSeconds); + * context.mock.timers.tick(twoSeconds); + * + * assert.strictEqual(fn.mock.callCount(), 1); + * }); + * ``` + * + * Advancing time using `.tick` will also advance the time for any `Date` object + * created after the mock was enabled (if `Date` was also set to be mocked). + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * + * context.mock.timers.enable({ apis: ['setTimeout', 'Date'] }); + * setTimeout(fn, 9999); + * + * assert.strictEqual(fn.mock.callCount(), 0); + * assert.strictEqual(Date.now(), 0); + * + * // Advance in time + * context.mock.timers.tick(9999); + * assert.strictEqual(fn.mock.callCount(), 1); + * assert.strictEqual(Date.now(), 9999); + * }); + * ``` + * @since v20.4.0 + */ + tick(milliseconds: number): void; + /** + * Triggers all pending mocked timers immediately. If the `Date` object is also + * mocked, it will also advance the `Date` object to the furthest timer's time. + * + * The example below triggers all pending timers immediately, + * causing them to execute without any delay. + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('runAll functions following the given order', (context) => { + * context.mock.timers.enable({ apis: ['setTimeout', 'Date'] }); + * const results = []; + * setTimeout(() => results.push(1), 9999); + * + * // Notice that if both timers have the same timeout, + * // the order of execution is guaranteed + * setTimeout(() => results.push(3), 8888); + * setTimeout(() => results.push(2), 8888); + * + * assert.deepStrictEqual(results, []); + * + * context.mock.timers.runAll(); + * assert.deepStrictEqual(results, [3, 2, 1]); + * // The Date object is also advanced to the furthest timer's time + * assert.strictEqual(Date.now(), 9999); + * }); + * ``` + * + * **Note:** The `runAll()` function is specifically designed for + * triggering timers in the context of timer mocking. + * It does not have any effect on real-time system + * clocks or actual timers outside of the mocking environment. + * @since v20.4.0 + */ + runAll(): void; + /** + * Calls {@link MockTimers.reset()}. + */ + [Symbol.dispose](): void; + } + /** + * An object whose methods are used to configure available assertions on the + * `TestContext` objects in the current process. The methods from `node:assert` + * and snapshot testing functions are available by default. + * + * It is possible to apply the same configuration to all files by placing common + * configuration code in a module + * preloaded with `--require` or `--import`. + * @since v22.14.0 + */ + namespace assert { + /** + * Defines a new assertion function with the provided name and function. If an + * assertion already exists with the same name, it is overwritten. + * @since v22.14.0 + */ + function register(name: string, fn: (this: TestContext, ...args: any[]) => void): void; + } + /** + * @since v22.3.0 + */ + namespace snapshot { + /** + * This function is used to customize the default serialization mechanism used by the test runner. + * + * By default, the test runner performs serialization by calling `JSON.stringify(value, null, 2)` on the provided value. + * `JSON.stringify()` does have limitations regarding circular structures and supported data types. + * If a more robust serialization mechanism is required, this function should be used to specify a list of custom serializers. + * + * Serializers are called in order, with the output of the previous serializer passed as input to the next. + * The final result must be a string value. + * @since v22.3.0 + * @param serializers An array of synchronous functions used as the default serializers for snapshot tests. + */ + function setDefaultSnapshotSerializers(serializers: ReadonlyArray<(value: any) => any>): void; + /** + * This function is used to set a custom resolver for the location of the snapshot file used for snapshot testing. + * By default, the snapshot filename is the same as the entry point filename with `.snapshot` appended. + * @since v22.3.0 + * @param fn A function used to compute the location of the snapshot file. + * The function receives the path of the test file as its only argument. If the + * test is not associated with a file (for example in the REPL), the input is + * undefined. `fn()` must return a string specifying the location of the snapshot file. + */ + function setResolveSnapshotPath(fn: (path: string | undefined) => string): void; + } + } + type FunctionPropertyNames = { + [K in keyof T]: T[K] extends Function ? K : never; + }[keyof T]; + export = test; +} diff --git a/backend/node_modules/@types/node/test/reporters.d.ts b/backend/node_modules/@types/node/test/reporters.d.ts new file mode 100644 index 0000000..465e80d --- /dev/null +++ b/backend/node_modules/@types/node/test/reporters.d.ts @@ -0,0 +1,96 @@ +/** + * The `node:test` module supports passing `--test-reporter` + * flags for the test runner to use a specific reporter. + * + * The following built-reporters are supported: + * + * * `spec` + * The `spec` reporter outputs the test results in a human-readable format. This + * is the default reporter. + * + * * `tap` + * The `tap` reporter outputs the test results in the [TAP](https://testanything.org/) format. + * + * * `dot` + * The `dot` reporter outputs the test results in a compact format, + * where each passing test is represented by a `.`, + * and each failing test is represented by a `X`. + * + * * `junit` + * The junit reporter outputs test results in a jUnit XML format + * + * * `lcov` + * The `lcov` reporter outputs test coverage when used with the + * `--experimental-test-coverage` flag. + * + * The exact output of these reporters is subject to change between versions of + * Node.js, and should not be relied on programmatically. If programmatic access + * to the test runner's output is required, use the events emitted by the + * `TestsStream`. + * + * The reporters are available via the `node:test/reporters` module: + * + * ```js + * import { tap, spec, dot, junit, lcov } from 'node:test/reporters'; + * ``` + * @since v19.9.0, v18.17.0 + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/test/reporters.js) + */ +declare module "node:test/reporters" { + import { Transform, TransformOptions } from "node:stream"; + import { EventData } from "node:test"; + type TestEvent = + | { type: "test:coverage"; data: EventData.TestCoverage } + | { type: "test:complete"; data: EventData.TestComplete } + | { type: "test:dequeue"; data: EventData.TestDequeue } + | { type: "test:diagnostic"; data: EventData.TestDiagnostic } + | { type: "test:enqueue"; data: EventData.TestEnqueue } + | { type: "test:fail"; data: EventData.TestFail } + | { type: "test:pass"; data: EventData.TestPass } + | { type: "test:plan"; data: EventData.TestPlan } + | { type: "test:start"; data: EventData.TestStart } + | { type: "test:stderr"; data: EventData.TestStderr } + | { type: "test:stdout"; data: EventData.TestStdout } + | { type: "test:summary"; data: EventData.TestSummary } + | { type: "test:watch:drained"; data: undefined } + | { type: "test:watch:restarted"; data: undefined }; + interface ReporterConstructorWrapper Transform> { + new(...args: ConstructorParameters): InstanceType; + (...args: ConstructorParameters): InstanceType; + } + /** + * The `dot` reporter outputs the test results in a compact format, + * where each passing test is represented by a `.`, + * and each failing test is represented by a `X`. + * @since v20.0.0 + */ + function dot(source: AsyncIterable): NodeJS.AsyncIterator; + /** + * The `tap` reporter outputs the test results in the [TAP](https://testanything.org/) format. + * @since v20.0.0 + */ + function tap(source: AsyncIterable): NodeJS.AsyncIterator; + class SpecReporter extends Transform { + constructor(); + } + /** + * The `spec` reporter outputs the test results in a human-readable format. + * @since v20.0.0 + */ + const spec: ReporterConstructorWrapper; + /** + * The `junit` reporter outputs test results in a jUnit XML format. + * @since v21.0.0 + */ + function junit(source: AsyncIterable): NodeJS.AsyncIterator; + class LcovReporter extends Transform { + constructor(options?: Omit); + } + /** + * The `lcov` reporter outputs test coverage when used with the + * [`--experimental-test-coverage`](https://nodejs.org/docs/latest-v25.x/api/cli.html#--experimental-test-coverage) flag. + * @since v22.0.0 + */ + const lcov: ReporterConstructorWrapper; + export { dot, junit, lcov, spec, tap, TestEvent }; +} diff --git a/backend/node_modules/@types/node/timers.d.ts b/backend/node_modules/@types/node/timers.d.ts new file mode 100644 index 0000000..00a8cd0 --- /dev/null +++ b/backend/node_modules/@types/node/timers.d.ts @@ -0,0 +1,159 @@ +/** + * The `timer` module exposes a global API for scheduling functions to + * be called at some future period of time. Because the timer functions are + * globals, there is no need to import `node:timers` to use the API. + * + * The timer functions within Node.js implement a similar API as the timers API + * provided by Web Browsers but use a different internal implementation that is + * built around the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout). + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/timers.js) + */ +declare module "node:timers" { + import { Abortable } from "node:events"; + import * as promises from "node:timers/promises"; + export interface TimerOptions extends Abortable { + /** + * Set to `false` to indicate that the scheduled `Timeout` + * should not require the Node.js event loop to remain active. + * @default true + */ + ref?: boolean | undefined; + } + global { + namespace NodeJS { + /** + * This object is created internally and is returned from `setImmediate()`. It + * can be passed to `clearImmediate()` in order to cancel the scheduled + * actions. + * + * By default, when an immediate is scheduled, the Node.js event loop will continue + * running as long as the immediate is active. The `Immediate` object returned by + * `setImmediate()` exports both `immediate.ref()` and `immediate.unref()` + * functions that can be used to control this default behavior. + */ + interface Immediate extends RefCounted, Disposable { + /** + * If true, the `Immediate` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + /** + * When called, requests that the Node.js event loop _not_ exit so long as the + * `Immediate` is active. Calling `immediate.ref()` multiple times will have no + * effect. + * + * By default, all `Immediate` objects are "ref'ed", making it normally unnecessary + * to call `immediate.ref()` unless `immediate.unref()` had been called previously. + * @since v9.7.0 + * @returns a reference to `immediate` + */ + ref(): this; + /** + * When called, the active `Immediate` object will not require the Node.js event + * loop to remain active. If there is no other activity keeping the event loop + * running, the process may exit before the `Immediate` object's callback is + * invoked. Calling `immediate.unref()` multiple times will have no effect. + * @since v9.7.0 + * @returns a reference to `immediate` + */ + unref(): this; + /** + * Cancels the immediate. This is similar to calling `clearImmediate()`. + * @since v20.5.0, v18.18.0 + */ + [Symbol.dispose](): void; + _onImmediate(...args: any[]): void; + } + // Legacy interface used in Node.js v9 and prior + // TODO: remove in a future major version bump + /** @deprecated Use `NodeJS.Timeout` instead. */ + interface Timer extends RefCounted { + hasRef(): boolean; + refresh(): this; + [Symbol.toPrimitive](): number; + } + /** + * This object is created internally and is returned from `setTimeout()` and + * `setInterval()`. It can be passed to either `clearTimeout()` or + * `clearInterval()` in order to cancel the scheduled actions. + * + * By default, when a timer is scheduled using either `setTimeout()` or + * `setInterval()`, the Node.js event loop will continue running as long as the + * timer is active. Each of the `Timeout` objects returned by these functions + * export both `timeout.ref()` and `timeout.unref()` functions that can be used to + * control this default behavior. + */ + interface Timeout extends RefCounted, Disposable, Timer { + /** + * Cancels the timeout. + * @since v0.9.1 + * @legacy Use `clearTimeout()` instead. + * @returns a reference to `timeout` + */ + close(): this; + /** + * If true, the `Timeout` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + /** + * When called, requests that the Node.js event loop _not_ exit so long as the + * `Timeout` is active. Calling `timeout.ref()` multiple times will have no effect. + * + * By default, all `Timeout` objects are "ref'ed", making it normally unnecessary + * to call `timeout.ref()` unless `timeout.unref()` had been called previously. + * @since v0.9.1 + * @returns a reference to `timeout` + */ + ref(): this; + /** + * Sets the timer's start time to the current time, and reschedules the timer to + * call its callback at the previously specified duration adjusted to the current + * time. This is useful for refreshing a timer without allocating a new + * JavaScript object. + * + * Using this on a timer that has already called its callback will reactivate the + * timer. + * @since v10.2.0 + * @returns a reference to `timeout` + */ + refresh(): this; + /** + * When called, the active `Timeout` object will not require the Node.js event loop + * to remain active. If there is no other activity keeping the event loop running, + * the process may exit before the `Timeout` object's callback is invoked. Calling + * `timeout.unref()` multiple times will have no effect. + * @since v0.9.1 + * @returns a reference to `timeout` + */ + unref(): this; + /** + * Coerce a `Timeout` to a primitive. The primitive can be used to + * clear the `Timeout`. The primitive can only be used in the + * same thread where the timeout was created. Therefore, to use it + * across `worker_threads` it must first be passed to the correct + * thread. This allows enhanced compatibility with browser + * `setTimeout()` and `setInterval()` implementations. + * @since v14.9.0, v12.19.0 + */ + [Symbol.toPrimitive](): number; + /** + * Cancels the timeout. + * @since v20.5.0, v18.18.0 + */ + [Symbol.dispose](): void; + _onTimeout(...args: any[]): void; + } + } + } + import clearImmediate = globalThis.clearImmediate; + import clearInterval = globalThis.clearInterval; + import clearTimeout = globalThis.clearTimeout; + import setImmediate = globalThis.setImmediate; + import setInterval = globalThis.setInterval; + import setTimeout = globalThis.setTimeout; + export { clearImmediate, clearInterval, clearTimeout, promises, setImmediate, setInterval, setTimeout }; +} +declare module "timers" { + export * from "node:timers"; +} diff --git a/backend/node_modules/@types/node/timers/promises.d.ts b/backend/node_modules/@types/node/timers/promises.d.ts new file mode 100644 index 0000000..85bc831 --- /dev/null +++ b/backend/node_modules/@types/node/timers/promises.d.ts @@ -0,0 +1,108 @@ +/** + * The `timers/promises` API provides an alternative set of timer functions + * that return `Promise` objects. The API is accessible via + * `require('node:timers/promises')`. + * + * ```js + * import { + * setTimeout, + * setImmediate, + * setInterval, + * } from 'node:timers/promises'; + * ``` + * @since v15.0.0 + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/timers/promises.js) + */ +declare module "node:timers/promises" { + import { TimerOptions } from "node:timers"; + /** + * ```js + * import { + * setTimeout, + * } from 'node:timers/promises'; + * + * const res = await setTimeout(100, 'result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param delay The number of milliseconds to wait before fulfilling the + * promise. **Default:** `1`. + * @param value A value with which the promise is fulfilled. + */ + function setTimeout(delay?: number, value?: T, options?: TimerOptions): Promise; + /** + * ```js + * import { + * setImmediate, + * } from 'node:timers/promises'; + * + * const res = await setImmediate('result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param value A value with which the promise is fulfilled. + */ + function setImmediate(value?: T, options?: TimerOptions): Promise; + /** + * Returns an async iterator that generates values in an interval of `delay` ms. + * If `ref` is `true`, you need to call `next()` of async iterator explicitly + * or implicitly to keep the event loop alive. + * + * ```js + * import { + * setInterval, + * } from 'node:timers/promises'; + * + * const interval = 100; + * for await (const startTime of setInterval(interval, Date.now())) { + * const now = Date.now(); + * console.log(now); + * if ((now - startTime) > 1000) + * break; + * } + * console.log(Date.now()); + * ``` + * @since v15.9.0 + * @param delay The number of milliseconds to wait between iterations. + * **Default:** `1`. + * @param value A value with which the iterator returns. + */ + function setInterval(delay?: number, value?: T, options?: TimerOptions): NodeJS.AsyncIterator; + interface Scheduler { + /** + * An experimental API defined by the [Scheduling APIs](https://github.com/WICG/scheduling-apis) draft specification + * being developed as a standard Web Platform API. + * + * Calling `timersPromises.scheduler.wait(delay, options)` is roughly equivalent + * to calling `timersPromises.setTimeout(delay, undefined, options)` except that + * the `ref` option is not supported. + * + * ```js + * import { scheduler } from 'node:timers/promises'; + * + * await scheduler.wait(1000); // Wait one second before continuing + * ``` + * @since v17.3.0, v16.14.0 + * @experimental + * @param delay The number of milliseconds to wait before resolving the + * promise. + */ + wait(delay: number, options?: { signal?: AbortSignal }): Promise; + /** + * An experimental API defined by the [Scheduling APIs](https://github.com/WICG/scheduling-apis) draft specification + * being developed as a standard Web Platform API. + * + * Calling `timersPromises.scheduler.yield()` is equivalent to calling + * `timersPromises.setImmediate()` with no arguments. + * @since v17.3.0, v16.14.0 + * @experimental + */ + yield(): Promise; + } + const scheduler: Scheduler; +} +declare module "timers/promises" { + export * from "node:timers/promises"; +} diff --git a/backend/node_modules/@types/node/tls.d.ts b/backend/node_modules/@types/node/tls.d.ts new file mode 100644 index 0000000..8e2ffa7 --- /dev/null +++ b/backend/node_modules/@types/node/tls.d.ts @@ -0,0 +1,1194 @@ +/** + * The `node:tls` module provides an implementation of the Transport Layer Security + * (TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL. + * The module can be accessed using: + * + * ```js + * import tls from 'node:tls'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/tls.js) + */ +declare module "node:tls" { + import { NonSharedBuffer } from "node:buffer"; + import { X509Certificate } from "node:crypto"; + import * as net from "node:net"; + import * as stream from "stream"; + const CLIENT_RENEG_LIMIT: number; + const CLIENT_RENEG_WINDOW: number; + interface Certificate { + /** + * Country code. + */ + C: string; + /** + * Street. + */ + ST: string; + /** + * Locality. + */ + L: string; + /** + * Organization. + */ + O: string; + /** + * Organizational unit. + */ + OU: string; + /** + * Common name. + */ + CN: string; + } + interface PeerCertificate { + /** + * `true` if a Certificate Authority (CA), `false` otherwise. + * @since v18.13.0 + */ + ca: boolean; + /** + * The DER encoded X.509 certificate data. + */ + raw: NonSharedBuffer; + /** + * The certificate subject. + */ + subject: Certificate; + /** + * The certificate issuer, described in the same terms as the `subject`. + */ + issuer: Certificate; + /** + * The date-time the certificate is valid from. + */ + valid_from: string; + /** + * The date-time the certificate is valid to. + */ + valid_to: string; + /** + * The certificate serial number, as a hex string. + */ + serialNumber: string; + /** + * The SHA-1 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint: string; + /** + * The SHA-256 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint256: string; + /** + * The SHA-512 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint512: string; + /** + * The extended key usage, a set of OIDs. + */ + ext_key_usage?: string[]; + /** + * A string containing concatenated names for the subject, + * an alternative to the `subject` names. + */ + subjectaltname?: string; + /** + * An array describing the AuthorityInfoAccess, used with OCSP. + */ + infoAccess?: NodeJS.Dict; + /** + * For RSA keys: The RSA bit size. + * + * For EC keys: The key size in bits. + */ + bits?: number; + /** + * The RSA exponent, as a string in hexadecimal number notation. + */ + exponent?: string; + /** + * The RSA modulus, as a hexadecimal string. + */ + modulus?: string; + /** + * The public key. + */ + pubkey?: NonSharedBuffer; + /** + * The ASN.1 name of the OID of the elliptic curve. + * Well-known curves are identified by an OID. + * While it is unusual, it is possible that the curve + * is identified by its mathematical properties, + * in which case it will not have an OID. + */ + asn1Curve?: string; + /** + * The NIST name for the elliptic curve, if it has one + * (not all well-known curves have been assigned names by NIST). + */ + nistCurve?: string; + } + interface DetailedPeerCertificate extends PeerCertificate { + /** + * The issuer certificate object. + * For self-signed certificates, this may be a circular reference. + */ + issuerCertificate: DetailedPeerCertificate; + } + interface CipherNameAndProtocol { + /** + * The cipher name. + */ + name: string; + /** + * SSL/TLS protocol version. + */ + version: string; + /** + * IETF name for the cipher suite. + */ + standardName: string; + } + interface EphemeralKeyInfo { + /** + * The supported types are 'DH' and 'ECDH'. + */ + type: string; + /** + * The name property is available only when type is 'ECDH'. + */ + name?: string | undefined; + /** + * The size of parameter of an ephemeral key exchange. + */ + size: number; + } + interface KeyObject { + /** + * Private keys in PEM format. + */ + pem: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; + } + interface PxfObject { + /** + * PFX or PKCS12 encoded private key and certificate chain. + */ + buf: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; + } + interface TLSSocketOptions extends SecureContextOptions, CommonConnectionOptions { + /** + * If true the TLS socket will be instantiated in server-mode. + * Defaults to false. + */ + isServer?: boolean | undefined; + /** + * An optional net.Server instance. + */ + server?: net.Server | undefined; + /** + * An optional Buffer instance containing a TLS session. + */ + session?: Buffer | undefined; + /** + * If true, specifies that the OCSP status request extension will be + * added to the client hello and an 'OCSPResponse' event will be + * emitted on the socket before establishing a secure communication + */ + requestOCSP?: boolean | undefined; + } + interface TLSSocketEventMap extends net.SocketEventMap { + "keylog": [line: NonSharedBuffer]; + "OCSPResponse": [response: NonSharedBuffer]; + "secureConnect": []; + "session": [session: NonSharedBuffer]; + } + /** + * Performs transparent encryption of written data and all required TLS + * negotiation. + * + * Instances of `tls.TLSSocket` implement the duplex `Stream` interface. + * + * Methods that return TLS connection metadata (e.g.{@link TLSSocket.getPeerCertificate}) will only return data while the + * connection is open. + * @since v0.11.4 + */ + class TLSSocket extends net.Socket { + /** + * Construct a new tls.TLSSocket object from an existing TCP socket. + */ + constructor(socket: net.Socket | stream.Duplex, options?: TLSSocketOptions); + /** + * This property is `true` if the peer certificate was signed by one of the CAs + * specified when creating the `tls.TLSSocket` instance, otherwise `false`. + * @since v0.11.4 + */ + authorized: boolean; + /** + * Returns the reason why the peer's certificate was not been verified. This + * property is set only when `tlsSocket.authorized === false`. + * @since v0.11.4 + */ + authorizationError: Error; + /** + * Always returns `true`. This may be used to distinguish TLS sockets from regular`net.Socket` instances. + * @since v0.11.4 + */ + encrypted: true; + /** + * String containing the selected ALPN protocol. + * Before a handshake has completed, this value is always null. + * When a handshake is completed but not ALPN protocol was selected, tlsSocket.alpnProtocol equals false. + */ + alpnProtocol: string | false | null; + /** + * Returns an object representing the local certificate. The returned object has + * some properties corresponding to the fields of the certificate. + * + * See {@link TLSSocket.getPeerCertificate} for an example of the certificate + * structure. + * + * If there is no local certificate, an empty object will be returned. If the + * socket has been destroyed, `null` will be returned. + * @since v11.2.0 + */ + getCertificate(): PeerCertificate | object | null; + /** + * Returns an object containing information on the negotiated cipher suite. + * + * For example, a TLSv1.2 protocol with AES256-SHA cipher: + * + * ```json + * { + * "name": "AES256-SHA", + * "standardName": "TLS_RSA_WITH_AES_256_CBC_SHA", + * "version": "SSLv3" + * } + * ``` + * + * See [SSL\_CIPHER\_get\_name](https://www.openssl.org/docs/man1.1.1/man3/SSL_CIPHER_get_name.html) for more information. + * @since v0.11.4 + */ + getCipher(): CipherNameAndProtocol; + /** + * Returns an object representing the type, name, and size of parameter of + * an ephemeral key exchange in `perfect forward secrecy` on a client + * connection. It returns an empty object when the key exchange is not + * ephemeral. As this is only supported on a client socket; `null` is returned + * if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The `name` property is available only when type is `'ECDH'`. + * + * For example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }`. + * @since v5.0.0 + */ + getEphemeralKeyInfo(): EphemeralKeyInfo | object | null; + /** + * As the `Finished` messages are message digests of the complete handshake + * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can + * be used for external authentication procedures when the authentication + * provided by SSL/TLS is not desired or is not enough. + * + * Corresponds to the `SSL_get_finished` routine in OpenSSL and may be used + * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + * @since v9.9.0 + * @return The latest `Finished` message that has been sent to the socket as part of a SSL/TLS handshake, or `undefined` if no `Finished` message has been sent yet. + */ + getFinished(): NonSharedBuffer | undefined; + /** + * Returns an object representing the peer's certificate. If the peer does not + * provide a certificate, an empty object will be returned. If the socket has been + * destroyed, `null` will be returned. + * + * If the full certificate chain was requested, each certificate will include an`issuerCertificate` property containing an object representing its issuer's + * certificate. + * @since v0.11.4 + * @param detailed Include the full certificate chain if `true`, otherwise include just the peer's certificate. + * @return A certificate object. + */ + getPeerCertificate(detailed: true): DetailedPeerCertificate; + getPeerCertificate(detailed?: false): PeerCertificate; + getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; + /** + * As the `Finished` messages are message digests of the complete handshake + * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can + * be used for external authentication procedures when the authentication + * provided by SSL/TLS is not desired or is not enough. + * + * Corresponds to the `SSL_get_peer_finished` routine in OpenSSL and may be used + * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + * @since v9.9.0 + * @return The latest `Finished` message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, or `undefined` if there is no `Finished` message so + * far. + */ + getPeerFinished(): NonSharedBuffer | undefined; + /** + * Returns a string containing the negotiated SSL/TLS protocol version of the + * current connection. The value `'unknown'` will be returned for connected + * sockets that have not completed the handshaking process. The value `null` will + * be returned for server sockets or disconnected client sockets. + * + * Protocol versions are: + * + * * `'SSLv3'` + * * `'TLSv1'` + * * `'TLSv1.1'` + * * `'TLSv1.2'` + * * `'TLSv1.3'` + * + * See the OpenSSL [`SSL_get_version`](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html) documentation for more information. + * @since v5.7.0 + */ + getProtocol(): string | null; + /** + * Returns the TLS session data or `undefined` if no session was + * negotiated. On the client, the data can be provided to the `session` option of {@link connect} to resume the connection. On the server, it may be useful + * for debugging. + * + * See `Session Resumption` for more information. + * + * Note: `getSession()` works only for TLSv1.2 and below. For TLSv1.3, applications + * must use the `'session'` event (it also works for TLSv1.2 and below). + * @since v0.11.4 + */ + getSession(): NonSharedBuffer | undefined; + /** + * See [SSL\_get\_shared\_sigalgs](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_shared_sigalgs.html) for more information. + * @since v12.11.0 + * @return List of signature algorithms shared between the server and the client in the order of decreasing preference. + */ + getSharedSigalgs(): string[]; + /** + * For a client, returns the TLS session ticket if one is available, or`undefined`. For a server, always returns `undefined`. + * + * It may be useful for debugging. + * + * See `Session Resumption` for more information. + * @since v0.11.4 + */ + getTLSTicket(): NonSharedBuffer | undefined; + /** + * See `Session Resumption` for more information. + * @since v0.5.6 + * @return `true` if the session was reused, `false` otherwise. + */ + isSessionReused(): boolean; + /** + * The `tlsSocket.renegotiate()` method initiates a TLS renegotiation process. + * Upon completion, the `callback` function will be passed a single argument + * that is either an `Error` (if the request failed) or `null`. + * + * This method can be used to request a peer's certificate after the secure + * connection has been established. + * + * When running as the server, the socket will be destroyed with an error after `handshakeTimeout` timeout. + * + * For TLSv1.3, renegotiation cannot be initiated, it is not supported by the + * protocol. + * @since v0.11.8 + * @param callback If `renegotiate()` returned `true`, callback is attached once to the `'secure'` event. If `renegotiate()` returned `false`, `callback` will be called in the next tick with + * an error, unless the `tlsSocket` has been destroyed, in which case `callback` will not be called at all. + * @return `true` if renegotiation was initiated, `false` otherwise. + */ + renegotiate( + options: { + rejectUnauthorized?: boolean | undefined; + requestCert?: boolean | undefined; + }, + callback: (err: Error | null) => void, + ): undefined | boolean; + /** + * The `tlsSocket.setKeyCert()` method sets the private key and certificate to use for the socket. + * This is mainly useful if you wish to select a server certificate from a TLS server's `ALPNCallback`. + * @since v22.5.0, v20.17.0 + * @param context An object containing at least `key` and `cert` properties from the {@link createSecureContext()} `options`, + * or a TLS context object created with {@link createSecureContext()} itself. + */ + setKeyCert(context: SecureContextOptions | SecureContext): void; + /** + * The `tlsSocket.setMaxSendFragment()` method sets the maximum TLS fragment size. + * Returns `true` if setting the limit succeeded; `false` otherwise. + * + * Smaller fragment sizes decrease the buffering latency on the client: larger + * fragments are buffered by the TLS layer until the entire fragment is received + * and its integrity is verified; large fragments can span multiple roundtrips + * and their processing can be delayed due to packet loss or reordering. However, + * smaller fragments add extra TLS framing bytes and CPU overhead, which may + * decrease overall server throughput. + * @since v0.11.11 + * @param [size=16384] The maximum TLS fragment size. The maximum value is `16384`. + */ + setMaxSendFragment(size: number): boolean; + /** + * Disables TLS renegotiation for this `TLSSocket` instance. Once called, attempts + * to renegotiate will trigger an `'error'` event on the `TLSSocket`. + * @since v8.4.0 + */ + disableRenegotiation(): void; + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * + * The format of the output is identical to the output of`openssl s_client -trace` or `openssl s_server -trace`. While it is produced by + * OpenSSL's `SSL_trace()` function, the format is undocumented, can change + * without notice, and should not be relied on. + * @since v12.2.0 + */ + enableTrace(): void; + /** + * Returns the peer certificate as an `X509Certificate` object. + * + * If there is no peer certificate, or the socket has been destroyed,`undefined` will be returned. + * @since v15.9.0 + */ + getPeerX509Certificate(): X509Certificate | undefined; + /** + * Returns the local certificate as an `X509Certificate` object. + * + * If there is no local certificate, or the socket has been destroyed,`undefined` will be returned. + * @since v15.9.0 + */ + getX509Certificate(): X509Certificate | undefined; + /** + * Keying material is used for validations to prevent different kind of attacks in + * network protocols, for example in the specifications of IEEE 802.1X. + * + * Example + * + * ```js + * const keyingMaterial = tlsSocket.exportKeyingMaterial( + * 128, + * 'client finished'); + * + * /* + * Example return value of keyingMaterial: + * + * + * ``` + * + * See the OpenSSL [`SSL_export_keying_material`](https://www.openssl.org/docs/man1.1.1/man3/SSL_export_keying_material.html) documentation for more + * information. + * @since v13.10.0, v12.17.0 + * @param length number of bytes to retrieve from keying material + * @param label an application specific label, typically this will be a value from the [IANA Exporter Label + * Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels). + * @param context Optionally provide a context. + * @return requested bytes of the keying material + */ + exportKeyingMaterial(length: number, label: string, context: Buffer): NonSharedBuffer; + // #region InternalEventEmitter + addListener( + eventName: E, + listener: (...args: TLSSocketEventMap[E]) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: TLSSocketEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: TLSSocketEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners(eventName: E): ((...args: TLSSocketEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off(eventName: E, listener: (...args: TLSSocketEventMap[E]) => void): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on(eventName: E, listener: (...args: TLSSocketEventMap[E]) => void): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once(eventName: E, listener: (...args: TLSSocketEventMap[E]) => void): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: TLSSocketEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: TLSSocketEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners(eventName: E): ((...args: TLSSocketEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: TLSSocketEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + interface CommonConnectionOptions { + /** + * An optional TLS context object from tls.createSecureContext() + */ + secureContext?: SecureContext | undefined; + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * @default false + */ + enableTrace?: boolean | undefined; + /** + * If true the server will request a certificate from clients that + * connect and attempt to verify that certificate. Defaults to + * false. + */ + requestCert?: boolean | undefined; + /** + * An array of strings or a Buffer naming possible ALPN protocols. + * (Protocols should be ordered by their priority.) + */ + ALPNProtocols?: readonly string[] | NodeJS.ArrayBufferView | undefined; + /** + * SNICallback(servername, cb) A function that will be + * called if the client supports SNI TLS extension. Two arguments + * will be passed when called: servername and cb. SNICallback should + * invoke cb(null, ctx), where ctx is a SecureContext instance. + * (tls.createSecureContext(...) can be used to get a proper + * SecureContext.) If SNICallback wasn't provided the default callback + * with high-level API will be used (see below). + */ + SNICallback?: ((servername: string, cb: (err: Error | null, ctx?: SecureContext) => void) => void) | undefined; + /** + * If true the server will reject any connection which is not + * authorized with the list of supplied CAs. This option only has an + * effect if requestCert is true. + * @default true + */ + rejectUnauthorized?: boolean | undefined; + } + interface TlsOptions extends SecureContextOptions, CommonConnectionOptions, net.ServerOpts { + /** + * Abort the connection if the SSL/TLS handshake does not finish in the + * specified number of milliseconds. A 'tlsClientError' is emitted on + * the tls.Server object whenever a handshake times out. Default: + * 120000 (120 seconds). + */ + handshakeTimeout?: number | undefined; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number | undefined; + /** + * 48-bytes of cryptographically strong pseudo-random data. + */ + ticketKeys?: Buffer | undefined; + /** + * @param socket + * @param identity identity parameter sent from the client. + * @return pre-shared key that must either be + * a buffer or `null` to stop the negotiation process. Returned PSK must be + * compatible with the selected cipher's digest. + * + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with the identity provided by the client. + * If the return value is `null` the negotiation process will stop and an + * "unknown_psk_identity" alert message will be sent to the other party. + * If the server wishes to hide the fact that the PSK identity was not known, + * the callback must provide some random data as `psk` to make the connection + * fail with "decrypt_error" before negotiation is finished. + * PSK ciphers are disabled by default, and using TLS-PSK thus + * requires explicitly specifying a cipher suite with the `ciphers` option. + * More information can be found in the RFC 4279. + */ + pskCallback?: ((socket: TLSSocket, identity: string) => NodeJS.ArrayBufferView | null) | undefined; + /** + * hint to send to a client to help + * with selecting the identity during TLS-PSK negotiation. Will be ignored + * in TLS 1.3. Upon failing to set pskIdentityHint `tlsClientError` will be + * emitted with `ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED` code. + */ + pskIdentityHint?: string | undefined; + } + interface PSKCallbackNegotation { + psk: NodeJS.ArrayBufferView; + identity: string; + } + interface ConnectionOptions extends SecureContextOptions, CommonConnectionOptions { + host?: string | undefined; + port?: number | undefined; + path?: string | undefined; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. + socket?: stream.Duplex | undefined; // Establish secure connection on a given socket rather than creating a new socket + checkServerIdentity?: typeof checkServerIdentity | undefined; + servername?: string | undefined; // SNI TLS Extension + session?: Buffer | undefined; + minDHSize?: number | undefined; + lookup?: net.LookupFunction | undefined; + timeout?: number | undefined; + /** + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with optional identity `hint` provided by the server or `null` + * in case of TLS 1.3 where `hint` was removed. + * It will be necessary to provide a custom `tls.checkServerIdentity()` + * for the connection as the default one will try to check hostname/IP + * of the server against the certificate but that's not applicable for PSK + * because there won't be a certificate present. + * More information can be found in the RFC 4279. + * + * @param hint message sent from the server to help client + * decide which identity to use during negotiation. + * Always `null` if TLS 1.3 is used. + * @returns Return `null` to stop the negotiation process. `psk` must be + * compatible with the selected cipher's digest. + * `identity` must use UTF-8 encoding. + */ + pskCallback?: ((hint: string | null) => PSKCallbackNegotation | null) | undefined; + } + interface ServerEventMap extends net.ServerEventMap { + "connection": [socket: net.Socket]; + "keylog": [line: NonSharedBuffer, tlsSocket: TLSSocket]; + "newSession": [sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void]; + "OCSPRequest": [ + certificate: NonSharedBuffer, + issuer: NonSharedBuffer, + callback: (err: Error | null, resp: Buffer | null) => void, + ]; + "resumeSession": [sessionId: Buffer, callback: (err: Error | null, sessionData?: Buffer) => void]; + "secureConnection": [tlsSocket: TLSSocket]; + "tlsClientError": [exception: Error, tlsSocket: TLSSocket]; + } + /** + * Accepts encrypted connections using TLS or SSL. + * @since v0.3.2 + */ + class Server extends net.Server { + constructor(secureConnectionListener?: (socket: TLSSocket) => void); + constructor(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void); + /** + * The `server.addContext()` method adds a secure context that will be used if + * the client request's SNI name matches the supplied `hostname` (or wildcard). + * + * When there are multiple matching contexts, the most recently added one is + * used. + * @since v0.5.3 + * @param hostname A SNI host name or wildcard (e.g. `'*'`) + * @param context An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc), or a TLS context object created + * with {@link createSecureContext} itself. + */ + addContext(hostname: string, context: SecureContextOptions | SecureContext): void; + /** + * Returns the session ticket keys. + * + * See `Session Resumption` for more information. + * @since v3.0.0 + * @return A 48-byte buffer containing the session ticket keys. + */ + getTicketKeys(): NonSharedBuffer; + /** + * The `server.setSecureContext()` method replaces the secure context of an + * existing server. Existing connections to the server are not interrupted. + * @since v11.0.0 + * @param options An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc). + */ + setSecureContext(options: SecureContextOptions): void; + /** + * Sets the session ticket keys. + * + * Changes to the ticket keys are effective only for future server connections. + * Existing or currently pending server connections will use the previous keys. + * + * See `Session Resumption` for more information. + * @since v3.0.0 + * @param keys A 48-byte buffer containing the session ticket keys. + */ + setTicketKeys(keys: Buffer): void; + // #region InternalEventEmitter + addListener(eventName: E, listener: (...args: ServerEventMap[E]) => void): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: ServerEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: ServerEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners(eventName: E): ((...args: ServerEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off(eventName: E, listener: (...args: ServerEventMap[E]) => void): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on(eventName: E, listener: (...args: ServerEventMap[E]) => void): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once(eventName: E, listener: (...args: ServerEventMap[E]) => void): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: ServerEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: ServerEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners(eventName: E): ((...args: ServerEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: ServerEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } + type SecureVersion = "TLSv1.3" | "TLSv1.2" | "TLSv1.1" | "TLSv1"; + interface SecureContextOptions { + /** + * If set, this will be called when a client opens a connection using the ALPN extension. + * One argument will be passed to the callback: an object containing `servername` and `protocols` fields, + * respectively containing the server name from the SNI extension (if any) and an array of + * ALPN protocol name strings. The callback must return either one of the strings listed in `protocols`, + * which will be returned to the client as the selected ALPN protocol, or `undefined`, + * to reject the connection with a fatal alert. If a string is returned that does not match one of + * the client's ALPN protocols, an error will be thrown. + * This option cannot be used with the `ALPNProtocols` option, and setting both options will throw an error. + */ + ALPNCallback?: ((arg: { servername: string; protocols: string[] }) => string | undefined) | undefined; + /** + * Treat intermediate (non-self-signed) + * certificates in the trust CA certificate list as trusted. + * @since v22.9.0, v20.18.0 + */ + allowPartialTrustChain?: boolean | undefined; + /** + * Optionally override the trusted CA certificates. Default is to trust + * the well-known CAs curated by Mozilla. Mozilla's CAs are completely + * replaced when CAs are explicitly specified using this option. + */ + ca?: string | Buffer | Array | undefined; + /** + * Cert chains in PEM format. One cert chain should be provided per + * private key. Each cert chain should consist of the PEM formatted + * certificate for a provided private key, followed by the PEM + * formatted intermediate certificates (if any), in order, and not + * including the root CA (the root CA must be pre-known to the peer, + * see ca). When providing multiple cert chains, they do not have to + * be in the same order as their private keys in key. If the + * intermediate certificates are not provided, the peer will not be + * able to validate the certificate, and the handshake will fail. + */ + cert?: string | Buffer | Array | undefined; + /** + * Colon-separated list of supported signature algorithms. The list + * can contain digest algorithms (SHA256, MD5 etc.), public key + * algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g + * 'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512). + */ + sigalgs?: string | undefined; + /** + * Cipher suite specification, replacing the default. For more + * information, see modifying the default cipher suite. Permitted + * ciphers can be obtained via tls.getCiphers(). Cipher names must be + * uppercased in order for OpenSSL to accept them. + */ + ciphers?: string | undefined; + /** + * Name of an OpenSSL engine which can provide the client certificate. + * @deprecated + */ + clientCertEngine?: string | undefined; + /** + * PEM formatted CRLs (Certificate Revocation Lists). + */ + crl?: string | Buffer | Array | undefined; + /** + * `'auto'` or custom Diffie-Hellman parameters, required for non-ECDHE perfect forward secrecy. + * If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available. + * ECDHE-based perfect forward secrecy will still be available. + */ + dhparam?: string | Buffer | undefined; + /** + * A string describing a named curve or a colon separated list of curve + * NIDs or names, for example P-521:P-384:P-256, to use for ECDH key + * agreement. Set to auto to select the curve automatically. Use + * crypto.getCurves() to obtain a list of available curve names. On + * recent releases, openssl ecparam -list_curves will also display the + * name and description of each available elliptic curve. Default: + * tls.DEFAULT_ECDH_CURVE. + */ + ecdhCurve?: string | undefined; + /** + * Attempt to use the server's cipher suite preferences instead of the + * client's. When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be + * set in secureOptions + */ + honorCipherOrder?: boolean | undefined; + /** + * Private keys in PEM format. PEM allows the option of private keys + * being encrypted. Encrypted keys will be decrypted with + * options.passphrase. Multiple keys using different algorithms can be + * provided either as an array of unencrypted key strings or buffers, + * or an array of objects in the form {pem: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted keys will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + key?: string | Buffer | Array | undefined; + /** + * Name of an OpenSSL engine to get private key from. Should be used + * together with privateKeyIdentifier. + * @deprecated + */ + privateKeyEngine?: string | undefined; + /** + * Identifier of a private key managed by an OpenSSL engine. Should be + * used together with privateKeyEngine. Should not be set together with + * key, because both options define a private key in different ways. + * @deprecated + */ + privateKeyIdentifier?: string | undefined; + /** + * Optionally set the maximum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. + * **Default:** `'TLSv1.3'`, unless changed using CLI options. Using + * `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using `--tls-max-v1.3` sets the default to + * `'TLSv1.3'`. If multiple of the options are provided, the highest maximum is used. + */ + maxVersion?: SecureVersion | undefined; + /** + * Optionally set the minimum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. It is not recommended to use + * less than TLSv1.2, but it may be required for interoperability. + * **Default:** `'TLSv1.2'`, unless changed using CLI options. Using + * `--tls-v1.0` sets the default to `'TLSv1'`. Using `--tls-v1.1` sets the default to + * `'TLSv1.1'`. Using `--tls-min-v1.3` sets the default to + * 'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used. + */ + minVersion?: SecureVersion | undefined; + /** + * Shared passphrase used for a single private key and/or a PFX. + */ + passphrase?: string | undefined; + /** + * PFX or PKCS12 encoded private key and certificate chain. pfx is an + * alternative to providing key and cert individually. PFX is usually + * encrypted, if it is, passphrase will be used to decrypt it. Multiple + * PFX can be provided either as an array of unencrypted PFX buffers, + * or an array of objects in the form {buf: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted PFX will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + pfx?: string | Buffer | Array | undefined; + /** + * Optionally affect the OpenSSL protocol behavior, which is not + * usually necessary. This should be used carefully if at all! Value is + * a numeric bitmask of the SSL_OP_* options from OpenSSL Options + */ + secureOptions?: number | undefined; // Value is a numeric bitmask of the `SSL_OP_*` options + /** + * Legacy mechanism to select the TLS protocol version to use, it does + * not support independent control of the minimum and maximum version, + * and does not support limiting the protocol to TLSv1.3. Use + * minVersion and maxVersion instead. The possible values are listed as + * SSL_METHODS, use the function names as strings. For example, use + * 'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow + * any TLS protocol version up to TLSv1.3. It is not recommended to use + * TLS versions less than 1.2, but it may be required for + * interoperability. Default: none, see minVersion. + */ + secureProtocol?: string | undefined; + /** + * Opaque identifier used by servers to ensure session state is not + * shared between applications. Unused by clients. + */ + sessionIdContext?: string | undefined; + /** + * 48-bytes of cryptographically strong pseudo-random data. + * See Session Resumption for more information. + */ + ticketKeys?: Buffer | undefined; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number | undefined; + } + interface SecureContext { + context: any; + } + /** + * Verifies the certificate `cert` is issued to `hostname`. + * + * Returns [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object, populating it with `reason`, `host`, and `cert` on + * failure. On success, returns [undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type). + * + * This function is intended to be used in combination with the`checkServerIdentity` option that can be passed to {@link connect} and as + * such operates on a `certificate object`. For other purposes, consider using `x509.checkHost()` instead. + * + * This function can be overwritten by providing an alternative function as the `options.checkServerIdentity` option that is passed to `tls.connect()`. The + * overwriting function can call `tls.checkServerIdentity()` of course, to augment + * the checks done with additional verification. + * + * This function is only called if the certificate passed all other checks, such as + * being issued by trusted CA (`options.ca`). + * + * Earlier versions of Node.js incorrectly accepted certificates for a given`hostname` if a matching `uniformResourceIdentifier` subject alternative name + * was present (see [CVE-2021-44531](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44531)). Applications that wish to accept`uniformResourceIdentifier` subject alternative names can use + * a custom `options.checkServerIdentity` function that implements the desired behavior. + * @since v0.8.4 + * @param hostname The host name or IP address to verify the certificate against. + * @param cert A `certificate object` representing the peer's certificate. + */ + function checkServerIdentity(hostname: string, cert: PeerCertificate): Error | undefined; + /** + * Creates a new {@link Server}. The `secureConnectionListener`, if provided, is + * automatically set as a listener for the `'secureConnection'` event. + * + * The `ticketKeys` options is automatically shared between `node:cluster` module + * workers. + * + * The following illustrates a simple echo server: + * + * ```js + * import tls from 'node:tls'; + * import fs from 'node:fs'; + * + * const options = { + * key: fs.readFileSync('server-key.pem'), + * cert: fs.readFileSync('server-cert.pem'), + * + * // This is necessary only if using client certificate authentication. + * requestCert: true, + * + * // This is necessary only if the client uses a self-signed certificate. + * ca: [ fs.readFileSync('client-cert.pem') ], + * }; + * + * const server = tls.createServer(options, (socket) => { + * console.log('server connected', + * socket.authorized ? 'authorized' : 'unauthorized'); + * socket.write('welcome!\n'); + * socket.setEncoding('utf8'); + * socket.pipe(socket); + * }); + * server.listen(8000, () => { + * console.log('server bound'); + * }); + * ``` + * + * The server can be tested by connecting to it using the example client from {@link connect}. + * @since v0.3.2 + */ + function createServer(secureConnectionListener?: (socket: TLSSocket) => void): Server; + function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; + /** + * The `callback` function, if specified, will be added as a listener for the `'secureConnect'` event. + * + * `tls.connect()` returns a {@link TLSSocket} object. + * + * Unlike the `https` API, `tls.connect()` does not enable the + * SNI (Server Name Indication) extension by default, which may cause some + * servers to return an incorrect certificate or reject the connection + * altogether. To enable SNI, set the `servername` option in addition + * to `host`. + * + * The following illustrates a client for the echo server example from {@link createServer}: + * + * ```js + * // Assumes an echo server that is listening on port 8000. + * import tls from 'node:tls'; + * import fs from 'node:fs'; + * + * const options = { + * // Necessary only if the server requires client certificate authentication. + * key: fs.readFileSync('client-key.pem'), + * cert: fs.readFileSync('client-cert.pem'), + * + * // Necessary only if the server uses a self-signed certificate. + * ca: [ fs.readFileSync('server-cert.pem') ], + * + * // Necessary only if the server's cert isn't for "localhost". + * checkServerIdentity: () => { return null; }, + * }; + * + * const socket = tls.connect(8000, options, () => { + * console.log('client connected', + * socket.authorized ? 'authorized' : 'unauthorized'); + * process.stdin.pipe(socket); + * process.stdin.resume(); + * }); + * socket.setEncoding('utf8'); + * socket.on('data', (data) => { + * console.log(data); + * }); + * socket.on('end', () => { + * console.log('server ends connection'); + * }); + * ``` + * @since v0.11.3 + */ + function connect(options: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function connect( + port: number, + host?: string, + options?: ConnectionOptions, + secureConnectListener?: () => void, + ): TLSSocket; + function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + /** + * `{@link createServer}` sets the default value of the `honorCipherOrder` option + * to `true`, other APIs that create secure contexts leave it unset. + * + * `{@link createServer}` uses a 128 bit truncated SHA1 hash value generated + * from `process.argv` as the default value of the `sessionIdContext` option, other + * APIs that create secure contexts have no default value. + * + * The `tls.createSecureContext()` method creates a `SecureContext` object. It is + * usable as an argument to several `tls` APIs, such as `server.addContext()`, + * but has no public methods. The {@link Server} constructor and the {@link createServer} method do not support the `secureContext` option. + * + * A key is _required_ for ciphers that use certificates. Either `key` or `pfx` can be used to provide it. + * + * If the `ca` option is not given, then Node.js will default to using [Mozilla's publicly trusted list of + * CAs](https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt). + * + * Custom DHE parameters are discouraged in favor of the new `dhparam: 'auto' `option. When set to `'auto'`, well-known DHE parameters of sufficient strength + * will be selected automatically. Otherwise, if necessary, `openssl dhparam` can + * be used to create custom parameters. The key length must be greater than or + * equal to 1024 bits or else an error will be thrown. Although 1024 bits is + * permissible, use 2048 bits or larger for stronger security. + * @since v0.11.13 + */ + function createSecureContext(options?: SecureContextOptions): SecureContext; + /** + * Returns an array containing the CA certificates from various sources, depending on `type`: + * + * * `"default"`: return the CA certificates that will be used by the Node.js TLS clients by default. + * * When `--use-bundled-ca` is enabled (default), or `--use-openssl-ca` is not enabled, + * this would include CA certificates from the bundled Mozilla CA store. + * * When `--use-system-ca` is enabled, this would also include certificates from the system's + * trusted store. + * * When `NODE_EXTRA_CA_CERTS` is used, this would also include certificates loaded from the specified + * file. + * * `"system"`: return the CA certificates that are loaded from the system's trusted store, according + * to rules set by `--use-system-ca`. This can be used to get the certificates from the system + * when `--use-system-ca` is not enabled. + * * `"bundled"`: return the CA certificates from the bundled Mozilla CA store. This would be the same + * as `tls.rootCertificates`. + * * `"extra"`: return the CA certificates loaded from `NODE_EXTRA_CA_CERTS`. It's an empty array if + * `NODE_EXTRA_CA_CERTS` is not set. + * @since v22.15.0 + * @param type The type of CA certificates that will be returned. Valid values + * are `"default"`, `"system"`, `"bundled"` and `"extra"`. + * **Default:** `"default"`. + * @returns An array of PEM-encoded certificates. The array may contain duplicates + * if the same certificate is repeatedly stored in multiple sources. + */ + function getCACertificates(type?: "default" | "system" | "bundled" | "extra"): string[]; + /** + * Returns an array with the names of the supported TLS ciphers. The names are + * lower-case for historical reasons, but must be uppercased to be used in + * the `ciphers` option of `{@link createSecureContext}`. + * + * Not all supported ciphers are enabled by default. See + * [Modifying the default TLS cipher suite](https://nodejs.org/docs/latest-v25.x/api/tls.html#modifying-the-default-tls-cipher-suite). + * + * Cipher names that start with `'tls_'` are for TLSv1.3, all the others are for + * TLSv1.2 and below. + * + * ```js + * console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...] + * ``` + * @since v0.10.2 + */ + function getCiphers(): string[]; + /** + * Sets the default CA certificates used by Node.js TLS clients. If the provided + * certificates are parsed successfully, they will become the default CA + * certificate list returned by {@link getCACertificates} and used + * by subsequent TLS connections that don't specify their own CA certificates. + * The certificates will be deduplicated before being set as the default. + * + * This function only affects the current Node.js thread. Previous + * sessions cached by the HTTPS agent won't be affected by this change, so + * this method should be called before any unwanted cachable TLS connections are + * made. + * + * To use system CA certificates as the default: + * + * ```js + * import tls from 'node:tls'; + * tls.setDefaultCACertificates(tls.getCACertificates('system')); + * ``` + * + * This function completely replaces the default CA certificate list. To add additional + * certificates to the existing defaults, get the current certificates and append to them: + * + * ```js + * import tls from 'node:tls'; + * const currentCerts = tls.getCACertificates('default'); + * const additionalCerts = ['-----BEGIN CERTIFICATE-----\n...']; + * tls.setDefaultCACertificates([...currentCerts, ...additionalCerts]); + * ``` + * @since v24.5.0 + * @param certs An array of CA certificates in PEM format. + */ + function setDefaultCACertificates(certs: ReadonlyArray): void; + /** + * The default curve name to use for ECDH key agreement in a tls server. + * The default value is `'auto'`. See `{@link createSecureContext()}` for further + * information. + * @since v0.11.13 + */ + let DEFAULT_ECDH_CURVE: string; + /** + * The default value of the `maxVersion` option of `{@link createSecureContext()}`. + * It can be assigned any of the supported TLS protocol versions, + * `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. **Default:** `'TLSv1.3'`, unless + * changed using CLI options. Using `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using + * `--tls-max-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options + * are provided, the highest maximum is used. + * @since v11.4.0 + */ + let DEFAULT_MAX_VERSION: SecureVersion; + /** + * The default value of the `minVersion` option of `{@link createSecureContext()}`. + * It can be assigned any of the supported TLS protocol versions, + * `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. **Default:** `'TLSv1.2'`, unless + * changed using CLI options. Using `--tls-min-v1.0` sets the default to + * `'TLSv1'`. Using `--tls-min-v1.1` sets the default to `'TLSv1.1'`. Using + * `--tls-min-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options + * are provided, the lowest minimum is used. + * @since v11.4.0 + */ + let DEFAULT_MIN_VERSION: SecureVersion; + /** + * The default value of the `ciphers` option of `{@link createSecureContext()}`. + * It can be assigned any of the supported OpenSSL ciphers. + * Defaults to the content of `crypto.constants.defaultCoreCipherList`, unless + * changed using CLI options using `--tls-default-ciphers`. + * @since v19.8.0 + */ + let DEFAULT_CIPHERS: string; + /** + * An immutable array of strings representing the root certificates (in PEM format) + * from the bundled Mozilla CA store as supplied by the current Node.js version. + * + * The bundled CA store, as supplied by Node.js, is a snapshot of Mozilla CA store + * that is fixed at release time. It is identical on all supported platforms. + * @since v12.3.0 + */ + const rootCertificates: readonly string[]; +} +declare module "tls" { + export * from "node:tls"; +} diff --git a/backend/node_modules/@types/node/trace_events.d.ts b/backend/node_modules/@types/node/trace_events.d.ts new file mode 100644 index 0000000..b2c6b32 --- /dev/null +++ b/backend/node_modules/@types/node/trace_events.d.ts @@ -0,0 +1,197 @@ +/** + * The `node:trace_events` module provides a mechanism to centralize tracing information + * generated by V8, Node.js core, and userspace code. + * + * Tracing can be enabled with the `--trace-event-categories` command-line flag + * or by using the `trace_events` module. The `--trace-event-categories` flag + * accepts a list of comma-separated category names. + * + * The available categories are: + * + * * `node`: An empty placeholder. + * * `node.async_hooks`: Enables capture of detailed [`async_hooks`](https://nodejs.org/docs/latest-v25.x/api/async_hooks.html) trace data. + * The [`async_hooks`](https://nodejs.org/docs/latest-v25.x/api/async_hooks.html) events have a unique `asyncId` and a special `triggerId` `triggerAsyncId` property. + * * `node.bootstrap`: Enables capture of Node.js bootstrap milestones. + * * `node.console`: Enables capture of `console.time()` and `console.count()` output. + * * `node.threadpoolwork.sync`: Enables capture of trace data for threadpool synchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. + * * `node.threadpoolwork.async`: Enables capture of trace data for threadpool asynchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. + * * `node.dns.native`: Enables capture of trace data for DNS queries. + * * `node.net.native`: Enables capture of trace data for network. + * * `node.environment`: Enables capture of Node.js Environment milestones. + * * `node.fs.sync`: Enables capture of trace data for file system sync methods. + * * `node.fs_dir.sync`: Enables capture of trace data for file system sync directory methods. + * * `node.fs.async`: Enables capture of trace data for file system async methods. + * * `node.fs_dir.async`: Enables capture of trace data for file system async directory methods. + * * `node.perf`: Enables capture of [Performance API](https://nodejs.org/docs/latest-v25.x/api/perf_hooks.html) measurements. + * * `node.perf.usertiming`: Enables capture of only Performance API User Timing + * measures and marks. + * * `node.perf.timerify`: Enables capture of only Performance API timerify + * measurements. + * * `node.promises.rejections`: Enables capture of trace data tracking the number + * of unhandled Promise rejections and handled-after-rejections. + * * `node.vm.script`: Enables capture of trace data for the `node:vm` module's `runInNewContext()`, `runInContext()`, and `runInThisContext()` methods. + * * `v8`: The [V8](https://nodejs.org/docs/latest-v25.x/api/v8.html) events are GC, compiling, and execution related. + * * `node.http`: Enables capture of trace data for http request / response. + * + * By default the `node`, `node.async_hooks`, and `v8` categories are enabled. + * + * ```bash + * node --trace-event-categories v8,node,node.async_hooks server.js + * ``` + * + * Prior versions of Node.js required the use of the `--trace-events-enabled` flag to enable trace events. This requirement has been removed. However, the `--trace-events-enabled` flag _may_ still be + * used and will enable the `node`, `node.async_hooks`, and `v8` trace event categories by default. + * + * ```bash + * node --trace-events-enabled + * + * # is equivalent to + * + * node --trace-event-categories v8,node,node.async_hooks + * ``` + * + * Alternatively, trace events may be enabled using the `node:trace_events` module: + * + * ```js + * import trace_events from 'node:trace_events'; + * const tracing = trace_events.createTracing({ categories: ['node.perf'] }); + * tracing.enable(); // Enable trace event capture for the 'node.perf' category + * + * // do work + * + * tracing.disable(); // Disable trace event capture for the 'node.perf' category + * ``` + * + * Running Node.js with tracing enabled will produce log files that can be opened + * in the [`chrome://tracing`](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool) tab of Chrome. + * + * The logging file is by default called `node_trace.${rotation}.log`, where `${rotation}` is an incrementing log-rotation id. The filepath pattern can + * be specified with `--trace-event-file-pattern` that accepts a template + * string that supports `${rotation}` and `${pid}`: + * + * ```bash + * node --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotation}.log' server.js + * ``` + * + * To guarantee that the log file is properly generated after signal events like `SIGINT`, `SIGTERM`, or `SIGBREAK`, make sure to have the appropriate handlers + * in your code, such as: + * + * ```js + * process.on('SIGINT', function onSigint() { + * console.info('Received SIGINT.'); + * process.exit(130); // Or applicable exit code depending on OS and signal + * }); + * ``` + * + * The tracing system uses the same time source + * as the one used by `process.hrtime()`. + * However the trace-event timestamps are expressed in microseconds, + * unlike `process.hrtime()` which returns nanoseconds. + * + * The features from this module are not available in [`Worker`](https://nodejs.org/docs/latest-v25.x/api/worker_threads.html#class-worker) threads. + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/trace_events.js) + */ +declare module "node:trace_events" { + /** + * The `Tracing` object is used to enable or disable tracing for sets of + * categories. Instances are created using the + * `trace_events.createTracing()` method. + * + * When created, the `Tracing` object is disabled. Calling the + * `tracing.enable()` method adds the categories to the set of enabled trace + * event categories. Calling `tracing.disable()` will remove the categories + * from the set of enabled trace event categories. + */ + interface Tracing { + /** + * A comma-separated list of the trace event categories covered by this + * `Tracing` object. + * @since v10.0.0 + */ + readonly categories: string; + /** + * Disables this `Tracing` object. + * + * Only trace event categories _not_ covered by other enabled `Tracing` + * objects and _not_ specified by the `--trace-event-categories` flag + * will be disabled. + * + * ```js + * import trace_events from 'node:trace_events'; + * const t1 = trace_events.createTracing({ categories: ['node', 'v8'] }); + * const t2 = trace_events.createTracing({ categories: ['node.perf', 'node'] }); + * t1.enable(); + * t2.enable(); + * + * // Prints 'node,node.perf,v8' + * console.log(trace_events.getEnabledCategories()); + * + * t2.disable(); // Will only disable emission of the 'node.perf' category + * + * // Prints 'node,v8' + * console.log(trace_events.getEnabledCategories()); + * ``` + * @since v10.0.0 + */ + disable(): void; + /** + * Enables this `Tracing` object for the set of categories covered by + * the `Tracing` object. + * @since v10.0.0 + */ + enable(): void; + /** + * `true` only if the `Tracing` object has been enabled. + * @since v10.0.0 + */ + readonly enabled: boolean; + } + interface CreateTracingOptions { + /** + * An array of trace category names. Values included in the array are + * coerced to a string when possible. An error will be thrown if the + * value cannot be coerced. + */ + categories: string[]; + } + /** + * Creates and returns a `Tracing` object for the given set of `categories`. + * + * ```js + * import trace_events from 'node:trace_events'; + * const categories = ['node.perf', 'node.async_hooks']; + * const tracing = trace_events.createTracing({ categories }); + * tracing.enable(); + * // do stuff + * tracing.disable(); + * ``` + * @since v10.0.0 + */ + function createTracing(options: CreateTracingOptions): Tracing; + /** + * Returns a comma-separated list of all currently-enabled trace event + * categories. The current set of enabled trace event categories is determined + * by the _union_ of all currently-enabled `Tracing` objects and any categories + * enabled using the `--trace-event-categories` flag. + * + * Given the file `test.js` below, the command `node --trace-event-categories node.perf test.js` will print `'node.async_hooks,node.perf'` to the console. + * + * ```js + * import trace_events from 'node:trace_events'; + * const t1 = trace_events.createTracing({ categories: ['node.async_hooks'] }); + * const t2 = trace_events.createTracing({ categories: ['node.perf'] }); + * const t3 = trace_events.createTracing({ categories: ['v8'] }); + * + * t1.enable(); + * t2.enable(); + * + * console.log(trace_events.getEnabledCategories()); + * ``` + * @since v10.0.0 + */ + function getEnabledCategories(): string | undefined; +} +declare module "trace_events" { + export * from "node:trace_events"; +} diff --git a/backend/node_modules/@types/node/ts5.6/buffer.buffer.d.ts b/backend/node_modules/@types/node/ts5.6/buffer.buffer.d.ts new file mode 100644 index 0000000..bd32dc6 --- /dev/null +++ b/backend/node_modules/@types/node/ts5.6/buffer.buffer.d.ts @@ -0,0 +1,462 @@ +declare module "node:buffer" { + global { + interface BufferConstructor { + // see ../buffer.d.ts for implementation shared with all TypeScript versions + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. + */ + new(str: string, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). + */ + new(size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: ArrayLike): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}/{SharedArrayBuffer}. + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. + */ + new(arrayBuffer: ArrayBufferLike): Buffer; + /** + * Allocates a new `Buffer` using an `array` of bytes in the range `0` – `255`. + * Array entries outside that range will be truncated to fit into it. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'. + * const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); + * ``` + * + * If `array` is an `Array`-like object (that is, one with a `length` property of + * type `number`), it is treated as if it is an array, unless it is a `Buffer` or + * a `Uint8Array`. This means all other `TypedArray` variants get treated as an + * `Array`. To create a `Buffer` from the bytes backing a `TypedArray`, use + * `Buffer.copyBytesFrom()`. + * + * A `TypeError` will be thrown if `array` is not an `Array` or another type + * appropriate for `Buffer.from()` variants. + * + * `Buffer.from(array)` and `Buffer.from(string)` may also use the internal + * `Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v5.10.0 + */ + from(array: WithImplicitCoercion>): Buffer; + /** + * This creates a view of the `ArrayBuffer` without copying the underlying + * memory. For example, when passed a reference to the `.buffer` property of a + * `TypedArray` instance, the newly created `Buffer` will share the same + * allocated memory as the `TypedArray`'s underlying `ArrayBuffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const arr = new Uint16Array(2); + * + * arr[0] = 5000; + * arr[1] = 4000; + * + * // Shares memory with `arr`. + * const buf = Buffer.from(arr.buffer); + * + * console.log(buf); + * // Prints: + * + * // Changing the original Uint16Array changes the Buffer also. + * arr[1] = 6000; + * + * console.log(buf); + * // Prints: + * ``` + * + * The optional `byteOffset` and `length` arguments specify a memory range within + * the `arrayBuffer` that will be shared by the `Buffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const ab = new ArrayBuffer(10); + * const buf = Buffer.from(ab, 0, 2); + * + * console.log(buf.length); + * // Prints: 2 + * ``` + * + * A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer` or a + * `SharedArrayBuffer` or another type appropriate for `Buffer.from()` + * variants. + * + * It is important to remember that a backing `ArrayBuffer` can cover a range + * of memory that extends beyond the bounds of a `TypedArray` view. A new + * `Buffer` created using the `buffer` property of a `TypedArray` may extend + * beyond the range of the `TypedArray`: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements + * const arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements + * console.log(arrA.buffer === arrB.buffer); // true + * + * const buf = Buffer.from(arrB.buffer); + * console.log(buf); + * // Prints: + * ``` + * @since v5.10.0 + * @param arrayBuffer An `ArrayBuffer`, `SharedArrayBuffer`, for example the + * `.buffer` property of a `TypedArray`. + * @param byteOffset Index of first byte to expose. **Default:** `0`. + * @param length Number of bytes to expose. **Default:** + * `arrayBuffer.byteLength - byteOffset`. + */ + from( + arrayBuffer: WithImplicitCoercion, + byteOffset?: number, + length?: number, + ): Buffer; + /** + * Creates a new `Buffer` containing `string`. The `encoding` parameter identifies + * the character encoding to be used when converting `string` into bytes. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('this is a tést'); + * const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); + * + * console.log(buf1.toString()); + * // Prints: this is a tést + * console.log(buf2.toString()); + * // Prints: this is a tést + * console.log(buf1.toString('latin1')); + * // Prints: this is a tést + * ``` + * + * A `TypeError` will be thrown if `string` is not a string or another type + * appropriate for `Buffer.from()` variants. + * + * `Buffer.from(string)` may also use the internal `Buffer` pool like + * `Buffer.allocUnsafe()` does. + * @since v5.10.0 + * @param string A string to encode. + * @param encoding The encoding of `string`. **Default:** `'utf8'`. + */ + from(string: WithImplicitCoercion, encoding?: BufferEncoding): Buffer; + from(arrayOrString: WithImplicitCoercion | string>): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + of(...items: number[]): Buffer; + /** + * Returns a new `Buffer` which is the result of concatenating all the `Buffer` instances in the `list` together. + * + * If the list has no items, or if the `totalLength` is 0, then a new zero-length `Buffer` is returned. + * + * If `totalLength` is not provided, it is calculated from the `Buffer` instances + * in `list` by adding their lengths. + * + * If `totalLength` is provided, it is coerced to an unsigned integer. If the + * combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is + * truncated to `totalLength`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a single `Buffer` from a list of three `Buffer` instances. + * + * const buf1 = Buffer.alloc(10); + * const buf2 = Buffer.alloc(14); + * const buf3 = Buffer.alloc(18); + * const totalLength = buf1.length + buf2.length + buf3.length; + * + * console.log(totalLength); + * // Prints: 42 + * + * const bufA = Buffer.concat([buf1, buf2, buf3], totalLength); + * + * console.log(bufA); + * // Prints: + * console.log(bufA.length); + * // Prints: 42 + * ``` + * + * `Buffer.concat()` may also use the internal `Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v0.7.11 + * @param list List of `Buffer` or {@link Uint8Array} instances to concatenate. + * @param totalLength Total length of the `Buffer` instances in `list` when concatenated. + */ + concat(list: readonly Uint8Array[], totalLength?: number): Buffer; + /** + * Copies the underlying memory of `view` into a new `Buffer`. + * + * ```js + * const u16 = new Uint16Array([0, 0xffff]); + * const buf = Buffer.copyBytesFrom(u16, 1, 1); + * u16[1] = 0; + * console.log(buf.length); // 2 + * console.log(buf[0]); // 255 + * console.log(buf[1]); // 255 + * ``` + * @since v19.8.0 + * @param view The {TypedArray} to copy. + * @param [offset=0] The starting offset within `view`. + * @param [length=view.length - offset] The number of elements from `view` to copy. + */ + copyBytesFrom(view: NodeJS.TypedArray, offset?: number, length?: number): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(5); + * + * console.log(buf); + * // Prints: + * ``` + * + * If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. + * + * If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(5, 'a'); + * + * console.log(buf); + * // Prints: + * ``` + * + * If both `fill` and `encoding` are specified, the allocated `Buffer` will be + * initialized by calling `buf.fill(fill, encoding)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); + * + * console.log(buf); + * // Prints: + * ``` + * + * Calling `Buffer.alloc()` can be measurably slower than the alternative `Buffer.allocUnsafe()` but ensures that the newly created `Buffer` instance + * contents will never contain sensitive data from previous allocations, including + * data that might not have been allocated for `Buffer`s. + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + * @param [fill=0] A value to pre-fill the new `Buffer` with. + * @param [encoding='utf8'] If `fill` is a string, this is its encoding. + */ + alloc(size: number, fill?: string | Uint8Array | number, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `Buffer.alloc()` instead to initialize`Buffer` instances with zeroes. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(10); + * + * console.log(buf); + * // Prints (contents may vary): + * + * buf.fill(0); + * + * console.log(buf); + * // Prints: + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * + * The `Buffer` module pre-allocates an internal `Buffer` instance of + * size `Buffer.poolSize` that is used as a pool for the fast allocation of new `Buffer` instances created using `Buffer.allocUnsafe()`, `Buffer.from(array)`, + * and `Buffer.concat()` only when `size` is less than `Buffer.poolSize >>> 1` (floor of `Buffer.poolSize` divided by two). + * + * Use of this pre-allocated internal memory pool is a key difference between + * calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. + * Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`pool, while `Buffer.allocUnsafe(size).fill(fill)`_will_ use the internal`Buffer` pool if `size` is less + * than or equal to half `Buffer.poolSize`. The + * difference is subtle but can be important when an application requires the + * additional performance that `Buffer.allocUnsafe()` provides. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafe(size: number): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. A zero-length `Buffer` is created if + * `size` is 0. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `buf.fill(0)` to initialize + * such `Buffer` instances with zeroes. + * + * When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, + * allocations under 4 KiB are sliced from a single pre-allocated `Buffer`. This + * allows applications to avoid the garbage collection overhead of creating many + * individually allocated `Buffer` instances. This approach improves both + * performance and memory usage by eliminating the need to track and clean up as + * many individual `ArrayBuffer` objects. + * + * However, in the case where a developer may need to retain a small chunk of + * memory from a pool for an indeterminate amount of time, it may be appropriate + * to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and + * then copying out the relevant bits. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Need to keep around a few small chunks of memory. + * const store = []; + * + * socket.on('readable', () => { + * let data; + * while (null !== (data = readable.read())) { + * // Allocate for retained data. + * const sb = Buffer.allocUnsafeSlow(10); + * + * // Copy the data into the new allocation. + * data.copy(sb, 0, 0, 10); + * + * store.push(sb); + * } + * }); + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.12.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafeSlow(size: number): Buffer; + } + interface Buffer extends Uint8Array { + // see ../buffer.d.ts for implementation shared with all TypeScript versions + + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * This method is not compatible with the `Uint8Array.prototype.slice()`, + * which is a superclass of `Buffer`. To copy the slice, use`Uint8Array.prototype.slice()`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * const copiedBuf = Uint8Array.prototype.slice.call(buf); + * copiedBuf[0]++; + * console.log(copiedBuf.toString()); + * // Prints: cuffer + * + * console.log(buf.toString()); + * // Prints: buffer + * + * // With buf.slice(), the original buffer is modified. + * const notReallyCopiedBuf = buf.slice(); + * notReallyCopiedBuf[0]++; + * console.log(notReallyCopiedBuf.toString()); + * // Prints: cuffer + * console.log(buf.toString()); + * // Also prints: cuffer (!) + * ``` + * @since v0.3.0 + * @deprecated Use `subarray` instead. + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + slice(start?: number, end?: number): Buffer; + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * Specifying `end` greater than `buf.length` will return the same result as + * that of `end` equal to `buf.length`. + * + * This method is inherited from [`TypedArray.prototype.subarray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray). + * + * Modifying the new `Buffer` slice will modify the memory in the original `Buffer`because the allocated memory of the two objects overlap. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte + * // from the original `Buffer`. + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * const buf2 = buf1.subarray(0, 3); + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: abc + * + * buf1[0] = 33; + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: !bc + * ``` + * + * Specifying negative indexes causes the slice to be generated relative to the + * end of `buf` rather than the beginning. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * console.log(buf.subarray(-6, -1).toString()); + * // Prints: buffe + * // (Equivalent to buf.subarray(0, 5).) + * + * console.log(buf.subarray(-6, -2).toString()); + * // Prints: buff + * // (Equivalent to buf.subarray(0, 4).) + * + * console.log(buf.subarray(-5, -2).toString()); + * // Prints: uff + * // (Equivalent to buf.subarray(1, 4).) + * ``` + * @since v3.0.0 + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + subarray(start?: number, end?: number): Buffer; + } + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedBuffer = Buffer; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type AllowSharedBuffer = Buffer; + } +} diff --git a/backend/node_modules/@types/node/ts5.6/compatibility/float16array.d.ts b/backend/node_modules/@types/node/ts5.6/compatibility/float16array.d.ts new file mode 100644 index 0000000..f148cc4 --- /dev/null +++ b/backend/node_modules/@types/node/ts5.6/compatibility/float16array.d.ts @@ -0,0 +1,71 @@ +// Interface declaration for Float16Array, required in @types/node v24+. +// These definitions are specific to TS <=5.6. + +// This needs all of the "common" properties/methods of the TypedArrays, +// otherwise the type unions `TypedArray` and `ArrayBufferView` will be +// empty objects. +interface Float16Array extends Pick { + readonly BYTES_PER_ELEMENT: number; + readonly buffer: ArrayBufferLike; + readonly byteLength: number; + readonly byteOffset: number; + readonly length: number; + readonly [Symbol.toStringTag]: "Float16Array"; + at(index: number): number | undefined; + copyWithin(target: number, start: number, end?: number): this; + every(predicate: (value: number, index: number, array: Float16Array) => unknown, thisArg?: any): boolean; + fill(value: number, start?: number, end?: number): this; + filter(predicate: (value: number, index: number, array: Float16Array) => any, thisArg?: any): Float16Array; + find(predicate: (value: number, index: number, obj: Float16Array) => boolean, thisArg?: any): number | undefined; + findIndex(predicate: (value: number, index: number, obj: Float16Array) => boolean, thisArg?: any): number; + findLast( + predicate: (value: number, index: number, array: Float16Array) => value is S, + thisArg?: any, + ): S | undefined; + findLast( + predicate: (value: number, index: number, array: Float16Array) => unknown, + thisArg?: any, + ): number | undefined; + findLastIndex(predicate: (value: number, index: number, array: Float16Array) => unknown, thisArg?: any): number; + forEach(callbackfn: (value: number, index: number, array: Float16Array) => void, thisArg?: any): void; + includes(searchElement: number, fromIndex?: number): boolean; + indexOf(searchElement: number, fromIndex?: number): number; + join(separator?: string): string; + lastIndexOf(searchElement: number, fromIndex?: number): number; + map(callbackfn: (value: number, index: number, array: Float16Array) => number, thisArg?: any): Float16Array; + reduce( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float16Array) => number, + ): number; + reduce( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float16Array) => number, + initialValue: number, + ): number; + reduce( + callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float16Array) => U, + initialValue: U, + ): U; + reduceRight( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float16Array) => number, + ): number; + reduceRight( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float16Array) => number, + initialValue: number, + ): number; + reduceRight( + callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float16Array) => U, + initialValue: U, + ): U; + reverse(): Float16Array; + set(array: ArrayLike, offset?: number): void; + slice(start?: number, end?: number): Float16Array; + some(predicate: (value: number, index: number, array: Float16Array) => unknown, thisArg?: any): boolean; + sort(compareFn?: (a: number, b: number) => number): this; + subarray(begin?: number, end?: number): Float16Array; + toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string; + toReversed(): Float16Array; + toSorted(compareFn?: (a: number, b: number) => number): Float16Array; + toString(): string; + valueOf(): Float16Array; + with(index: number, value: number): Float16Array; + [index: number]: number; +} diff --git a/backend/node_modules/@types/node/ts5.6/globals.typedarray.d.ts b/backend/node_modules/@types/node/ts5.6/globals.typedarray.d.ts new file mode 100644 index 0000000..57a1ab4 --- /dev/null +++ b/backend/node_modules/@types/node/ts5.6/globals.typedarray.d.ts @@ -0,0 +1,36 @@ +export {}; // Make this a module + +declare global { + namespace NodeJS { + type TypedArray = + | Uint8Array + | Uint8ClampedArray + | Uint16Array + | Uint32Array + | Int8Array + | Int16Array + | Int32Array + | BigUint64Array + | BigInt64Array + | Float16Array + | Float32Array + | Float64Array; + type ArrayBufferView = TypedArray | DataView; + + type NonSharedUint8Array = Uint8Array; + type NonSharedUint8ClampedArray = Uint8ClampedArray; + type NonSharedUint16Array = Uint16Array; + type NonSharedUint32Array = Uint32Array; + type NonSharedInt8Array = Int8Array; + type NonSharedInt16Array = Int16Array; + type NonSharedInt32Array = Int32Array; + type NonSharedBigUint64Array = BigUint64Array; + type NonSharedBigInt64Array = BigInt64Array; + type NonSharedFloat16Array = Float16Array; + type NonSharedFloat32Array = Float32Array; + type NonSharedFloat64Array = Float64Array; + type NonSharedDataView = DataView; + type NonSharedTypedArray = TypedArray; + type NonSharedArrayBufferView = ArrayBufferView; + } +} diff --git a/backend/node_modules/@types/node/ts5.6/index.d.ts b/backend/node_modules/@types/node/ts5.6/index.d.ts new file mode 100644 index 0000000..a157660 --- /dev/null +++ b/backend/node_modules/@types/node/ts5.6/index.d.ts @@ -0,0 +1,117 @@ +/** + * License for programmatically and manually incorporated + * documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc + * + * Copyright Node.js 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. + */ + +// NOTE: These definitions support Node.js and TypeScript 5.2 through 5.6. + +// Reference required TypeScript libraries: +/// +/// + +// TypeScript library polyfills required for TypeScript <=5.6: +/// + +// Iterator definitions required for compatibility with TypeScript <5.6: +/// + +// Definitions for Node.js modules specific to TypeScript <=5.6: +/// +/// + +// Definitions for Node.js modules that are not specific to any version of TypeScript: +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/backend/node_modules/@types/node/ts5.7/compatibility/float16array.d.ts b/backend/node_modules/@types/node/ts5.7/compatibility/float16array.d.ts new file mode 100644 index 0000000..110b1eb --- /dev/null +++ b/backend/node_modules/@types/node/ts5.7/compatibility/float16array.d.ts @@ -0,0 +1,72 @@ +// Interface declaration for Float16Array, required in @types/node v24+. +// These definitions are specific to TS 5.7. + +// This needs all of the "common" properties/methods of the TypedArrays, +// otherwise the type unions `TypedArray` and `ArrayBufferView` will be +// empty objects. +interface Float16Array { + readonly BYTES_PER_ELEMENT: number; + readonly buffer: TArrayBuffer; + readonly byteLength: number; + readonly byteOffset: number; + readonly length: number; + readonly [Symbol.toStringTag]: "Float16Array"; + at(index: number): number | undefined; + copyWithin(target: number, start: number, end?: number): this; + entries(): ArrayIterator<[number, number]>; + every(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): boolean; + fill(value: number, start?: number, end?: number): this; + filter(predicate: (value: number, index: number, array: this) => any, thisArg?: any): Float16Array; + find(predicate: (value: number, index: number, obj: this) => boolean, thisArg?: any): number | undefined; + findIndex(predicate: (value: number, index: number, obj: this) => boolean, thisArg?: any): number; + findLast( + predicate: (value: number, index: number, array: this) => value is S, + thisArg?: any, + ): S | undefined; + findLast(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): number | undefined; + findLastIndex(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): number; + forEach(callbackfn: (value: number, index: number, array: this) => void, thisArg?: any): void; + includes(searchElement: number, fromIndex?: number): boolean; + indexOf(searchElement: number, fromIndex?: number): number; + join(separator?: string): string; + keys(): ArrayIterator; + lastIndexOf(searchElement: number, fromIndex?: number): number; + map(callbackfn: (value: number, index: number, array: this) => number, thisArg?: any): Float16Array; + reduce( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, + ): number; + reduce( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, + initialValue: number, + ): number; + reduce( + callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U, + initialValue: U, + ): U; + reduceRight( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, + ): number; + reduceRight( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, + initialValue: number, + ): number; + reduceRight( + callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U, + initialValue: U, + ): U; + reverse(): this; + set(array: ArrayLike, offset?: number): void; + slice(start?: number, end?: number): Float16Array; + some(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): boolean; + sort(compareFn?: (a: number, b: number) => number): this; + subarray(begin?: number, end?: number): Float16Array; + toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string; + toReversed(): Float16Array; + toSorted(compareFn?: (a: number, b: number) => number): Float16Array; + toString(): string; + valueOf(): this; + values(): ArrayIterator; + with(index: number, value: number): Float16Array; + [Symbol.iterator](): ArrayIterator; + [index: number]: number; +} diff --git a/backend/node_modules/@types/node/ts5.7/index.d.ts b/backend/node_modules/@types/node/ts5.7/index.d.ts new file mode 100644 index 0000000..32c541b --- /dev/null +++ b/backend/node_modules/@types/node/ts5.7/index.d.ts @@ -0,0 +1,117 @@ +/** + * License for programmatically and manually incorporated + * documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc + * + * Copyright Node.js 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. + */ + +// NOTE: These definitions support Node.js and TypeScript 5.7. + +// Reference required TypeScript libraries: +/// +/// + +// TypeScript library polyfills required for TypeScript 5.7: +/// + +// Iterator definitions required for compatibility with TypeScript <5.6: +/// + +// Definitions for Node.js modules specific to TypeScript 5.7+: +/// +/// + +// Definitions for Node.js modules that are not specific to any version of TypeScript: +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/backend/node_modules/@types/node/tty.d.ts b/backend/node_modules/@types/node/tty.d.ts new file mode 100644 index 0000000..9b97a1e --- /dev/null +++ b/backend/node_modules/@types/node/tty.d.ts @@ -0,0 +1,250 @@ +/** + * The `node:tty` module provides the `tty.ReadStream` and `tty.WriteStream` classes. In most cases, it will not be necessary or possible to use this module + * directly. However, it can be accessed using: + * + * ```js + * import tty from 'node:tty'; + * ``` + * + * When Node.js detects that it is being run with a text terminal ("TTY") + * attached, `process.stdin` will, by default, be initialized as an instance of `tty.ReadStream` and both `process.stdout` and `process.stderr` will, by + * default, be instances of `tty.WriteStream`. The preferred method of determining + * whether Node.js is being run within a TTY context is to check that the value of + * the `process.stdout.isTTY` property is `true`: + * + * ```console + * $ node -p -e "Boolean(process.stdout.isTTY)" + * true + * $ node -p -e "Boolean(process.stdout.isTTY)" | cat + * false + * ``` + * + * In most cases, there should be little to no reason for an application to + * manually create instances of the `tty.ReadStream` and `tty.WriteStream` classes. + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/tty.js) + */ +declare module "node:tty" { + import * as net from "node:net"; + /** + * The `tty.isatty()` method returns `true` if the given `fd` is associated with + * a TTY and `false` if it is not, including whenever `fd` is not a non-negative + * integer. + * @since v0.5.8 + * @param fd A numeric file descriptor + */ + function isatty(fd: number): boolean; + /** + * Represents the readable side of a TTY. In normal circumstances `process.stdin` will be the only `tty.ReadStream` instance in a Node.js + * process and there should be no reason to create additional instances. + * @since v0.5.8 + */ + class ReadStream extends net.Socket { + constructor(fd: number, options?: net.SocketConstructorOpts); + /** + * A `boolean` that is `true` if the TTY is currently configured to operate as a + * raw device. + * + * This flag is always `false` when a process starts, even if the terminal is + * operating in raw mode. Its value will change with subsequent calls to `setRawMode`. + * @since v0.7.7 + */ + isRaw: boolean; + /** + * Allows configuration of `tty.ReadStream` so that it operates as a raw device. + * + * When in raw mode, input is always available character-by-character, not + * including modifiers. Additionally, all special processing of characters by the + * terminal is disabled, including echoing input + * characters. Ctrl+C will no longer cause a `SIGINT` when + * in this mode. + * @since v0.7.7 + * @param mode If `true`, configures the `tty.ReadStream` to operate as a raw device. If `false`, configures the `tty.ReadStream` to operate in its default mode. The `readStream.isRaw` + * property will be set to the resulting mode. + * @return The read stream instance. + */ + setRawMode(mode: boolean): this; + /** + * A `boolean` that is always `true` for `tty.ReadStream` instances. + * @since v0.5.8 + */ + isTTY: boolean; + } + /** + * -1 - to the left from cursor + * 0 - the entire line + * 1 - to the right from cursor + */ + type Direction = -1 | 0 | 1; + interface WriteStreamEventMap extends net.SocketEventMap { + "resize": []; + } + /** + * Represents the writable side of a TTY. In normal circumstances, `process.stdout` and `process.stderr` will be the only`tty.WriteStream` instances created for a Node.js process and there + * should be no reason to create additional instances. + * @since v0.5.8 + */ + class WriteStream extends net.Socket { + constructor(fd: number); + /** + * `writeStream.clearLine()` clears the current line of this `WriteStream` in a + * direction identified by `dir`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + clearLine(dir: Direction, callback?: () => void): boolean; + /** + * `writeStream.clearScreenDown()` clears this `WriteStream` from the current + * cursor down. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + clearScreenDown(callback?: () => void): boolean; + /** + * `writeStream.cursorTo()` moves this `WriteStream`'s cursor to the specified + * position. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + cursorTo(x: number, y?: number, callback?: () => void): boolean; + cursorTo(x: number, callback: () => void): boolean; + /** + * `writeStream.moveCursor()` moves this `WriteStream`'s cursor _relative_ to its + * current position. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + moveCursor(dx: number, dy: number, callback?: () => void): boolean; + /** + * Returns: + * + * * `1` for 2, + * * `4` for 16, + * * `8` for 256, + * * `24` for 16,777,216 colors supported. + * + * Use this to determine what colors the terminal supports. Due to the nature of + * colors in terminals it is possible to either have false positives or false + * negatives. It depends on process information and the environment variables that + * may lie about what terminal is used. + * It is possible to pass in an `env` object to simulate the usage of a specific + * terminal. This can be useful to check how specific environment settings behave. + * + * To enforce a specific color support, use one of the below environment settings. + * + * * 2 colors: `FORCE_COLOR = 0` (Disables colors) + * * 16 colors: `FORCE_COLOR = 1` + * * 256 colors: `FORCE_COLOR = 2` + * * 16,777,216 colors: `FORCE_COLOR = 3` + * + * Disabling color support is also possible by using the `NO_COLOR` and `NODE_DISABLE_COLORS` environment variables. + * @since v9.9.0 + * @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal. + */ + getColorDepth(env?: object): number; + /** + * Returns `true` if the `writeStream` supports at least as many colors as provided + * in `count`. Minimum support is 2 (black and white). + * + * This has the same false positives and negatives as described in `writeStream.getColorDepth()`. + * + * ```js + * process.stdout.hasColors(); + * // Returns true or false depending on if `stdout` supports at least 16 colors. + * process.stdout.hasColors(256); + * // Returns true or false depending on if `stdout` supports at least 256 colors. + * process.stdout.hasColors({ TMUX: '1' }); + * // Returns true. + * process.stdout.hasColors(2 ** 24, { TMUX: '1' }); + * // Returns false (the environment setting pretends to support 2 ** 8 colors). + * ``` + * @since v11.13.0, v10.16.0 + * @param [count=16] The number of colors that are requested (minimum 2). + * @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal. + */ + hasColors(count?: number): boolean; + hasColors(env?: object): boolean; + hasColors(count: number, env?: object): boolean; + /** + * `writeStream.getWindowSize()` returns the size of the TTY + * corresponding to this `WriteStream`. The array is of the type `[numColumns, numRows]` where `numColumns` and `numRows` represent the number + * of columns and rows in the corresponding TTY. + * @since v0.7.7 + */ + getWindowSize(): [number, number]; + /** + * A `number` specifying the number of columns the TTY currently has. This property + * is updated whenever the `'resize'` event is emitted. + * @since v0.7.7 + */ + columns: number; + /** + * A `number` specifying the number of rows the TTY currently has. This property + * is updated whenever the `'resize'` event is emitted. + * @since v0.7.7 + */ + rows: number; + /** + * A `boolean` that is always `true`. + * @since v0.5.8 + */ + isTTY: boolean; + // #region InternalEventEmitter + addListener( + eventName: E, + listener: (...args: WriteStreamEventMap[E]) => void, + ): this; + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(eventName: E, ...args: WriteStreamEventMap[E]): boolean; + emit(eventName: string | symbol, ...args: any[]): boolean; + listenerCount( + eventName: E, + listener?: (...args: WriteStreamEventMap[E]) => void, + ): number; + listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number; + listeners(eventName: E): ((...args: WriteStreamEventMap[E]) => void)[]; + listeners(eventName: string | symbol): ((...args: any[]) => void)[]; + off( + eventName: E, + listener: (...args: WriteStreamEventMap[E]) => void, + ): this; + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + on( + eventName: E, + listener: (...args: WriteStreamEventMap[E]) => void, + ): this; + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + once( + eventName: E, + listener: (...args: WriteStreamEventMap[E]) => void, + ): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + eventName: E, + listener: (...args: WriteStreamEventMap[E]) => void, + ): this; + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + eventName: E, + listener: (...args: WriteStreamEventMap[E]) => void, + ): this; + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + rawListeners(eventName: E): ((...args: WriteStreamEventMap[E]) => void)[]; + rawListeners(eventName: string | symbol): ((...args: any[]) => void)[]; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + removeAllListeners(eventName?: E): this; + removeAllListeners(eventName?: string | symbol): this; + removeListener( + eventName: E, + listener: (...args: WriteStreamEventMap[E]) => void, + ): this; + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + // #endregion + } +} +declare module "tty" { + export * from "node:tty"; +} diff --git a/backend/node_modules/@types/node/url.d.ts b/backend/node_modules/@types/node/url.d.ts new file mode 100644 index 0000000..6f5b885 --- /dev/null +++ b/backend/node_modules/@types/node/url.d.ts @@ -0,0 +1,519 @@ +/** + * The `node:url` module provides utilities for URL resolution and parsing. It can + * be accessed using: + * + * ```js + * import url from 'node:url'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/url.js) + */ +declare module "node:url" { + import { Blob, NonSharedBuffer } from "node:buffer"; + import { ClientRequestArgs } from "node:http"; + import { ParsedUrlQuery, ParsedUrlQueryInput } from "node:querystring"; + // Input to `url.format` + interface UrlObject { + auth?: string | null | undefined; + hash?: string | null | undefined; + host?: string | null | undefined; + hostname?: string | null | undefined; + href?: string | null | undefined; + pathname?: string | null | undefined; + protocol?: string | null | undefined; + search?: string | null | undefined; + slashes?: boolean | null | undefined; + port?: string | number | null | undefined; + query?: string | null | ParsedUrlQueryInput | undefined; + } + // Output of `url.parse` + interface Url { + auth: string | null; + hash: string | null; + host: string | null; + hostname: string | null; + href: string; + path: string | null; + pathname: string | null; + protocol: string | null; + search: string | null; + slashes: boolean | null; + port: string | null; + query: string | null | ParsedUrlQuery; + } + interface UrlWithParsedQuery extends Url { + query: ParsedUrlQuery; + } + interface UrlWithStringQuery extends Url { + query: string | null; + } + interface FileUrlToPathOptions { + /** + * `true` if the `path` should be return as a windows filepath, `false` for posix, and `undefined` for the system default. + * @default undefined + * @since v22.1.0 + */ + windows?: boolean | undefined; + } + interface PathToFileUrlOptions { + /** + * `true` if the `path` should be return as a windows filepath, `false` for posix, and `undefined` for the system default. + * @default undefined + * @since v22.1.0 + */ + windows?: boolean | undefined; + } + /** + * The `url.parse()` method takes a URL string, parses it, and returns a URL + * object. + * + * A `TypeError` is thrown if `urlString` is not a string. + * + * A `URIError` is thrown if the `auth` property is present but cannot be decoded. + * + * `url.parse()` uses a lenient, non-standard algorithm for parsing URL + * strings. It is prone to security issues such as [host name spoofing](https://hackerone.com/reports/678487) + * and incorrect handling of usernames and passwords. Do not use with untrusted + * input. CVEs are not issued for `url.parse()` vulnerabilities. Use the + * [WHATWG URL](https://nodejs.org/docs/latest-v25.x/api/url.html#the-whatwg-url-api) API instead, for example: + * + * ```js + * function getURL(req) { + * const proto = req.headers['x-forwarded-proto'] || 'https'; + * const host = req.headers['x-forwarded-host'] || req.headers.host || 'example.com'; + * return new URL(req.url || '/', `${proto}://${host}`); + * } + * ``` + * + * The example above assumes well-formed headers are forwarded from a reverse + * proxy to your Node.js server. If you are not using a reverse proxy, you should + * use the example below: + * + * ```js + * function getURL(req) { + * return new URL(req.url || '/', 'https://example.com'); + * } + * ``` + * @since v0.1.25 + * @deprecated Use the WHATWG URL API instead. + * @param urlString The URL string to parse. + * @param parseQueryString If `true`, the `query` property will always + * be set to an object returned by the [`querystring`](https://nodejs.org/docs/latest-v25.x/api/querystring.html) module's `parse()` + * method. If `false`, the `query` property on the returned URL object will be an + * unparsed, undecoded string. **Default:** `false`. + * @param slashesDenoteHost If `true`, the first token after the literal + * string `//` and preceding the next `/` will be interpreted as the `host`. + * For instance, given `//foo/bar`, the result would be + * `{host: 'foo', pathname: '/bar'}` rather than `{pathname: '//foo/bar'}`. + * **Default:** `false`. + */ + function parse( + urlString: string, + parseQueryString?: false, + slashesDenoteHost?: boolean, + ): UrlWithStringQuery; + function parse(urlString: string, parseQueryString: true, slashesDenoteHost?: boolean): UrlWithParsedQuery; + function parse(urlString: string, parseQueryString: boolean, slashesDenoteHost?: boolean): Url; + /** + * The `url.format()` method returns a formatted URL string derived from `urlObject`. + * + * ```js + * import url from 'node:url'; + * url.format({ + * protocol: 'https', + * hostname: 'example.com', + * pathname: '/some/path', + * query: { + * page: 1, + * format: 'json', + * }, + * }); + * + * // => 'https://example.com/some/path?page=1&format=json' + * ``` + * + * If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. + * + * The formatting process operates as follows: + * + * * A new empty string `result` is created. + * * If `urlObject.protocol` is a string, it is appended as-is to `result`. + * * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. + * * For all string values of `urlObject.protocol` that _do not end_ with an ASCII + * colon (`:`) character, the literal string `:` will be appended to `result`. + * * If either of the following conditions is true, then the literal string `//` will be appended to `result`: + * * `urlObject.slashes` property is true; + * * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or `file`; + * * If the value of the `urlObject.auth` property is truthy, and either `urlObject.host` or `urlObject.hostname` are not `undefined`, the value of `urlObject.auth` will be coerced into a string + * and appended to `result` followed by the literal string `@`. + * * If the `urlObject.host` property is `undefined` then: + * * If the `urlObject.hostname` is a string, it is appended to `result`. + * * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, + * an `Error` is thrown. + * * If the `urlObject.port` property value is truthy, and `urlObject.hostname` is not `undefined`: + * * The literal string `:` is appended to `result`, and + * * The value of `urlObject.port` is coerced to a string and appended to `result`. + * * Otherwise, if the `urlObject.host` property value is truthy, the value of `urlObject.host` is coerced to a string and appended to `result`. + * * If the `urlObject.pathname` property is a string that is not an empty string: + * * If the `urlObject.pathname` _does not start_ with an ASCII forward slash + * (`/`), then the literal string `'/'` is appended to `result`. + * * The value of `urlObject.pathname` is appended to `result`. + * * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result` followed by the output of calling the + * `querystring` module's `stringify()` method passing the value of `urlObject.query`. + * * Otherwise, if `urlObject.search` is a string: + * * If the value of `urlObject.search` _does not start_ with the ASCII question + * mark (`?`) character, the literal string `?` is appended to `result`. + * * The value of `urlObject.search` is appended to `result`. + * * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.hash` property is a string: + * * If the value of `urlObject.hash` _does not start_ with the ASCII hash (`#`) + * character, the literal string `#` is appended to `result`. + * * The value of `urlObject.hash` is appended to `result`. + * * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a + * string, an `Error` is thrown. + * * `result` is returned. + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. + */ + function format(urlObject: URL, options?: URLFormatOptions): string; + /** + * The `url.format()` method returns a formatted URL string derived from `urlObject`. + * + * ```js + * import url from 'node:url'; + * url.format({ + * protocol: 'https', + * hostname: 'example.com', + * pathname: '/some/path', + * query: { + * page: 1, + * format: 'json', + * }, + * }); + * + * // => 'https://example.com/some/path?page=1&format=json' + * ``` + * + * If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. + * + * The formatting process operates as follows: + * + * * A new empty string `result` is created. + * * If `urlObject.protocol` is a string, it is appended as-is to `result`. + * * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. + * * For all string values of `urlObject.protocol` that _do not end_ with an ASCII + * colon (`:`) character, the literal string `:` will be appended to `result`. + * * If either of the following conditions is true, then the literal string `//` will be appended to `result`: + * * `urlObject.slashes` property is true; + * * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or `file`; + * * If the value of the `urlObject.auth` property is truthy, and either `urlObject.host` or `urlObject.hostname` are not `undefined`, the value of `urlObject.auth` will be coerced into a string + * and appended to `result` followed by the literal string `@`. + * * If the `urlObject.host` property is `undefined` then: + * * If the `urlObject.hostname` is a string, it is appended to `result`. + * * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, + * an `Error` is thrown. + * * If the `urlObject.port` property value is truthy, and `urlObject.hostname` is not `undefined`: + * * The literal string `:` is appended to `result`, and + * * The value of `urlObject.port` is coerced to a string and appended to `result`. + * * Otherwise, if the `urlObject.host` property value is truthy, the value of `urlObject.host` is coerced to a string and appended to `result`. + * * If the `urlObject.pathname` property is a string that is not an empty string: + * * If the `urlObject.pathname` _does not start_ with an ASCII forward slash + * (`/`), then the literal string `'/'` is appended to `result`. + * * The value of `urlObject.pathname` is appended to `result`. + * * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result` followed by the output of calling the + * `querystring` module's `stringify()` method passing the value of `urlObject.query`. + * * Otherwise, if `urlObject.search` is a string: + * * If the value of `urlObject.search` _does not start_ with the ASCII question + * mark (`?`) character, the literal string `?` is appended to `result`. + * * The value of `urlObject.search` is appended to `result`. + * * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.hash` property is a string: + * * If the value of `urlObject.hash` _does not start_ with the ASCII hash (`#`) + * character, the literal string `#` is appended to `result`. + * * The value of `urlObject.hash` is appended to `result`. + * * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a + * string, an `Error` is thrown. + * * `result` is returned. + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. + */ + function format(urlObject: UrlObject | string): string; + /** + * The `url.resolve()` method resolves a target URL relative to a base URL in a + * manner similar to that of a web browser resolving an anchor tag. + * + * ```js + * import url from 'node:url'; + * url.resolve('/one/two/three', 'four'); // '/one/two/four' + * url.resolve('http://example.com/', '/one'); // 'http://example.com/one' + * url.resolve('http://example.com/one', '/two'); // 'http://example.com/two' + * ``` + * + * To achieve the same result using the WHATWG URL API: + * + * ```js + * function resolve(from, to) { + * const resolvedUrl = new URL(to, new URL(from, 'resolve://')); + * if (resolvedUrl.protocol === 'resolve:') { + * // `from` is a relative URL. + * const { pathname, search, hash } = resolvedUrl; + * return pathname + search + hash; + * } + * return resolvedUrl.toString(); + * } + * + * resolve('/one/two/three', 'four'); // '/one/two/four' + * resolve('http://example.com/', '/one'); // 'http://example.com/one' + * resolve('http://example.com/one', '/two'); // 'http://example.com/two' + * ``` + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param from The base URL to use if `to` is a relative URL. + * @param to The target URL to resolve. + */ + function resolve(from: string, to: string): string; + /** + * Returns the [Punycode](https://tools.ietf.org/html/rfc5891#section-4.4) ASCII serialization of the `domain`. If `domain` is an + * invalid domain, the empty string is returned. + * + * It performs the inverse operation to {@link domainToUnicode}. + * + * ```js + * import url from 'node:url'; + * + * console.log(url.domainToASCII('español.com')); + * // Prints xn--espaol-zwa.com + * console.log(url.domainToASCII('中文.com')); + * // Prints xn--fiq228c.com + * console.log(url.domainToASCII('xn--iñvalid.com')); + * // Prints an empty string + * ``` + * @since v7.4.0, v6.13.0 + */ + function domainToASCII(domain: string): string; + /** + * Returns the Unicode serialization of the `domain`. If `domain` is an invalid + * domain, the empty string is returned. + * + * It performs the inverse operation to {@link domainToASCII}. + * + * ```js + * import url from 'node:url'; + * + * console.log(url.domainToUnicode('xn--espaol-zwa.com')); + * // Prints español.com + * console.log(url.domainToUnicode('xn--fiq228c.com')); + * // Prints 中文.com + * console.log(url.domainToUnicode('xn--iñvalid.com')); + * // Prints an empty string + * ``` + * @since v7.4.0, v6.13.0 + */ + function domainToUnicode(domain: string): string; + /** + * This function ensures the correct decodings of percent-encoded characters as + * well as ensuring a cross-platform valid absolute path string. + * + * ```js + * import { fileURLToPath } from 'node:url'; + * + * const __filename = fileURLToPath(import.meta.url); + * + * new URL('file:///C:/path/').pathname; // Incorrect: /C:/path/ + * fileURLToPath('file:///C:/path/'); // Correct: C:\path\ (Windows) + * + * new URL('file://nas/foo.txt').pathname; // Incorrect: /foo.txt + * fileURLToPath('file://nas/foo.txt'); // Correct: \\nas\foo.txt (Windows) + * + * new URL('file:///你好.txt').pathname; // Incorrect: /%E4%BD%A0%E5%A5%BD.txt + * fileURLToPath('file:///你好.txt'); // Correct: /你好.txt (POSIX) + * + * new URL('file:///hello world').pathname; // Incorrect: /hello%20world + * fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX) + * ``` + * @since v10.12.0 + * @param url The file URL string or URL object to convert to a path. + * @return The fully-resolved platform-specific Node.js file path. + */ + function fileURLToPath(url: string | URL, options?: FileUrlToPathOptions): string; + /** + * Like `url.fileURLToPath(...)` except that instead of returning a string + * representation of the path, a `Buffer` is returned. This conversion is + * helpful when the input URL contains percent-encoded segments that are + * not valid UTF-8 / Unicode sequences. + * @since v24.3.0 + * @param url The file URL string or URL object to convert to a path. + * @returns The fully-resolved platform-specific Node.js file path + * as a `Buffer`. + */ + function fileURLToPathBuffer(url: string | URL, options?: FileUrlToPathOptions): NonSharedBuffer; + /** + * This function ensures that `path` is resolved absolutely, and that the URL + * control characters are correctly encoded when converting into a File URL. + * + * ```js + * import { pathToFileURL } from 'node:url'; + * + * new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1 + * pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX) + * + * new URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c + * pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSIX) + * ``` + * @since v10.12.0 + * @param path The path to convert to a File URL. + * @return The file URL object. + */ + function pathToFileURL(path: string, options?: PathToFileUrlOptions): URL; + /** + * This utility function converts a URL object into an ordinary options object as + * expected by the `http.request()` and `https.request()` APIs. + * + * ```js + * import { urlToHttpOptions } from 'node:url'; + * const myURL = new URL('https://a:b@測試?abc#foo'); + * + * console.log(urlToHttpOptions(myURL)); + * /* + * { + * protocol: 'https:', + * hostname: 'xn--g6w251d', + * hash: '#foo', + * search: '?abc', + * pathname: '/', + * path: '/?abc', + * href: 'https://a:b@xn--g6w251d/?abc#foo', + * auth: 'a:b' + * } + * + * ``` + * @since v15.7.0, v14.18.0 + * @param url The `WHATWG URL` object to convert to an options object. + * @return Options object + */ + function urlToHttpOptions(url: URL): ClientRequestArgs; + interface URLFormatOptions { + /** + * `true` if the serialized URL string should include the username and password, `false` otherwise. + * @default true + */ + auth?: boolean | undefined; + /** + * `true` if the serialized URL string should include the fragment, `false` otherwise. + * @default true + */ + fragment?: boolean | undefined; + /** + * `true` if the serialized URL string should include the search query, `false` otherwise. + * @default true + */ + search?: boolean | undefined; + /** + * `true` if Unicode characters appearing in the host component of the URL string should be encoded directly as opposed to + * being Punycode encoded. + * @default false + */ + unicode?: boolean | undefined; + } + // #region web types + type URLPatternInput = string | URLPatternInit; + interface URLPatternComponentResult { + input: string; + groups: Record; + } + interface URLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; + } + interface URLPatternOptions { + ignoreCase?: boolean; + } + interface URLPatternResult { + inputs: URLPatternInput[]; + protocol: URLPatternComponentResult; + username: URLPatternComponentResult; + password: URLPatternComponentResult; + hostname: URLPatternComponentResult; + port: URLPatternComponentResult; + pathname: URLPatternComponentResult; + search: URLPatternComponentResult; + hash: URLPatternComponentResult; + } + interface URL { + hash: string; + host: string; + hostname: string; + href: string; + readonly origin: string; + password: string; + pathname: string; + port: string; + protocol: string; + search: string; + readonly searchParams: URLSearchParams; + username: string; + toJSON(): string; + } + var URL: { + prototype: URL; + new(url: string | URL, base?: string | URL): URL; + canParse(input: string | URL, base?: string | URL): boolean; + createObjectURL(blob: Blob): string; + parse(input: string | URL, base?: string | URL): URL | null; + revokeObjectURL(id: string): void; + }; + interface URLPattern { + readonly hasRegExpGroups: boolean; + readonly hash: string; + readonly hostname: string; + readonly password: string; + readonly pathname: string; + readonly port: string; + readonly protocol: string; + readonly search: string; + readonly username: string; + exec(input?: URLPatternInput, baseURL?: string | URL): URLPatternResult | null; + test(input?: URLPatternInput, baseURL?: string | URL): boolean; + } + var URLPattern: { + prototype: URLPattern; + new(input: URLPatternInput, baseURL: string | URL, options?: URLPatternOptions): URLPattern; + new(input?: URLPatternInput, options?: URLPatternOptions): URLPattern; + }; + interface URLSearchParams { + readonly size: number; + append(name: string, value: string): void; + delete(name: string, value?: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string, value?: string): boolean; + set(name: string, value: string): void; + sort(): void; + forEach(callbackfn: (value: string, key: string, parent: URLSearchParams) => void, thisArg?: any): void; + [Symbol.iterator](): URLSearchParamsIterator<[string, string]>; + entries(): URLSearchParamsIterator<[string, string]>; + keys(): URLSearchParamsIterator; + values(): URLSearchParamsIterator; + } + var URLSearchParams: { + prototype: URLSearchParams; + new(init?: string[][] | Record | string | URLSearchParams): URLSearchParams; + }; + interface URLSearchParamsIterator extends NodeJS.Iterator { + [Symbol.iterator](): URLSearchParamsIterator; + } + // #endregion +} +declare module "url" { + export * from "node:url"; +} diff --git a/backend/node_modules/@types/node/util.d.ts b/backend/node_modules/@types/node/util.d.ts new file mode 100644 index 0000000..6e0a44d --- /dev/null +++ b/backend/node_modules/@types/node/util.d.ts @@ -0,0 +1,1650 @@ +/** + * The `node:util` module supports the needs of Node.js internal APIs. Many of the + * utilities are useful for application and module developers as well. To access + * it: + * + * ```js + * import util from 'node:util'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/util.js) + */ +declare module "node:util" { + export * as types from "node:util/types"; + export type InspectStyle = + | "special" + | "number" + | "bigint" + | "boolean" + | "undefined" + | "null" + | "string" + | "symbol" + | "date" + | "name" + | "regexp" + | "module"; + export interface InspectStyles extends Record string)> { + regexp: { + (value: string): string; + colors: InspectColor[]; + }; + } + export type InspectColorModifier = + | "reset" + | "bold" + | "dim" + | "italic" + | "underline" + | "blink" + | "inverse" + | "hidden" + | "strikethrough" + | "doubleunderline"; + export type InspectColorForeground = + | "black" + | "red" + | "green" + | "yellow" + | "blue" + | "magenta" + | "cyan" + | "white" + | "gray" + | "redBright" + | "greenBright" + | "yellowBright" + | "blueBright" + | "magentaBright" + | "cyanBright" + | "whiteBright"; + export type InspectColorBackground = `bg${Capitalize}`; + export type InspectColor = InspectColorModifier | InspectColorForeground | InspectColorBackground; + export interface InspectColors extends Record {} + export interface InspectOptions { + /** + * If `true`, object's non-enumerable symbols and properties are included in the formatted result. + * `WeakMap` and `WeakSet` entries are also included as well as user defined prototype properties (excluding method properties). + * @default false + */ + showHidden?: boolean | undefined; + /** + * Specifies the number of times to recurse while formatting object. + * This is useful for inspecting large objects. + * To recurse up to the maximum call stack size pass `Infinity` or `null`. + * @default 2 + */ + depth?: number | null | undefined; + /** + * If `true`, the output is styled with ANSI color codes. Colors are customizable. + */ + colors?: boolean | undefined; + /** + * If `false`, `[util.inspect.custom](depth, opts, inspect)` functions are not invoked. + * @default true + */ + customInspect?: boolean | undefined; + /** + * If `true`, `Proxy` inspection includes the target and handler objects. + * @default false + */ + showProxy?: boolean | undefined; + /** + * Specifies the maximum number of `Array`, `TypedArray`, `WeakMap`, and `WeakSet` elements + * to include when formatting. Set to `null` or `Infinity` to show all elements. + * Set to `0` or negative to show no elements. + * @default 100 + */ + maxArrayLength?: number | null | undefined; + /** + * Specifies the maximum number of characters to + * include when formatting. Set to `null` or `Infinity` to show all elements. + * Set to `0` or negative to show no characters. + * @default 10000 + */ + maxStringLength?: number | null | undefined; + /** + * The length at which input values are split across multiple lines. + * Set to `Infinity` to format the input as a single line + * (in combination with `compact` set to `true` or any number >= `1`). + * @default 80 + */ + breakLength?: number | undefined; + /** + * Setting this to `false` causes each object key + * to be displayed on a new line. It will also add new lines to text that is + * longer than `breakLength`. If set to a number, the most `n` inner elements + * are united on a single line as long as all properties fit into + * `breakLength`. Short array elements are also grouped together. Note that no + * text will be reduced below 16 characters, no matter the `breakLength` size. + * For more information, see the example below. + * @default true + */ + compact?: boolean | number | undefined; + /** + * If set to `true` or a function, all properties of an object, and `Set` and `Map` + * entries are sorted in the resulting string. + * If set to `true` the default sort is used. + * If set to a function, it is used as a compare function. + */ + sorted?: boolean | ((a: string, b: string) => number) | undefined; + /** + * If set to `true`, getters are going to be + * inspected as well. If set to `'get'` only getters without setter are going + * to be inspected. If set to `'set'` only getters having a corresponding + * setter are going to be inspected. This might cause side effects depending on + * the getter function. + * @default false + */ + getters?: "get" | "set" | boolean | undefined; + /** + * If set to `true`, an underscore is used to separate every three digits in all bigints and numbers. + * @default false + */ + numericSeparator?: boolean | undefined; + } + export interface InspectContext extends Required { + stylize(text: string, styleType: InspectStyle): string; + } + import _inspect = inspect; + export interface Inspectable { + [inspect.custom](depth: number, options: InspectContext, inspect: typeof _inspect): any; + } + // TODO: Remove these in a future major + /** @deprecated Use `InspectStyle` instead. */ + export type Style = Exclude; + /** @deprecated Use the `Inspectable` interface instead. */ + export type CustomInspectFunction = (depth: number, options: InspectContext) => any; + /** @deprecated Use `InspectContext` instead. */ + export interface InspectOptionsStylized extends InspectContext {} + /** @deprecated Use `InspectColorModifier` instead. */ + export type Modifiers = InspectColorModifier; + /** @deprecated Use `InspectColorForeground` instead. */ + export type ForegroundColors = InspectColorForeground; + /** @deprecated Use `InspectColorBackground` instead. */ + export type BackgroundColors = InspectColorBackground; + export interface CallSiteObject { + /** + * Returns the name of the function associated with this call site. + */ + functionName: string; + /** + * Returns the name of the resource that contains the script for the + * function for this call site. + */ + scriptName: string; + /** + * Returns the unique id of the script, as in Chrome DevTools protocol + * [`Runtime.ScriptId`](https://chromedevtools.github.io/devtools-protocol/1-3/Runtime/#type-ScriptId). + * @since v22.14.0 + */ + scriptId: string; + /** + * Returns the number, 1-based, of the line for the associate function call. + */ + lineNumber: number; + /** + * Returns the 1-based column offset on the line for the associated function call. + */ + columnNumber: number; + } + export type DiffEntry = [operation: -1 | 0 | 1, value: string]; + /** + * `util.diff()` compares two string or array values and returns an array of difference entries. + * It uses the Myers diff algorithm to compute minimal differences, which is the same algorithm + * used internally by assertion error messages. + * + * If the values are equal, an empty array is returned. + * + * ```js + * const { diff } = require('node:util'); + * + * // Comparing strings + * const actualString = '12345678'; + * const expectedString = '12!!5!7!'; + * console.log(diff(actualString, expectedString)); + * // [ + * // [0, '1'], + * // [0, '2'], + * // [1, '3'], + * // [1, '4'], + * // [-1, '!'], + * // [-1, '!'], + * // [0, '5'], + * // [1, '6'], + * // [-1, '!'], + * // [0, '7'], + * // [1, '8'], + * // [-1, '!'], + * // ] + * // Comparing arrays + * const actualArray = ['1', '2', '3']; + * const expectedArray = ['1', '3', '4']; + * console.log(diff(actualArray, expectedArray)); + * // [ + * // [0, '1'], + * // [1, '2'], + * // [0, '3'], + * // [-1, '4'], + * // ] + * // Equal values return empty array + * console.log(diff('same', 'same')); + * // [] + * ``` + * @since v22.15.0 + * @experimental + * @param actual The first value to compare + * @param expected The second value to compare + * @returns An array of difference entries. Each entry is an array with two elements: + * * Index 0: `number` Operation code: `-1` for delete, `0` for no-op/unchanged, `1` for insert + * * Index 1: `string` The value associated with the operation + */ + export function diff(actual: string | readonly string[], expected: string | readonly string[]): DiffEntry[]; + /** + * The `util.format()` method returns a formatted string using the first argument + * as a `printf`-like format string which can contain zero or more format + * specifiers. Each specifier is replaced with the converted value from the + * corresponding argument. Supported specifiers are: + * + * If a specifier does not have a corresponding argument, it is not replaced: + * + * ```js + * util.format('%s:%s', 'foo'); + * // Returns: 'foo:%s' + * ``` + * + * Values that are not part of the format string are formatted using `util.inspect()` if their type is not `string`. + * + * If there are more arguments passed to the `util.format()` method than the + * number of specifiers, the extra arguments are concatenated to the returned + * string, separated by spaces: + * + * ```js + * util.format('%s:%s', 'foo', 'bar', 'baz'); + * // Returns: 'foo:bar baz' + * ``` + * + * If the first argument does not contain a valid format specifier, `util.format()` returns a string that is the concatenation of all arguments separated by spaces: + * + * ```js + * util.format(1, 2, 3); + * // Returns: '1 2 3' + * ``` + * + * If only one argument is passed to `util.format()`, it is returned as it is + * without any formatting: + * + * ```js + * util.format('%% %s'); + * // Returns: '%% %s' + * ``` + * + * `util.format()` is a synchronous method that is intended as a debugging tool. + * Some input values can have a significant performance overhead that can block the + * event loop. Use this function with care and never in a hot code path. + * @since v0.5.3 + * @param format A `printf`-like format string. + */ + export function format(format?: any, ...param: any[]): string; + /** + * This function is identical to {@link format}, except in that it takes + * an `inspectOptions` argument which specifies options that are passed along to {@link inspect}. + * + * ```js + * util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 }); + * // Returns 'See object { foo: 42 }', where `42` is colored as a number + * // when printed to a terminal. + * ``` + * @since v10.0.0 + */ + export function formatWithOptions(inspectOptions: InspectOptions, format?: any, ...param: any[]): string; + export interface GetCallSitesOptions { + /** + * Reconstruct the original location in the stacktrace from the source-map. + * Enabled by default with the flag `--enable-source-maps`. + */ + sourceMap?: boolean | undefined; + } + /** + * Returns an array of call site objects containing the stack of + * the caller function. + * + * ```js + * import { getCallSites } from 'node:util'; + * + * function exampleFunction() { + * const callSites = getCallSites(); + * + * console.log('Call Sites:'); + * callSites.forEach((callSite, index) => { + * console.log(`CallSite ${index + 1}:`); + * console.log(`Function Name: ${callSite.functionName}`); + * console.log(`Script Name: ${callSite.scriptName}`); + * console.log(`Line Number: ${callSite.lineNumber}`); + * console.log(`Column Number: ${callSite.column}`); + * }); + * // CallSite 1: + * // Function Name: exampleFunction + * // Script Name: /home/example.js + * // Line Number: 5 + * // Column Number: 26 + * + * // CallSite 2: + * // Function Name: anotherFunction + * // Script Name: /home/example.js + * // Line Number: 22 + * // Column Number: 3 + * + * // ... + * } + * + * // A function to simulate another stack layer + * function anotherFunction() { + * exampleFunction(); + * } + * + * anotherFunction(); + * ``` + * + * It is possible to reconstruct the original locations by setting the option `sourceMap` to `true`. + * If the source map is not available, the original location will be the same as the current location. + * When the `--enable-source-maps` flag is enabled, for example when using `--experimental-transform-types`, + * `sourceMap` will be true by default. + * + * ```ts + * import { getCallSites } from 'node:util'; + * + * interface Foo { + * foo: string; + * } + * + * const callSites = getCallSites({ sourceMap: true }); + * + * // With sourceMap: + * // Function Name: '' + * // Script Name: example.js + * // Line Number: 7 + * // Column Number: 26 + * + * // Without sourceMap: + * // Function Name: '' + * // Script Name: example.js + * // Line Number: 2 + * // Column Number: 26 + * ``` + * @param frameCount Number of frames to capture as call site objects. + * **Default:** `10`. Allowable range is between 1 and 200. + * @return An array of call site objects + * @since v22.9.0 + */ + export function getCallSites(frameCount?: number, options?: GetCallSitesOptions): CallSiteObject[]; + export function getCallSites(options: GetCallSitesOptions): CallSiteObject[]; + /** + * Returns the string name for a numeric error code that comes from a Node.js API. + * The mapping between error codes and error names is platform-dependent. + * See `Common System Errors` for the names of common errors. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const name = util.getSystemErrorName(err.errno); + * console.error(name); // ENOENT + * }); + * ``` + * @since v9.7.0 + */ + export function getSystemErrorName(err: number): string; + /** + * Enable or disable printing a stack trace on `SIGINT`. The API is only available on the main thread. + * @since 24.6.0 + */ + export function setTraceSigInt(enable: boolean): void; + /** + * Returns a Map of all system error codes available from the Node.js API. + * The mapping between error codes and error names is platform-dependent. + * See `Common System Errors` for the names of common errors. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const errorMap = util.getSystemErrorMap(); + * const name = errorMap.get(err.errno); + * console.error(name); // ENOENT + * }); + * ``` + * @since v16.0.0, v14.17.0 + */ + export function getSystemErrorMap(): Map; + /** + * Returns the string message for a numeric error code that comes from a Node.js + * API. + * The mapping between error codes and string messages is platform-dependent. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const message = util.getSystemErrorMessage(err.errno); + * console.error(message); // no such file or directory + * }); + * ``` + * @since v22.12.0 + */ + export function getSystemErrorMessage(err: number): string; + /** + * Returns the `string` after replacing any surrogate code points + * (or equivalently, any unpaired surrogate code units) with the + * Unicode "replacement character" U+FFFD. + * @since v16.8.0, v14.18.0 + */ + export function toUSVString(string: string): string; + /** + * Creates and returns an `AbortController` instance whose `AbortSignal` is marked + * as transferable and can be used with `structuredClone()` or `postMessage()`. + * @since v18.11.0 + * @returns A transferable AbortController + */ + export function transferableAbortController(): AbortController; + /** + * Marks the given `AbortSignal` as transferable so that it can be used with`structuredClone()` and `postMessage()`. + * + * ```js + * const signal = transferableAbortSignal(AbortSignal.timeout(100)); + * const channel = new MessageChannel(); + * channel.port2.postMessage(signal, [signal]); + * ``` + * @since v18.11.0 + * @param signal The AbortSignal + * @returns The same AbortSignal + */ + export function transferableAbortSignal(signal: AbortSignal): AbortSignal; + /** + * Listens to abort event on the provided `signal` and returns a promise that resolves when the `signal` is aborted. + * If `resource` is provided, it weakly references the operation's associated object, + * so if `resource` is garbage collected before the `signal` aborts, + * then returned promise shall remain pending. + * This prevents memory leaks in long-running or non-cancelable operations. + * + * ```js + * import { aborted } from 'node:util'; + * + * // Obtain an object with an abortable signal, like a custom resource or operation. + * const dependent = obtainSomethingAbortable(); + * + * // Pass `dependent` as the resource, indicating the promise should only resolve + * // if `dependent` is still in memory when the signal is aborted. + * aborted(dependent.signal, dependent).then(() => { + * // This code runs when `dependent` is aborted. + * console.log('Dependent resource was aborted.'); + * }); + * + * // Simulate an event that triggers the abort. + * dependent.on('event', () => { + * dependent.abort(); // This will cause the `aborted` promise to resolve. + * }); + * ``` + * @since v19.7.0 + * @param resource Any non-null object tied to the abortable operation and held weakly. + * If `resource` is garbage collected before the `signal` aborts, the promise remains pending, + * allowing Node.js to stop tracking it. + * This helps prevent memory leaks in long-running or non-cancelable operations. + */ + export function aborted(signal: AbortSignal, resource: any): Promise; + /** + * The `util.inspect()` method returns a string representation of `object` that is + * intended for debugging. The output of `util.inspect` may change at any time + * and should not be depended upon programmatically. Additional `options` may be + * passed that alter the result. + * `util.inspect()` will use the constructor's name and/or `Symbol.toStringTag` + * property to make an identifiable tag for an inspected value. + * + * ```js + * class Foo { + * get [Symbol.toStringTag]() { + * return 'bar'; + * } + * } + * + * class Bar {} + * + * const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } }); + * + * util.inspect(new Foo()); // 'Foo [bar] {}' + * util.inspect(new Bar()); // 'Bar {}' + * util.inspect(baz); // '[foo] {}' + * ``` + * + * Circular references point to their anchor by using a reference index: + * + * ```js + * import { inspect } from 'node:util'; + * + * const obj = {}; + * obj.a = [obj]; + * obj.b = {}; + * obj.b.inner = obj.b; + * obj.b.obj = obj; + * + * console.log(inspect(obj)); + * // { + * // a: [ [Circular *1] ], + * // b: { inner: [Circular *2], obj: [Circular *1] } + * // } + * ``` + * + * The following example inspects all properties of the `util` object: + * + * ```js + * import util from 'node:util'; + * + * console.log(util.inspect(util, { showHidden: true, depth: null })); + * ``` + * + * The following example highlights the effect of the `compact` option: + * + * ```js + * import { inspect } from 'node:util'; + * + * const o = { + * a: [1, 2, [[ + * 'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit, sed do ' + + * 'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.', + * 'test', + * 'foo']], 4], + * b: new Map([['za', 1], ['zb', 'test']]), + * }; + * console.log(inspect(o, { compact: true, depth: 5, breakLength: 80 })); + * + * // { a: + * // [ 1, + * // 2, + * // [ [ 'Lorem ipsum dolor sit amet,\nconsectetur [...]', // A long line + * // 'test', + * // 'foo' ] ], + * // 4 ], + * // b: Map(2) { 'za' => 1, 'zb' => 'test' } } + * + * // Setting `compact` to false or an integer creates more reader friendly output. + * console.log(inspect(o, { compact: false, depth: 5, breakLength: 80 })); + * + * // { + * // a: [ + * // 1, + * // 2, + * // [ + * // [ + * // 'Lorem ipsum dolor sit amet,\n' + + * // 'consectetur adipiscing elit, sed do eiusmod \n' + + * // 'tempor incididunt ut labore et dolore magna aliqua.', + * // 'test', + * // 'foo' + * // ] + * // ], + * // 4 + * // ], + * // b: Map(2) { + * // 'za' => 1, + * // 'zb' => 'test' + * // } + * // } + * + * // Setting `breakLength` to e.g. 150 will print the "Lorem ipsum" text in a + * // single line. + * ``` + * + * The `showHidden` option allows `WeakMap` and `WeakSet` entries to be + * inspected. If there are more entries than `maxArrayLength`, there is no + * guarantee which entries are displayed. That means retrieving the same + * `WeakSet` entries twice may result in different output. Furthermore, entries + * with no remaining strong references may be garbage collected at any time. + * + * ```js + * import { inspect } from 'node:util'; + * + * const obj = { a: 1 }; + * const obj2 = { b: 2 }; + * const weakSet = new WeakSet([obj, obj2]); + * + * console.log(inspect(weakSet, { showHidden: true })); + * // WeakSet { { a: 1 }, { b: 2 } } + * ``` + * + * The `sorted` option ensures that an object's property insertion order does not + * impact the result of `util.inspect()`. + * + * ```js + * import { inspect } from 'node:util'; + * import assert from 'node:assert'; + * + * const o1 = { + * b: [2, 3, 1], + * a: '`a` comes before `b`', + * c: new Set([2, 3, 1]), + * }; + * console.log(inspect(o1, { sorted: true })); + * // { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } } + * console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) })); + * // { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' } + * + * const o2 = { + * c: new Set([2, 1, 3]), + * a: '`a` comes before `b`', + * b: [2, 3, 1], + * }; + * assert.strict.equal( + * inspect(o1, { sorted: true }), + * inspect(o2, { sorted: true }), + * ); + * ``` + * + * The `numericSeparator` option adds an underscore every three digits to all + * numbers. + * + * ```js + * import { inspect } from 'node:util'; + * + * const thousand = 1000; + * const million = 1000000; + * const bigNumber = 123456789n; + * const bigDecimal = 1234.12345; + * + * console.log(inspect(thousand, { numericSeparator: true })); + * // 1_000 + * console.log(inspect(million, { numericSeparator: true })); + * // 1_000_000 + * console.log(inspect(bigNumber, { numericSeparator: true })); + * // 123_456_789n + * console.log(inspect(bigDecimal, { numericSeparator: true })); + * // 1_234.123_45 + * ``` + * + * `util.inspect()` is a synchronous method intended for debugging. Its maximum + * output length is approximately 128 MiB. Inputs that result in longer output will + * be truncated. + * @since v0.3.0 + * @param object Any JavaScript primitive or `Object`. + * @return The representation of `object`. + */ + export function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; + export function inspect(object: any, options?: InspectOptions): string; + export namespace inspect { + const custom: unique symbol; + let colors: InspectColors; + let styles: InspectStyles; + let defaultOptions: InspectOptions; + let replDefaults: InspectOptions; + } + /** + * Alias for [`Array.isArray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray). + * + * Returns `true` if the given `object` is an `Array`. Otherwise, returns `false`. + * + * ```js + * import util from 'node:util'; + * + * util.isArray([]); + * // Returns: true + * util.isArray(new Array()); + * // Returns: true + * util.isArray({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use `isArray` instead. + */ + export function isArray(object: unknown): object is unknown[]; + /** + * Usage of `util.inherits()` is discouraged. Please use the ES6 `class` and + * `extends` keywords to get language level inheritance support. Also note + * that the two styles are [semantically incompatible](https://github.com/nodejs/node/issues/4179). + * + * Inherit the prototype methods from one + * [constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor) into another. The + * prototype of `constructor` will be set to a new object created from + * `superConstructor`. + * + * This mainly adds some input validation on top of + * `Object.setPrototypeOf(constructor.prototype, superConstructor.prototype)`. + * As an additional convenience, `superConstructor` will be accessible + * through the `constructor.super_` property. + * + * ```js + * const util = require('node:util'); + * const EventEmitter = require('node:events'); + * + * function MyStream() { + * EventEmitter.call(this); + * } + * + * util.inherits(MyStream, EventEmitter); + * + * MyStream.prototype.write = function(data) { + * this.emit('data', data); + * }; + * + * const stream = new MyStream(); + * + * console.log(stream instanceof EventEmitter); // true + * console.log(MyStream.super_ === EventEmitter); // true + * + * stream.on('data', (data) => { + * console.log(`Received data: "${data}"`); + * }); + * stream.write('It works!'); // Received data: "It works!" + * ``` + * + * ES6 example using `class` and `extends`: + * + * ```js + * import EventEmitter from 'node:events'; + * + * class MyStream extends EventEmitter { + * write(data) { + * this.emit('data', data); + * } + * } + * + * const stream = new MyStream(); + * + * stream.on('data', (data) => { + * console.log(`Received data: "${data}"`); + * }); + * stream.write('With ES6'); + * ``` + * @since v0.3.0 + * @legacy Use ES2015 class syntax and `extends` keyword instead. + */ + export function inherits(constructor: unknown, superConstructor: unknown): void; + export type DebugLoggerFunction = (msg: string, ...param: unknown[]) => void; + export interface DebugLogger extends DebugLoggerFunction { + /** + * The `util.debuglog().enabled` getter is used to create a test that can be used + * in conditionals based on the existence of the `NODE_DEBUG` environment variable. + * If the `section` name appears within the value of that environment variable, + * then the returned value will be `true`. If not, then the returned value will be + * `false`. + * + * ```js + * import { debuglog } from 'node:util'; + * const enabled = debuglog('foo').enabled; + * if (enabled) { + * console.log('hello from foo [%d]', 123); + * } + * ``` + * + * If this program is run with `NODE_DEBUG=foo` in the environment, then it will + * output something like: + * + * ```console + * hello from foo [123] + * ``` + */ + enabled: boolean; + } + /** + * The `util.debuglog()` method is used to create a function that conditionally + * writes debug messages to `stderr` based on the existence of the `NODE_DEBUG` + * environment variable. If the `section` name appears within the value of that + * environment variable, then the returned function operates similar to + * `console.error()`. If not, then the returned function is a no-op. + * + * ```js + * import { debuglog } from 'node:util'; + * const log = debuglog('foo'); + * + * log('hello from foo [%d]', 123); + * ``` + * + * If this program is run with `NODE_DEBUG=foo` in the environment, then + * it will output something like: + * + * ```console + * FOO 3245: hello from foo [123] + * ``` + * + * where `3245` is the process id. If it is not run with that + * environment variable set, then it will not print anything. + * + * The `section` supports wildcard also: + * + * ```js + * import { debuglog } from 'node:util'; + * const log = debuglog('foo'); + * + * log('hi there, it\'s foo-bar [%d]', 2333); + * ``` + * + * if it is run with `NODE_DEBUG=foo*` in the environment, then it will output + * something like: + * + * ```console + * FOO-BAR 3257: hi there, it's foo-bar [2333] + * ``` + * + * Multiple comma-separated `section` names may be specified in the `NODE_DEBUG` + * environment variable: `NODE_DEBUG=fs,net,tls`. + * + * The optional `callback` argument can be used to replace the logging function + * with a different function that doesn't have any initialization or + * unnecessary wrapping. + * + * ```js + * import { debuglog } from 'node:util'; + * let log = debuglog('internals', (debug) => { + * // Replace with a logging function that optimizes out + * // testing if the section is enabled + * log = debug; + * }); + * ``` + * @since v0.11.3 + * @param section A string identifying the portion of the application for which the `debuglog` function is being created. + * @param callback A callback invoked the first time the logging function is called with a function argument that is a more optimized logging function. + * @return The logging function + */ + export function debuglog(section: string, callback?: (fn: DebugLoggerFunction) => void): DebugLogger; + export { debuglog as debug }; + /** + * The `util.deprecate()` method wraps `fn` (which may be a function or class) in + * such a way that it is marked as deprecated. + * + * ```js + * import { deprecate } from 'node:util'; + * + * export const obsoleteFunction = deprecate(() => { + * // Do something here. + * }, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.'); + * ``` + * + * When called, `util.deprecate()` will return a function that will emit a + * `DeprecationWarning` using the `'warning'` event. The warning will + * be emitted and printed to `stderr` the first time the returned function is + * called. After the warning is emitted, the wrapped function is called without + * emitting a warning. + * + * If the same optional `code` is supplied in multiple calls to `util.deprecate()`, + * the warning will be emitted only once for that `code`. + * + * ```js + * import { deprecate } from 'node:util'; + * + * const fn1 = deprecate( + * () => 'a value', + * 'deprecation message', + * 'DEP0001', + * ); + * const fn2 = deprecate( + * () => 'a different value', + * 'other dep message', + * 'DEP0001', + * ); + * fn1(); // Emits a deprecation warning with code DEP0001 + * fn2(); // Does not emit a deprecation warning because it has the same code + * ``` + * + * If either the `--no-deprecation` or `--no-warnings` command-line flags are + * used, or if the `process.noDeprecation` property is set to `true` _prior_ to + * the first deprecation warning, the `util.deprecate()` method does nothing. + * + * If the `--trace-deprecation` or `--trace-warnings` command-line flags are set, + * or the `process.traceDeprecation` property is set to `true`, a warning and a + * stack trace are printed to `stderr` the first time the deprecated function is + * called. + * + * If the `--throw-deprecation` command-line flag is set, or the + * `process.throwDeprecation` property is set to `true`, then an exception will be + * thrown when the deprecated function is called. + * + * The `--throw-deprecation` command-line flag and `process.throwDeprecation` + * property take precedence over `--trace-deprecation` and + * `process.traceDeprecation`. + * @since v0.8.0 + * @param fn The function that is being deprecated. + * @param msg A warning message to display when the deprecated function is invoked. + * @param code A deprecation code. See the `list of deprecated APIs` for a list of codes. + * @return The deprecated function wrapped to emit a warning. + */ + export function deprecate(fn: T, msg: string, code?: string): T; + export interface IsDeepStrictEqualOptions { + /** + * If `true`, prototype and constructor + * comparison is skipped during deep strict equality check. + * @since v24.9.0 + * @default false + */ + skipPrototype?: boolean | undefined; + } + /** + * Returns `true` if there is deep strict equality between `val1` and `val2`. + * Otherwise, returns `false`. + * + * See `assert.deepStrictEqual()` for more information about deep strict + * equality. + * @since v9.0.0 + */ + export function isDeepStrictEqual(val1: unknown, val2: unknown, options?: IsDeepStrictEqualOptions): boolean; + /** + * Returns `str` with any ANSI escape codes removed. + * + * ```js + * console.log(util.stripVTControlCharacters('\u001B[4mvalue\u001B[0m')); + * // Prints "value" + * ``` + * @since v16.11.0 + */ + export function stripVTControlCharacters(str: string): string; + /** + * Takes an `async` function (or a function that returns a `Promise`) and returns a + * function following the error-first callback style, i.e. taking + * an `(err, value) => ...` callback as the last argument. In the callback, the + * first argument will be the rejection reason (or `null` if the `Promise` + * resolved), and the second argument will be the resolved value. + * + * ```js + * import { callbackify } from 'node:util'; + * + * async function fn() { + * return 'hello world'; + * } + * const callbackFunction = callbackify(fn); + * + * callbackFunction((err, ret) => { + * if (err) throw err; + * console.log(ret); + * }); + * ``` + * + * Will print: + * + * ```text + * hello world + * ``` + * + * The callback is executed asynchronously, and will have a limited stack trace. + * If the callback throws, the process will emit an `'uncaughtException'` + * event, and if not handled will exit. + * + * Since `null` has a special meaning as the first argument to a callback, if a + * wrapped function rejects a `Promise` with a falsy value as a reason, the value + * is wrapped in an `Error` with the original value stored in a field named + * `reason`. + * + * ```js + * function fn() { + * return Promise.reject(null); + * } + * const callbackFunction = util.callbackify(fn); + * + * callbackFunction((err, ret) => { + * // When the Promise was rejected with `null` it is wrapped with an Error and + * // the original value is stored in `reason`. + * err && Object.hasOwn(err, 'reason') && err.reason === null; // true + * }); + * ``` + * @since v8.2.0 + * @param fn An `async` function + * @return a callback style function + */ + export function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: () => Promise, + ): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1) => Promise, + ): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1) => Promise, + ): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2) => Promise, + ): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2) => Promise, + ): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, + ) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, + ) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + arg6: T6, + callback: (err: NodeJS.ErrnoException) => void, + ) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + arg6: T6, + callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, + ) => void; + export interface CustomPromisifyLegacy extends Function { + __promisify__: TCustom; + } + export interface CustomPromisifySymbol extends Function { + [promisify.custom]: TCustom; + } + export type CustomPromisify = + | CustomPromisifySymbol + | CustomPromisifyLegacy; + /** + * Takes a function following the common error-first callback style, i.e. taking + * an `(err, value) => ...` callback as the last argument, and returns a version + * that returns promises. + * + * ```js + * import { promisify } from 'node:util'; + * import { stat } from 'node:fs'; + * + * const promisifiedStat = promisify(stat); + * promisifiedStat('.').then((stats) => { + * // Do something with `stats` + * }).catch((error) => { + * // Handle the error. + * }); + * ``` + * + * Or, equivalently using `async function`s: + * + * ```js + * import { promisify } from 'node:util'; + * import { stat } from 'node:fs'; + * + * const promisifiedStat = promisify(stat); + * + * async function callStat() { + * const stats = await promisifiedStat('.'); + * console.log(`This directory is owned by ${stats.uid}`); + * } + * + * callStat(); + * ``` + * + * If there is an `original[util.promisify.custom]` property present, `promisify` + * will return its value, see [Custom promisified functions](https://nodejs.org/docs/latest-v25.x/api/util.html#custom-promisified-functions). + * + * `promisify()` assumes that `original` is a function taking a callback as its + * final argument in all cases. If `original` is not a function, `promisify()` + * will throw an error. If `original` is a function but its last argument is not + * an error-first callback, it will still be passed an error-first + * callback as its last argument. + * + * Using `promisify()` on class methods or other methods that use `this` may not + * work as expected unless handled specially: + * + * ```js + * import { promisify } from 'node:util'; + * + * class Foo { + * constructor() { + * this.a = 42; + * } + * + * bar(callback) { + * callback(null, this.a); + * } + * } + * + * const foo = new Foo(); + * + * const naiveBar = promisify(foo.bar); + * // TypeError: Cannot read properties of undefined (reading 'a') + * // naiveBar().then(a => console.log(a)); + * + * naiveBar.call(foo).then((a) => console.log(a)); // '42' + * + * const bindBar = naiveBar.bind(foo); + * bindBar().then((a) => console.log(a)); // '42' + * ``` + * @since v8.0.0 + */ + export function promisify(fn: CustomPromisify): TCustom; + export function promisify( + fn: (callback: (err: any, result: TResult) => void) => void, + ): () => Promise; + export function promisify(fn: (callback: (err?: any) => void) => void): () => Promise; + export function promisify( + fn: (arg1: T1, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1) => Promise; + export function promisify(fn: (arg1: T1, callback: (err?: any) => void) => void): (arg1: T1) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify(fn: Function): Function; + export namespace promisify { + /** + * That can be used to declare custom promisified variants of functions. + */ + const custom: unique symbol; + } + /** + * Stability: 1.1 - Active development + * Given an example `.env` file: + * + * ```js + * import { parseEnv } from 'node:util'; + * + * parseEnv('HELLO=world\nHELLO=oh my\n'); + * // Returns: { HELLO: 'oh my' } + * ``` + * @param content The raw contents of a `.env` file. + * @since v20.12.0 + */ + export function parseEnv(content: string): NodeJS.Dict; + export interface StyleTextOptions { + /** + * When true, `stream` is checked to see if it can handle colors. + * @default true + */ + validateStream?: boolean | undefined; + /** + * A stream that will be validated if it can be colored. + * @default process.stdout + */ + stream?: NodeJS.WritableStream | undefined; + } + /** + * This function returns a formatted text considering the `format` passed + * for printing in a terminal. It is aware of the terminal's capabilities + * and acts according to the configuration set via `NO_COLOR`, + * `NODE_DISABLE_COLORS` and `FORCE_COLOR` environment variables. + * + * ```js + * import { styleText } from 'node:util'; + * import { stderr } from 'node:process'; + * + * const successMessage = styleText('green', 'Success!'); + * console.log(successMessage); + * + * const errorMessage = styleText( + * 'red', + * 'Error! Error!', + * // Validate if process.stderr has TTY + * { stream: stderr }, + * ); + * console.error(errorMessage); + * ``` + * + * `util.inspect.colors` also provides text formats such as `italic`, and + * `underline` and you can combine both: + * + * ```js + * console.log( + * util.styleText(['underline', 'italic'], 'My italic underlined message'), + * ); + * ``` + * + * When passing an array of formats, the order of the format applied + * is left to right so the following style might overwrite the previous one. + * + * ```js + * console.log( + * util.styleText(['red', 'green'], 'text'), // green + * ); + * ``` + * + * The special format value `none` applies no additional styling to the text. + * + * The full list of formats can be found in [modifiers](https://nodejs.org/docs/latest-v25.x/api/util.html#modifiers). + * @param format A text format or an Array of text formats defined in `util.inspect.colors`. + * @param text The text to to be formatted. + * @since v20.12.0 + */ + export function styleText( + format: InspectColor | readonly InspectColor[], + text: string, + options?: StyleTextOptions, + ): string; + //// parseArgs + /** + * Provides a higher level API for command-line argument parsing than interacting + * with `process.argv` directly. Takes a specification for the expected arguments + * and returns a structured object with the parsed options and positionals. + * + * ```js + * import { parseArgs } from 'node:util'; + * const args = ['-f', '--bar', 'b']; + * const options = { + * foo: { + * type: 'boolean', + * short: 'f', + * }, + * bar: { + * type: 'string', + * }, + * }; + * const { + * values, + * positionals, + * } = parseArgs({ args, options }); + * console.log(values, positionals); + * // Prints: [Object: null prototype] { foo: true, bar: 'b' } [] + * ``` + * @since v18.3.0, v16.17.0 + * @param config Used to provide arguments for parsing and to configure the parser. `config` supports the following properties: + * @return The parsed command line arguments: + */ + export function parseArgs(config?: T): ParsedResults; + /** + * Type of argument used in {@link parseArgs}. + */ + export type ParseArgsOptionsType = "boolean" | "string"; + export interface ParseArgsOptionDescriptor { + /** + * Type of argument. + */ + type: ParseArgsOptionsType; + /** + * Whether this option can be provided multiple times. + * If `true`, all values will be collected in an array. + * If `false`, values for the option are last-wins. + * @default false. + */ + multiple?: boolean | undefined; + /** + * A single character alias for the option. + */ + short?: string | undefined; + /** + * The value to assign to + * the option if it does not appear in the arguments to be parsed. The value + * must match the type specified by the `type` property. If `multiple` is + * `true`, it must be an array. No default value is applied when the option + * does appear in the arguments to be parsed, even if the provided value + * is falsy. + * @since v18.11.0 + */ + default?: string | boolean | string[] | boolean[] | undefined; + } + export interface ParseArgsOptionsConfig { + [longOption: string]: ParseArgsOptionDescriptor; + } + export interface ParseArgsConfig { + /** + * Array of argument strings. + */ + args?: readonly string[] | undefined; + /** + * Used to describe arguments known to the parser. + */ + options?: ParseArgsOptionsConfig | undefined; + /** + * Should an error be thrown when unknown arguments are encountered, + * or when arguments are passed that do not match the `type` configured in `options`. + * @default true + */ + strict?: boolean | undefined; + /** + * Whether this command accepts positional arguments. + */ + allowPositionals?: boolean | undefined; + /** + * If `true`, allows explicitly setting boolean options to `false` by prefixing the option name with `--no-`. + * @default false + * @since v22.4.0 + */ + allowNegative?: boolean | undefined; + /** + * Return the parsed tokens. This is useful for extending the built-in behavior, + * from adding additional checks through to reprocessing the tokens in different ways. + * @default false + */ + tokens?: boolean | undefined; + } + /* + IfDefaultsTrue and IfDefaultsFalse are helpers to handle default values for missing boolean properties. + TypeScript does not have exact types for objects: https://github.com/microsoft/TypeScript/issues/12936 + This means it is impossible to distinguish between "field X is definitely not present" and "field X may or may not be present". + But we expect users to generally provide their config inline or `as const`, which means TS will always know whether a given field is present. + So this helper treats "not definitely present" (i.e., not `extends boolean`) as being "definitely not present", i.e. it should have its default value. + This is technically incorrect but is a much nicer UX for the common case. + The IfDefaultsTrue version is for things which default to true; the IfDefaultsFalse version is for things which default to false. + */ + type IfDefaultsTrue = T extends true ? IfTrue + : T extends false ? IfFalse + : IfTrue; + // we put the `extends false` condition first here because `undefined` compares like `any` when `strictNullChecks: false` + type IfDefaultsFalse = T extends false ? IfFalse + : T extends true ? IfTrue + : IfFalse; + type ExtractOptionValue = IfDefaultsTrue< + T["strict"], + O["type"] extends "string" ? string : O["type"] extends "boolean" ? boolean : string | boolean, + string | boolean + >; + type ApplyOptionalModifiers> = ( + & { -readonly [LongOption in keyof O]?: V[LongOption] } + & { [LongOption in keyof O as O[LongOption]["default"] extends {} ? LongOption : never]: V[LongOption] } + ) extends infer P ? { [K in keyof P]: P[K] } : never; // resolve intersection to object + type ParsedValues = + & IfDefaultsTrue + & (T["options"] extends ParseArgsOptionsConfig ? ApplyOptionalModifiers< + T["options"], + { + [LongOption in keyof T["options"]]: IfDefaultsFalse< + T["options"][LongOption]["multiple"], + Array>, + ExtractOptionValue + >; + } + > + : {}); + type ParsedPositionals = IfDefaultsTrue< + T["strict"], + IfDefaultsFalse, + IfDefaultsTrue + >; + type PreciseTokenForOptions< + K extends string, + O extends ParseArgsOptionDescriptor, + > = O["type"] extends "string" ? { + kind: "option"; + index: number; + name: K; + rawName: string; + value: string; + inlineValue: boolean; + } + : O["type"] extends "boolean" ? { + kind: "option"; + index: number; + name: K; + rawName: string; + value: undefined; + inlineValue: undefined; + } + : OptionToken & { name: K }; + type TokenForOptions< + T extends ParseArgsConfig, + K extends keyof T["options"] = keyof T["options"], + > = K extends unknown + ? T["options"] extends ParseArgsOptionsConfig ? PreciseTokenForOptions + : OptionToken + : never; + type ParsedOptionToken = IfDefaultsTrue, OptionToken>; + type ParsedPositionalToken = IfDefaultsTrue< + T["strict"], + IfDefaultsFalse, + IfDefaultsTrue + >; + type ParsedTokens = Array< + ParsedOptionToken | ParsedPositionalToken | { kind: "option-terminator"; index: number } + >; + type PreciseParsedResults = IfDefaultsFalse< + T["tokens"], + { + values: ParsedValues; + positionals: ParsedPositionals; + tokens: ParsedTokens; + }, + { + values: ParsedValues; + positionals: ParsedPositionals; + } + >; + type OptionToken = + | { kind: "option"; index: number; name: string; rawName: string; value: string; inlineValue: boolean } + | { + kind: "option"; + index: number; + name: string; + rawName: string; + value: undefined; + inlineValue: undefined; + }; + type Token = + | OptionToken + | { kind: "positional"; index: number; value: string } + | { kind: "option-terminator"; index: number }; + // If ParseArgsConfig extends T, then the user passed config constructed elsewhere. + // So we can't rely on the `"not definitely present" implies "definitely not present"` assumption mentioned above. + type ParsedResults = ParseArgsConfig extends T ? { + values: { + [longOption: string]: undefined | string | boolean | Array; + }; + positionals: string[]; + tokens?: Token[]; + } + : PreciseParsedResults; + /** + * An implementation of [the MIMEType class](https://bmeck.github.io/node-proposal-mime-api/). + * + * In accordance with browser conventions, all properties of `MIMEType` objects + * are implemented as getters and setters on the class prototype, rather than as + * data properties on the object itself. + * + * A MIME string is a structured string containing multiple meaningful + * components. When parsed, a `MIMEType` object is returned containing + * properties for each of these components. + * @since v19.1.0, v18.13.0 + */ + export class MIMEType { + /** + * Creates a new MIMEType object by parsing the input. + * + * A `TypeError` will be thrown if the `input` is not a valid MIME. + * Note that an effort will be made to coerce the given values into strings. + * @param input The input MIME to parse. + */ + constructor(input: string | { toString: () => string }); + /** + * Gets and sets the type portion of the MIME. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const myMIME = new MIMEType('text/javascript'); + * console.log(myMIME.type); + * // Prints: text + * myMIME.type = 'application'; + * console.log(myMIME.type); + * // Prints: application + * console.log(String(myMIME)); + * // Prints: application/javascript + * ``` + */ + type: string; + /** + * Gets and sets the subtype portion of the MIME. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const myMIME = new MIMEType('text/ecmascript'); + * console.log(myMIME.subtype); + * // Prints: ecmascript + * myMIME.subtype = 'javascript'; + * console.log(myMIME.subtype); + * // Prints: javascript + * console.log(String(myMIME)); + * // Prints: text/javascript + * ``` + */ + subtype: string; + /** + * Gets the essence of the MIME. This property is read only. + * Use `mime.type` or `mime.subtype` to alter the MIME. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const myMIME = new MIMEType('text/javascript;key=value'); + * console.log(myMIME.essence); + * // Prints: text/javascript + * myMIME.type = 'application'; + * console.log(myMIME.essence); + * // Prints: application/javascript + * console.log(String(myMIME)); + * // Prints: application/javascript;key=value + * ``` + */ + readonly essence: string; + /** + * Gets the `MIMEParams` object representing the + * parameters of the MIME. This property is read-only. See `MIMEParams` documentation for details. + */ + readonly params: MIMEParams; + /** + * The `toString()` method on the `MIMEType` object returns the serialized MIME. + * + * Because of the need for standard compliance, this method does not allow users + * to customize the serialization process of the MIME. + */ + toString(): string; + } + /** + * The `MIMEParams` API provides read and write access to the parameters of a `MIMEType`. + * @since v19.1.0, v18.13.0 + */ + export class MIMEParams { + /** + * Remove all name-value pairs whose name is `name`. + */ + delete(name: string): void; + /** + * Returns an iterator over each of the name-value pairs in the parameters. + * Each item of the iterator is a JavaScript `Array`. The first item of the array + * is the `name`, the second item of the array is the `value`. + */ + entries(): NodeJS.Iterator<[name: string, value: string]>; + /** + * Returns the value of the first name-value pair whose name is `name`. If there + * are no such pairs, `null` is returned. + * @return or `null` if there is no name-value pair with the given `name`. + */ + get(name: string): string | null; + /** + * Returns `true` if there is at least one name-value pair whose name is `name`. + */ + has(name: string): boolean; + /** + * Returns an iterator over the names of each name-value pair. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const { params } = new MIMEType('text/plain;foo=0;bar=1'); + * for (const name of params.keys()) { + * console.log(name); + * } + * // Prints: + * // foo + * // bar + * ``` + */ + keys(): NodeJS.Iterator; + /** + * Sets the value in the `MIMEParams` object associated with `name` to `value`. If there are any pre-existing name-value pairs whose names are `name`, + * set the first such pair's value to `value`. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const { params } = new MIMEType('text/plain;foo=0;bar=1'); + * params.set('foo', 'def'); + * params.set('baz', 'xyz'); + * console.log(params.toString()); + * // Prints: foo=def;bar=1;baz=xyz + * ``` + */ + set(name: string, value: string): void; + /** + * Returns an iterator over the values of each name-value pair. + */ + values(): NodeJS.Iterator; + /** + * Returns an iterator over each of the name-value pairs in the parameters. + */ + [Symbol.iterator](): NodeJS.Iterator<[name: string, value: string]>; + } + // #region web types + export interface TextDecodeOptions { + stream?: boolean; + } + export interface TextDecoderCommon { + readonly encoding: string; + readonly fatal: boolean; + readonly ignoreBOM: boolean; + } + export interface TextDecoderOptions { + fatal?: boolean; + ignoreBOM?: boolean; + } + export interface TextEncoderCommon { + readonly encoding: string; + } + export interface TextEncoderEncodeIntoResult { + read: number; + written: number; + } + export interface TextDecoder extends TextDecoderCommon { + decode(input?: NodeJS.AllowSharedBufferSource, options?: TextDecodeOptions): string; + } + export var TextDecoder: { + prototype: TextDecoder; + new(label?: string, options?: TextDecoderOptions): TextDecoder; + }; + export interface TextEncoder extends TextEncoderCommon { + encode(input?: string): NodeJS.NonSharedUint8Array; + encodeInto(source: string, destination: Uint8Array): TextEncoderEncodeIntoResult; + } + export var TextEncoder: { + prototype: TextEncoder; + new(): TextEncoder; + }; + // #endregion +} +declare module "util" { + export * from "node:util"; +} diff --git a/backend/node_modules/@types/node/util/types.d.ts b/backend/node_modules/@types/node/util/types.d.ts new file mode 100644 index 0000000..818825b --- /dev/null +++ b/backend/node_modules/@types/node/util/types.d.ts @@ -0,0 +1,558 @@ +declare module "node:util/types" { + import { KeyObject, webcrypto } from "node:crypto"; + /** + * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) or + * [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance. + * + * See also `util.types.isArrayBuffer()` and `util.types.isSharedArrayBuffer()`. + * + * ```js + * util.types.isAnyArrayBuffer(new ArrayBuffer()); // Returns true + * util.types.isAnyArrayBuffer(new SharedArrayBuffer()); // Returns true + * ``` + * @since v10.0.0 + */ + function isAnyArrayBuffer(object: unknown): object is ArrayBufferLike; + /** + * Returns `true` if the value is an `arguments` object. + * + * ```js + * function foo() { + * util.types.isArgumentsObject(arguments); // Returns true + * } + * ``` + * @since v10.0.0 + */ + function isArgumentsObject(object: unknown): object is IArguments; + /** + * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instance. + * This does _not_ include [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instances. Usually, it is + * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that. + * + * ```js + * util.types.isArrayBuffer(new ArrayBuffer()); // Returns true + * util.types.isArrayBuffer(new SharedArrayBuffer()); // Returns false + * ``` + * @since v10.0.0 + */ + function isArrayBuffer(object: unknown): object is ArrayBuffer; + /** + * Returns `true` if the value is an instance of one of the [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) views, such as typed + * array objects or [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView). Equivalent to + * [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * + * ```js + * util.types.isArrayBufferView(new Int8Array()); // true + * util.types.isArrayBufferView(Buffer.from('hello world')); // true + * util.types.isArrayBufferView(new DataView(new ArrayBuffer(16))); // true + * util.types.isArrayBufferView(new ArrayBuffer()); // false + * ``` + * @since v10.0.0 + */ + function isArrayBufferView(object: unknown): object is NodeJS.ArrayBufferView; + /** + * Returns `true` if the value is an [async function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function). + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * util.types.isAsyncFunction(function foo() {}); // Returns false + * util.types.isAsyncFunction(async function foo() {}); // Returns true + * ``` + * @since v10.0.0 + */ + function isAsyncFunction(object: unknown): boolean; + /** + * Returns `true` if the value is a `BigInt64Array` instance. + * + * ```js + * util.types.isBigInt64Array(new BigInt64Array()); // Returns true + * util.types.isBigInt64Array(new BigUint64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isBigInt64Array(value: unknown): value is BigInt64Array; + /** + * Returns `true` if the value is a BigInt object, e.g. created + * by `Object(BigInt(123))`. + * + * ```js + * util.types.isBigIntObject(Object(BigInt(123))); // Returns true + * util.types.isBigIntObject(BigInt(123)); // Returns false + * util.types.isBigIntObject(123); // Returns false + * ``` + * @since v10.4.0 + */ + function isBigIntObject(object: unknown): object is BigInt; + /** + * Returns `true` if the value is a `BigUint64Array` instance. + * + * ```js + * util.types.isBigUint64Array(new BigInt64Array()); // Returns false + * util.types.isBigUint64Array(new BigUint64Array()); // Returns true + * ``` + * @since v10.0.0 + */ + function isBigUint64Array(value: unknown): value is BigUint64Array; + /** + * Returns `true` if the value is a boolean object, e.g. created + * by `new Boolean()`. + * + * ```js + * util.types.isBooleanObject(false); // Returns false + * util.types.isBooleanObject(true); // Returns false + * util.types.isBooleanObject(new Boolean(false)); // Returns true + * util.types.isBooleanObject(new Boolean(true)); // Returns true + * util.types.isBooleanObject(Boolean(false)); // Returns false + * util.types.isBooleanObject(Boolean(true)); // Returns false + * ``` + * @since v10.0.0 + */ + function isBooleanObject(object: unknown): object is Boolean; + /** + * Returns `true` if the value is any boxed primitive object, e.g. created + * by `new Boolean()`, `new String()` or `Object(Symbol())`. + * + * For example: + * + * ```js + * util.types.isBoxedPrimitive(false); // Returns false + * util.types.isBoxedPrimitive(new Boolean(false)); // Returns true + * util.types.isBoxedPrimitive(Symbol('foo')); // Returns false + * util.types.isBoxedPrimitive(Object(Symbol('foo'))); // Returns true + * util.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true + * ``` + * @since v10.11.0 + */ + function isBoxedPrimitive(object: unknown): object is String | Number | BigInt | Boolean | Symbol; + /** + * Returns `true` if the value is a built-in [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) instance. + * + * ```js + * const ab = new ArrayBuffer(20); + * util.types.isDataView(new DataView(ab)); // Returns true + * util.types.isDataView(new Float64Array()); // Returns false + * ``` + * + * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * @since v10.0.0 + */ + function isDataView(object: unknown): object is DataView; + /** + * Returns `true` if the value is a built-in [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) instance. + * + * ```js + * util.types.isDate(new Date()); // Returns true + * ``` + * @since v10.0.0 + */ + function isDate(object: unknown): object is Date; + /** + * Returns `true` if the value is a native `External` value. + * + * A native `External` value is a special type of object that contains a + * raw C++ pointer (`void*`) for access from native code, and has no other + * properties. Such objects are created either by Node.js internals or native + * addons. In JavaScript, they are + * [frozen](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) objects with a + * `null` prototype. + * + * ```c + * #include + * #include + * napi_value result; + * static napi_value MyNapi(napi_env env, napi_callback_info info) { + * int* raw = (int*) malloc(1024); + * napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result); + * if (status != napi_ok) { + * napi_throw_error(env, NULL, "napi_create_external failed"); + * return NULL; + * } + * return result; + * } + * ... + * DECLARE_NAPI_PROPERTY("myNapi", MyNapi) + * ... + * ``` + * + * ```js + * import native from 'napi_addon.node'; + * import { types } from 'node:util'; + * + * const data = native.myNapi(); + * types.isExternal(data); // returns true + * types.isExternal(0); // returns false + * types.isExternal(new String('foo')); // returns false + * ``` + * + * For further information on `napi_create_external`, refer to + * [`napi_create_external()`](https://nodejs.org/docs/latest-v25.x/api/n-api.html#napi_create_external). + * @since v10.0.0 + */ + function isExternal(object: unknown): boolean; + /** + * Returns `true` if the value is a built-in [`Float16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float16Array) instance. + * + * ```js + * util.types.isFloat16Array(new ArrayBuffer()); // Returns false + * util.types.isFloat16Array(new Float16Array()); // Returns true + * util.types.isFloat16Array(new Float32Array()); // Returns false + * ``` + * @since v24.0.0 + */ + function isFloat16Array(object: unknown): object is Float16Array; + /** + * Returns `true` if the value is a built-in [`Float32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array) instance. + * + * ```js + * util.types.isFloat32Array(new ArrayBuffer()); // Returns false + * util.types.isFloat32Array(new Float32Array()); // Returns true + * util.types.isFloat32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isFloat32Array(object: unknown): object is Float32Array; + /** + * Returns `true` if the value is a built-in [`Float64Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array) instance. + * + * ```js + * util.types.isFloat64Array(new ArrayBuffer()); // Returns false + * util.types.isFloat64Array(new Uint8Array()); // Returns false + * util.types.isFloat64Array(new Float64Array()); // Returns true + * ``` + * @since v10.0.0 + */ + function isFloat64Array(object: unknown): object is Float64Array; + /** + * Returns `true` if the value is a generator function. + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * util.types.isGeneratorFunction(function foo() {}); // Returns false + * util.types.isGeneratorFunction(function* foo() {}); // Returns true + * ``` + * @since v10.0.0 + */ + function isGeneratorFunction(object: unknown): object is GeneratorFunction; + /** + * Returns `true` if the value is a generator object as returned from a + * built-in generator function. + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * function* foo() {} + * const generator = foo(); + * util.types.isGeneratorObject(generator); // Returns true + * ``` + * @since v10.0.0 + */ + function isGeneratorObject(object: unknown): object is Generator; + /** + * Returns `true` if the value is a built-in [`Int8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array) instance. + * + * ```js + * util.types.isInt8Array(new ArrayBuffer()); // Returns false + * util.types.isInt8Array(new Int8Array()); // Returns true + * util.types.isInt8Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt8Array(object: unknown): object is Int8Array; + /** + * Returns `true` if the value is a built-in [`Int16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array) instance. + * + * ```js + * util.types.isInt16Array(new ArrayBuffer()); // Returns false + * util.types.isInt16Array(new Int16Array()); // Returns true + * util.types.isInt16Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt16Array(object: unknown): object is Int16Array; + /** + * Returns `true` if the value is a built-in [`Int32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array) instance. + * + * ```js + * util.types.isInt32Array(new ArrayBuffer()); // Returns false + * util.types.isInt32Array(new Int32Array()); // Returns true + * util.types.isInt32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt32Array(object: unknown): object is Int32Array; + /** + * Returns `true` if the value is a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance. + * + * ```js + * util.types.isMap(new Map()); // Returns true + * ``` + * @since v10.0.0 + */ + function isMap( + object: T | {}, + ): object is T extends ReadonlyMap ? (unknown extends T ? never : ReadonlyMap) + : Map; + /** + * Returns `true` if the value is an iterator returned for a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance. + * + * ```js + * const map = new Map(); + * util.types.isMapIterator(map.keys()); // Returns true + * util.types.isMapIterator(map.values()); // Returns true + * util.types.isMapIterator(map.entries()); // Returns true + * util.types.isMapIterator(map[Symbol.iterator]()); // Returns true + * ``` + * @since v10.0.0 + */ + function isMapIterator(object: unknown): boolean; + /** + * Returns `true` if the value is an instance of a [Module Namespace Object](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects). + * + * ```js + * import * as ns from './a.js'; + * + * util.types.isModuleNamespaceObject(ns); // Returns true + * ``` + * @since v10.0.0 + */ + function isModuleNamespaceObject(value: unknown): boolean; + /** + * Returns `true` if the value was returned by the constructor of a + * [built-in `Error` type](https://tc39.es/ecma262/#sec-error-objects). + * + * ```js + * console.log(util.types.isNativeError(new Error())); // true + * console.log(util.types.isNativeError(new TypeError())); // true + * console.log(util.types.isNativeError(new RangeError())); // true + * ``` + * + * Subclasses of the native error types are also native errors: + * + * ```js + * class MyError extends Error {} + * console.log(util.types.isNativeError(new MyError())); // true + * ``` + * + * A value being `instanceof` a native error class is not equivalent to `isNativeError()` + * returning `true` for that value. `isNativeError()` returns `true` for errors + * which come from a different [realm](https://tc39.es/ecma262/#realm) while `instanceof Error` returns `false` + * for these errors: + * + * ```js + * import { createContext, runInContext } from 'node:vm'; + * import { types } from 'node:util'; + * + * const context = createContext({}); + * const myError = runInContext('new Error()', context); + * console.log(types.isNativeError(myError)); // true + * console.log(myError instanceof Error); // false + * ``` + * + * Conversely, `isNativeError()` returns `false` for all objects which were not + * returned by the constructor of a native error. That includes values + * which are `instanceof` native errors: + * + * ```js + * const myError = { __proto__: Error.prototype }; + * console.log(util.types.isNativeError(myError)); // false + * console.log(myError instanceof Error); // true + * ``` + * @since v10.0.0 + * @deprecated The `util.types.isNativeError` API is deprecated. Please use `Error.isError` instead. + */ + function isNativeError(object: unknown): object is Error; + /** + * Returns `true` if the value is a number object, e.g. created + * by `new Number()`. + * + * ```js + * util.types.isNumberObject(0); // Returns false + * util.types.isNumberObject(new Number(0)); // Returns true + * ``` + * @since v10.0.0 + */ + function isNumberObject(object: unknown): object is Number; + /** + * Returns `true` if the value is a built-in [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). + * + * ```js + * util.types.isPromise(Promise.resolve(42)); // Returns true + * ``` + * @since v10.0.0 + */ + function isPromise(object: unknown): object is Promise; + /** + * Returns `true` if the value is a [`Proxy`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) instance. + * + * ```js + * const target = {}; + * const proxy = new Proxy(target, {}); + * util.types.isProxy(target); // Returns false + * util.types.isProxy(proxy); // Returns true + * ``` + * @since v10.0.0 + */ + function isProxy(object: unknown): boolean; + /** + * Returns `true` if the value is a regular expression object. + * + * ```js + * util.types.isRegExp(/abc/); // Returns true + * util.types.isRegExp(new RegExp('abc')); // Returns true + * ``` + * @since v10.0.0 + */ + function isRegExp(object: unknown): object is RegExp; + /** + * Returns `true` if the value is a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance. + * + * ```js + * util.types.isSet(new Set()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSet( + object: T | {}, + ): object is T extends ReadonlySet ? (unknown extends T ? never : ReadonlySet) : Set; + /** + * Returns `true` if the value is an iterator returned for a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance. + * + * ```js + * const set = new Set(); + * util.types.isSetIterator(set.keys()); // Returns true + * util.types.isSetIterator(set.values()); // Returns true + * util.types.isSetIterator(set.entries()); // Returns true + * util.types.isSetIterator(set[Symbol.iterator]()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSetIterator(object: unknown): boolean; + /** + * Returns `true` if the value is a built-in [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance. + * This does _not_ include [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instances. Usually, it is + * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that. + * + * ```js + * util.types.isSharedArrayBuffer(new ArrayBuffer()); // Returns false + * util.types.isSharedArrayBuffer(new SharedArrayBuffer()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSharedArrayBuffer(object: unknown): object is SharedArrayBuffer; + /** + * Returns `true` if the value is a string object, e.g. created + * by `new String()`. + * + * ```js + * util.types.isStringObject('foo'); // Returns false + * util.types.isStringObject(new String('foo')); // Returns true + * ``` + * @since v10.0.0 + */ + function isStringObject(object: unknown): object is String; + /** + * Returns `true` if the value is a symbol object, created + * by calling `Object()` on a `Symbol` primitive. + * + * ```js + * const symbol = Symbol('foo'); + * util.types.isSymbolObject(symbol); // Returns false + * util.types.isSymbolObject(Object(symbol)); // Returns true + * ``` + * @since v10.0.0 + */ + function isSymbolObject(object: unknown): object is Symbol; + /** + * Returns `true` if the value is a built-in [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) instance. + * + * ```js + * util.types.isTypedArray(new ArrayBuffer()); // Returns false + * util.types.isTypedArray(new Uint8Array()); // Returns true + * util.types.isTypedArray(new Float64Array()); // Returns true + * ``` + * + * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * @since v10.0.0 + */ + function isTypedArray(object: unknown): object is NodeJS.TypedArray; + /** + * Returns `true` if the value is a built-in [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) instance. + * + * ```js + * util.types.isUint8Array(new ArrayBuffer()); // Returns false + * util.types.isUint8Array(new Uint8Array()); // Returns true + * util.types.isUint8Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint8Array(object: unknown): object is Uint8Array; + /** + * Returns `true` if the value is a built-in [`Uint8ClampedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray) instance. + * + * ```js + * util.types.isUint8ClampedArray(new ArrayBuffer()); // Returns false + * util.types.isUint8ClampedArray(new Uint8ClampedArray()); // Returns true + * util.types.isUint8ClampedArray(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint8ClampedArray(object: unknown): object is Uint8ClampedArray; + /** + * Returns `true` if the value is a built-in [`Uint16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array) instance. + * + * ```js + * util.types.isUint16Array(new ArrayBuffer()); // Returns false + * util.types.isUint16Array(new Uint16Array()); // Returns true + * util.types.isUint16Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint16Array(object: unknown): object is Uint16Array; + /** + * Returns `true` if the value is a built-in [`Uint32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array) instance. + * + * ```js + * util.types.isUint32Array(new ArrayBuffer()); // Returns false + * util.types.isUint32Array(new Uint32Array()); // Returns true + * util.types.isUint32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint32Array(object: unknown): object is Uint32Array; + /** + * Returns `true` if the value is a built-in [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) instance. + * + * ```js + * util.types.isWeakMap(new WeakMap()); // Returns true + * ``` + * @since v10.0.0 + */ + function isWeakMap(object: unknown): object is WeakMap; + /** + * Returns `true` if the value is a built-in [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) instance. + * + * ```js + * util.types.isWeakSet(new WeakSet()); // Returns true + * ``` + * @since v10.0.0 + */ + function isWeakSet(object: unknown): object is WeakSet; + /** + * Returns `true` if `value` is a `KeyObject`, `false` otherwise. + * @since v16.2.0 + */ + function isKeyObject(object: unknown): object is KeyObject; + /** + * Returns `true` if `value` is a `CryptoKey`, `false` otherwise. + * @since v16.2.0 + */ + function isCryptoKey(object: unknown): object is webcrypto.CryptoKey; +} +declare module "util/types" { + export * from "node:util/types"; +} diff --git a/backend/node_modules/@types/node/v8.d.ts b/backend/node_modules/@types/node/v8.d.ts new file mode 100644 index 0000000..9216587 --- /dev/null +++ b/backend/node_modules/@types/node/v8.d.ts @@ -0,0 +1,979 @@ +/** + * The `node:v8` module exposes APIs that are specific to the version of [V8](https://developers.google.com/v8/) built into the Node.js binary. It can be accessed using: + * + * ```js + * import v8 from 'node:v8'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/v8.js) + */ +declare module "node:v8" { + import { NonSharedBuffer } from "node:buffer"; + import { Readable } from "node:stream"; + interface HeapSpaceInfo { + space_name: string; + space_size: number; + space_used_size: number; + space_available_size: number; + physical_space_size: number; + } + // ** Signifies if the --zap_code_space option is enabled or not. 1 == enabled, 0 == disabled. */ + type DoesZapCodeSpaceFlag = 0 | 1; + interface HeapInfo { + total_heap_size: number; + total_heap_size_executable: number; + total_physical_size: number; + total_available_size: number; + used_heap_size: number; + heap_size_limit: number; + malloced_memory: number; + peak_malloced_memory: number; + does_zap_garbage: DoesZapCodeSpaceFlag; + number_of_native_contexts: number; + number_of_detached_contexts: number; + total_global_handles_size: number; + used_global_handles_size: number; + external_memory: number; + } + interface HeapCodeStatistics { + code_and_metadata_size: number; + bytecode_and_metadata_size: number; + external_script_source_size: number; + } + interface HeapSnapshotOptions { + /** + * If true, expose internals in the heap snapshot. + * @default false + */ + exposeInternals?: boolean | undefined; + /** + * If true, expose numeric values in artificial fields. + * @default false + */ + exposeNumericValues?: boolean | undefined; + } + /** + * Returns an integer representing a version tag derived from the V8 version, + * command-line flags, and detected CPU features. This is useful for determining + * whether a `vm.Script` `cachedData` buffer is compatible with this instance + * of V8. + * + * ```js + * console.log(v8.cachedDataVersionTag()); // 3947234607 + * // The value returned by v8.cachedDataVersionTag() is derived from the V8 + * // version, command-line flags, and detected CPU features. Test that the value + * // does indeed update when flags are toggled. + * v8.setFlagsFromString('--allow_natives_syntax'); + * console.log(v8.cachedDataVersionTag()); // 183726201 + * ``` + * @since v8.0.0 + */ + function cachedDataVersionTag(): number; + /** + * Returns an object with the following properties: + * + * `does_zap_garbage` is a 0/1 boolean, which signifies whether the `--zap_code_space` option is enabled or not. This makes V8 overwrite heap + * garbage with a bit pattern. The RSS footprint (resident set size) gets bigger + * because it continuously touches all heap pages and that makes them less likely + * to get swapped out by the operating system. + * + * `number_of_native_contexts` The value of native\_context is the number of the + * top-level contexts currently active. Increase of this number over time indicates + * a memory leak. + * + * `number_of_detached_contexts` The value of detached\_context is the number + * of contexts that were detached and not yet garbage collected. This number + * being non-zero indicates a potential memory leak. + * + * `total_global_handles_size` The value of total\_global\_handles\_size is the + * total memory size of V8 global handles. + * + * `used_global_handles_size` The value of used\_global\_handles\_size is the + * used memory size of V8 global handles. + * + * `external_memory` The value of external\_memory is the memory size of array + * buffers and external strings. + * + * ```js + * { + * total_heap_size: 7326976, + * total_heap_size_executable: 4194304, + * total_physical_size: 7326976, + * total_available_size: 1152656, + * used_heap_size: 3476208, + * heap_size_limit: 1535115264, + * malloced_memory: 16384, + * peak_malloced_memory: 1127496, + * does_zap_garbage: 0, + * number_of_native_contexts: 1, + * number_of_detached_contexts: 0, + * total_global_handles_size: 8192, + * used_global_handles_size: 3296, + * external_memory: 318824 + * } + * ``` + * @since v1.0.0 + */ + function getHeapStatistics(): HeapInfo; + /** + * It returns an object with a structure similar to the + * [`cppgc::HeapStatistics`](https://v8docs.nodesource.com/node-22.4/d7/d51/heap-statistics_8h_source.html) + * object. See the [V8 documentation](https://v8docs.nodesource.com/node-22.4/df/d2f/structcppgc_1_1_heap_statistics.html) + * for more information about the properties of the object. + * + * ```js + * // Detailed + * ({ + * committed_size_bytes: 131072, + * resident_size_bytes: 131072, + * used_size_bytes: 152, + * space_statistics: [ + * { + * name: 'NormalPageSpace0', + * committed_size_bytes: 0, + * resident_size_bytes: 0, + * used_size_bytes: 0, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * { + * name: 'NormalPageSpace1', + * committed_size_bytes: 131072, + * resident_size_bytes: 131072, + * used_size_bytes: 152, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * { + * name: 'NormalPageSpace2', + * committed_size_bytes: 0, + * resident_size_bytes: 0, + * used_size_bytes: 0, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * { + * name: 'NormalPageSpace3', + * committed_size_bytes: 0, + * resident_size_bytes: 0, + * used_size_bytes: 0, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * { + * name: 'LargePageSpace', + * committed_size_bytes: 0, + * resident_size_bytes: 0, + * used_size_bytes: 0, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * ], + * type_names: [], + * detail_level: 'detailed', + * }); + * ``` + * + * ```js + * // Brief + * ({ + * committed_size_bytes: 131072, + * resident_size_bytes: 131072, + * used_size_bytes: 128864, + * space_statistics: [], + * type_names: [], + * detail_level: 'brief', + * }); + * ``` + * @since v22.15.0 + * @param detailLevel **Default:** `'detailed'`. Specifies the level of detail in the returned statistics. + * Accepted values are: + * * `'brief'`: Brief statistics contain only the top-level + * allocated and used + * memory statistics for the entire heap. + * * `'detailed'`: Detailed statistics also contain a break + * down per space and page, as well as freelist statistics + * and object type histograms. + */ + function getCppHeapStatistics(detailLevel?: "brief" | "detailed"): object; + /** + * Returns statistics about the V8 heap spaces, i.e. the segments which make up + * the V8 heap. Neither the ordering of heap spaces, nor the availability of a + * heap space can be guaranteed as the statistics are provided via the + * V8 [`GetHeapSpaceStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#ac673576f24fdc7a33378f8f57e1d13a4) function and may change from one V8 version to the + * next. + * + * The value returned is an array of objects containing the following properties: + * + * ```json + * [ + * { + * "space_name": "new_space", + * "space_size": 2063872, + * "space_used_size": 951112, + * "space_available_size": 80824, + * "physical_space_size": 2063872 + * }, + * { + * "space_name": "old_space", + * "space_size": 3090560, + * "space_used_size": 2493792, + * "space_available_size": 0, + * "physical_space_size": 3090560 + * }, + * { + * "space_name": "code_space", + * "space_size": 1260160, + * "space_used_size": 644256, + * "space_available_size": 960, + * "physical_space_size": 1260160 + * }, + * { + * "space_name": "map_space", + * "space_size": 1094160, + * "space_used_size": 201608, + * "space_available_size": 0, + * "physical_space_size": 1094160 + * }, + * { + * "space_name": "large_object_space", + * "space_size": 0, + * "space_used_size": 0, + * "space_available_size": 1490980608, + * "physical_space_size": 0 + * } + * ] + * ``` + * @since v6.0.0 + */ + function getHeapSpaceStatistics(): HeapSpaceInfo[]; + /** + * The `v8.setFlagsFromString()` method can be used to programmatically set + * V8 command-line flags. This method should be used with care. Changing settings + * after the VM has started may result in unpredictable behavior, including + * crashes and data loss; or it may simply do nothing. + * + * The V8 options available for a version of Node.js may be determined by running `node --v8-options`. + * + * Usage: + * + * ```js + * // Print GC events to stdout for one minute. + * import v8 from 'node:v8'; + * v8.setFlagsFromString('--trace_gc'); + * setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3); + * ``` + * @since v1.0.0 + */ + function setFlagsFromString(flags: string): void; + /** + * This is similar to the [`queryObjects()` console API](https://developer.chrome.com/docs/devtools/console/utilities#queryObjects-function) + * provided by the Chromium DevTools console. It can be used to search for objects that have the matching constructor on its prototype chain + * in the heap after a full garbage collection, which can be useful for memory leak regression tests. To avoid surprising results, users should + * avoid using this API on constructors whose implementation they don't control, or on constructors that can be invoked by other parties in the + * application. + * + * To avoid accidental leaks, this API does not return raw references to the objects found. By default, it returns the count of the objects + * found. If `options.format` is `'summary'`, it returns an array containing brief string representations for each object. The visibility provided + * in this API is similar to what the heap snapshot provides, while users can save the cost of serialization and parsing and directly filter the + * target objects during the search. + * + * Only objects created in the current execution context are included in the results. + * + * ```js + * import { queryObjects } from 'node:v8'; + * class A { foo = 'bar'; } + * console.log(queryObjects(A)); // 0 + * const a = new A(); + * console.log(queryObjects(A)); // 1 + * // [ "A { foo: 'bar' }" ] + * console.log(queryObjects(A, { format: 'summary' })); + * + * class B extends A { bar = 'qux'; } + * const b = new B(); + * console.log(queryObjects(B)); // 1 + * // [ "B { foo: 'bar', bar: 'qux' }" ] + * console.log(queryObjects(B, { format: 'summary' })); + * + * // Note that, when there are child classes inheriting from a constructor, + * // the constructor also shows up in the prototype chain of the child + * // classes's prototoype, so the child classes's prototoype would also be + * // included in the result. + * console.log(queryObjects(A)); // 3 + * // [ "B { foo: 'bar', bar: 'qux' }", 'A {}', "A { foo: 'bar' }" ] + * console.log(queryObjects(A, { format: 'summary' })); + * ``` + * @param ctor The constructor that can be used to search on the prototype chain in order to filter target objects in the heap. + * @since v20.13.0 + * @experimental + */ + function queryObjects(ctor: Function): number | string[]; + function queryObjects(ctor: Function, options: { format: "count" }): number; + function queryObjects(ctor: Function, options: { format: "summary" }): string[]; + /** + * Generates a snapshot of the current V8 heap and returns a Readable + * Stream that may be used to read the JSON serialized representation. + * This JSON stream format is intended to be used with tools such as + * Chrome DevTools. The JSON schema is undocumented and specific to the + * V8 engine. Therefore, the schema may change from one version of V8 to the next. + * + * Creating a heap snapshot requires memory about twice the size of the heap at + * the time the snapshot is created. This results in the risk of OOM killers + * terminating the process. + * + * Generating a snapshot is a synchronous operation which blocks the event loop + * for a duration depending on the heap size. + * + * ```js + * // Print heap snapshot to the console + * import v8 from 'node:v8'; + * const stream = v8.getHeapSnapshot(); + * stream.pipe(process.stdout); + * ``` + * @since v11.13.0 + * @return A Readable containing the V8 heap snapshot. + */ + function getHeapSnapshot(options?: HeapSnapshotOptions): Readable; + /** + * Generates a snapshot of the current V8 heap and writes it to a JSON + * file. This file is intended to be used with tools such as Chrome + * DevTools. The JSON schema is undocumented and specific to the V8 + * engine, and may change from one version of V8 to the next. + * + * A heap snapshot is specific to a single V8 isolate. When using `worker threads`, a heap snapshot generated from the main thread will + * not contain any information about the workers, and vice versa. + * + * Creating a heap snapshot requires memory about twice the size of the heap at + * the time the snapshot is created. This results in the risk of OOM killers + * terminating the process. + * + * Generating a snapshot is a synchronous operation which blocks the event loop + * for a duration depending on the heap size. + * + * ```js + * import { writeHeapSnapshot } from 'node:v8'; + * import { + * Worker, + * isMainThread, + * parentPort, + * } from 'node:worker_threads'; + * + * if (isMainThread) { + * const worker = new Worker(__filename); + * + * worker.once('message', (filename) => { + * console.log(`worker heapdump: ${filename}`); + * // Now get a heapdump for the main thread. + * console.log(`main thread heapdump: ${writeHeapSnapshot()}`); + * }); + * + * // Tell the worker to create a heapdump. + * worker.postMessage('heapdump'); + * } else { + * parentPort.once('message', (message) => { + * if (message === 'heapdump') { + * // Generate a heapdump for the worker + * // and return the filename to the parent. + * parentPort.postMessage(writeHeapSnapshot()); + * } + * }); + * } + * ``` + * @since v11.13.0 + * @param filename The file path where the V8 heap snapshot is to be saved. If not specified, a file name with the pattern `'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot'` will be + * generated, where `{pid}` will be the PID of the Node.js process, `{thread_id}` will be `0` when `writeHeapSnapshot()` is called from the main Node.js thread or the id of a + * worker thread. + * @return The filename where the snapshot was saved. + */ + function writeHeapSnapshot(filename?: string, options?: HeapSnapshotOptions): string; + /** + * Get statistics about code and its metadata in the heap, see + * V8 [`GetHeapCodeAndMetadataStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#a6079122af17612ef54ef3348ce170866) API. Returns an object with the + * following properties: + * + * ```js + * { + * code_and_metadata_size: 212208, + * bytecode_and_metadata_size: 161368, + * external_script_source_size: 1410794, + * cpu_profiler_metadata_size: 0, + * } + * ``` + * @since v12.8.0 + */ + function getHeapCodeStatistics(): HeapCodeStatistics; + /** + * @since v25.0.0 + */ + interface SyncCPUProfileHandle { + /** + * Stopping collecting the profile and return the profile data. + * @since v25.0.0 + */ + stop(): string; + /** + * Stopping collecting the profile and the profile will be discarded. + * @since v25.0.0 + */ + [Symbol.dispose](): void; + } + /** + * @since v24.8.0 + */ + interface CPUProfileHandle { + /** + * Stopping collecting the profile, then return a Promise that fulfills with an error or the + * profile data. + * @since v24.8.0 + */ + stop(): Promise; + /** + * Stopping collecting the profile and the profile will be discarded. + * @since v24.8.0 + */ + [Symbol.asyncDispose](): Promise; + } + /** + * @since v24.9.0 + */ + interface HeapProfileHandle { + /** + * Stopping collecting the profile, then return a Promise that fulfills with an error or the + * profile data. + * @since v24.9.0 + */ + stop(): Promise; + /** + * Stopping collecting the profile and the profile will be discarded. + * @since v24.9.0 + */ + [Symbol.asyncDispose](): Promise; + } + /** + * Starting a CPU profile then return a `SyncCPUProfileHandle` object. + * This API supports `using` syntax. + * + * ```js + * const handle = v8.startCpuProfile(); + * const profile = handle.stop(); + * console.log(profile); + * ``` + * @since v25.0.0 + */ + function startCPUProfile(): SyncCPUProfileHandle; + /** + * V8 only supports `Latin-1/ISO-8859-1` and `UTF16` as the underlying representation of a string. + * If the `content` uses `Latin-1/ISO-8859-1` as the underlying representation, this function will return true; + * otherwise, it returns false. + * + * If this method returns false, that does not mean that the string contains some characters not in `Latin-1/ISO-8859-1`. + * Sometimes a `Latin-1` string may also be represented as `UTF16`. + * + * ```js + * const { isStringOneByteRepresentation } = require('node:v8'); + * + * const Encoding = { + * latin1: 1, + * utf16le: 2, + * }; + * const buffer = Buffer.alloc(100); + * function writeString(input) { + * if (isStringOneByteRepresentation(input)) { + * buffer.writeUint8(Encoding.latin1); + * buffer.writeUint32LE(input.length, 1); + * buffer.write(input, 5, 'latin1'); + * } else { + * buffer.writeUint8(Encoding.utf16le); + * buffer.writeUint32LE(input.length * 2, 1); + * buffer.write(input, 5, 'utf16le'); + * } + * } + * writeString('hello'); + * writeString('你好'); + * ``` + * @since v23.10.0, v22.15.0 + */ + function isStringOneByteRepresentation(content: string): boolean; + /** + * @since v8.0.0 + */ + class Serializer { + /** + * Writes out a header, which includes the serialization format version. + */ + writeHeader(): void; + /** + * Serializes a JavaScript value and adds the serialized representation to the + * internal buffer. + * + * This throws an error if `value` cannot be serialized. + */ + writeValue(val: any): boolean; + /** + * Returns the stored internal buffer. This serializer should not be used once + * the buffer is released. Calling this method results in undefined behavior + * if a previous write has failed. + */ + releaseBuffer(): NonSharedBuffer; + /** + * Marks an `ArrayBuffer` as having its contents transferred out of band. + * Pass the corresponding `ArrayBuffer` in the deserializing context to `deserializer.transferArrayBuffer()`. + * @param id A 32-bit unsigned integer. + * @param arrayBuffer An `ArrayBuffer` instance. + */ + transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; + /** + * Write a raw 32-bit unsigned integer. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeUint32(value: number): void; + /** + * Write a raw 64-bit unsigned integer, split into high and low 32-bit parts. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeUint64(hi: number, lo: number): void; + /** + * Write a JS `number` value. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeDouble(value: number): void; + /** + * Write raw bytes into the serializer's internal buffer. The deserializer + * will require a way to compute the length of the buffer. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeRawBytes(buffer: NodeJS.ArrayBufferView): void; + } + /** + * A subclass of `Serializer` that serializes `TypedArray`(in particular `Buffer`) and `DataView` objects as host objects, and only + * stores the part of their underlying `ArrayBuffer`s that they are referring to. + * @since v8.0.0 + */ + class DefaultSerializer extends Serializer {} + /** + * @since v8.0.0 + */ + class Deserializer { + constructor(data: NodeJS.TypedArray); + /** + * Reads and validates a header (including the format version). + * May, for example, reject an invalid or unsupported wire format. In that case, + * an `Error` is thrown. + */ + readHeader(): boolean; + /** + * Deserializes a JavaScript value from the buffer and returns it. + */ + readValue(): any; + /** + * Marks an `ArrayBuffer` as having its contents transferred out of band. + * Pass the corresponding `ArrayBuffer` in the serializing context to `serializer.transferArrayBuffer()` (or return the `id` from `serializer._getSharedArrayBufferId()` in the case of + * `SharedArrayBuffer`s). + * @param id A 32-bit unsigned integer. + * @param arrayBuffer An `ArrayBuffer` instance. + */ + transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; + /** + * Reads the underlying wire format version. Likely mostly to be useful to + * legacy code reading old wire format versions. May not be called before `.readHeader()`. + */ + getWireFormatVersion(): number; + /** + * Read a raw 32-bit unsigned integer and return it. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readUint32(): number; + /** + * Read a raw 64-bit unsigned integer and return it as an array `[hi, lo]` with two 32-bit unsigned integer entries. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readUint64(): [number, number]; + /** + * Read a JS `number` value. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readDouble(): number; + /** + * Read raw bytes from the deserializer's internal buffer. The `length` parameter + * must correspond to the length of the buffer that was passed to `serializer.writeRawBytes()`. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readRawBytes(length: number): Buffer; + } + /** + * A subclass of `Deserializer` corresponding to the format written by `DefaultSerializer`. + * @since v8.0.0 + */ + class DefaultDeserializer extends Deserializer {} + /** + * Uses a `DefaultSerializer` to serialize `value` into a buffer. + * + * `ERR_BUFFER_TOO_LARGE` will be thrown when trying to + * serialize a huge object which requires buffer + * larger than `buffer.constants.MAX_LENGTH`. + * @since v8.0.0 + */ + function serialize(value: any): NonSharedBuffer; + /** + * Uses a `DefaultDeserializer` with default options to read a JS value + * from a buffer. + * @since v8.0.0 + * @param buffer A buffer returned by {@link serialize}. + */ + function deserialize(buffer: NodeJS.ArrayBufferView): any; + /** + * The `v8.takeCoverage()` method allows the user to write the coverage started by `NODE_V8_COVERAGE` to disk on demand. This method can be invoked multiple + * times during the lifetime of the process. Each time the execution counter will + * be reset and a new coverage report will be written to the directory specified + * by `NODE_V8_COVERAGE`. + * + * When the process is about to exit, one last coverage will still be written to + * disk unless {@link stopCoverage} is invoked before the process exits. + * @since v15.1.0, v14.18.0, v12.22.0 + */ + function takeCoverage(): void; + /** + * The `v8.stopCoverage()` method allows the user to stop the coverage collection + * started by `NODE_V8_COVERAGE`, so that V8 can release the execution count + * records and optimize code. This can be used in conjunction with {@link takeCoverage} if the user wants to collect the coverage on demand. + * @since v15.1.0, v14.18.0, v12.22.0 + */ + function stopCoverage(): void; + /** + * The API is a no-op if `--heapsnapshot-near-heap-limit` is already set from the command line or the API is called more than once. + * `limit` must be a positive integer. See [`--heapsnapshot-near-heap-limit`](https://nodejs.org/docs/latest-v25.x/api/cli.html#--heapsnapshot-near-heap-limitmax_count) for more information. + * @since v18.10.0, v16.18.0 + */ + function setHeapSnapshotNearHeapLimit(limit: number): void; + /** + * This API collects GC data in current thread. + * @since v19.6.0, v18.15.0 + */ + class GCProfiler { + /** + * Start collecting GC data. + * @since v19.6.0, v18.15.0 + */ + start(): void; + /** + * Stop collecting GC data and return an object. The content of object + * is as follows. + * + * ```json + * { + * "version": 1, + * "startTime": 1674059033862, + * "statistics": [ + * { + * "gcType": "Scavenge", + * "beforeGC": { + * "heapStatistics": { + * "totalHeapSize": 5005312, + * "totalHeapSizeExecutable": 524288, + * "totalPhysicalSize": 5226496, + * "totalAvailableSize": 4341325216, + * "totalGlobalHandlesSize": 8192, + * "usedGlobalHandlesSize": 2112, + * "usedHeapSize": 4883840, + * "heapSizeLimit": 4345298944, + * "mallocedMemory": 254128, + * "externalMemory": 225138, + * "peakMallocedMemory": 181760 + * }, + * "heapSpaceStatistics": [ + * { + * "spaceName": "read_only_space", + * "spaceSize": 0, + * "spaceUsedSize": 0, + * "spaceAvailableSize": 0, + * "physicalSpaceSize": 0 + * } + * ] + * }, + * "cost": 1574.14, + * "afterGC": { + * "heapStatistics": { + * "totalHeapSize": 6053888, + * "totalHeapSizeExecutable": 524288, + * "totalPhysicalSize": 5500928, + * "totalAvailableSize": 4341101384, + * "totalGlobalHandlesSize": 8192, + * "usedGlobalHandlesSize": 2112, + * "usedHeapSize": 4059096, + * "heapSizeLimit": 4345298944, + * "mallocedMemory": 254128, + * "externalMemory": 225138, + * "peakMallocedMemory": 181760 + * }, + * "heapSpaceStatistics": [ + * { + * "spaceName": "read_only_space", + * "spaceSize": 0, + * "spaceUsedSize": 0, + * "spaceAvailableSize": 0, + * "physicalSpaceSize": 0 + * } + * ] + * } + * } + * ], + * "endTime": 1674059036865 + * } + * ``` + * + * Here's an example. + * + * ```js + * import { GCProfiler } from 'node:v8'; + * const profiler = new GCProfiler(); + * profiler.start(); + * setTimeout(() => { + * console.log(profiler.stop()); + * }, 1000); + * ``` + * @since v19.6.0, v18.15.0 + */ + stop(): GCProfilerResult; + } + interface GCProfilerResult { + version: number; + startTime: number; + endTime: number; + statistics: Array<{ + gcType: string; + cost: number; + beforeGC: { + heapStatistics: HeapStatistics; + heapSpaceStatistics: HeapSpaceStatistics[]; + }; + afterGC: { + heapStatistics: HeapStatistics; + heapSpaceStatistics: HeapSpaceStatistics[]; + }; + }>; + } + interface HeapStatistics { + totalHeapSize: number; + totalHeapSizeExecutable: number; + totalPhysicalSize: number; + totalAvailableSize: number; + totalGlobalHandlesSize: number; + usedGlobalHandlesSize: number; + usedHeapSize: number; + heapSizeLimit: number; + mallocedMemory: number; + externalMemory: number; + peakMallocedMemory: number; + } + interface HeapSpaceStatistics { + spaceName: string; + spaceSize: number; + spaceUsedSize: number; + spaceAvailableSize: number; + physicalSpaceSize: number; + } + /** + * Called when a promise is constructed. This does not mean that corresponding before/after events will occur, only that the possibility exists. This will + * happen if a promise is created without ever getting a continuation. + * @since v17.1.0, v16.14.0 + * @param promise The promise being created. + * @param parent The promise continued from, if applicable. + */ + interface Init { + (promise: Promise, parent: Promise): void; + } + /** + * Called before a promise continuation executes. This can be in the form of `then()`, `catch()`, or `finally()` handlers or an await resuming. + * + * The before callback will be called 0 to N times. The before callback will typically be called 0 times if no continuation was ever made for the promise. + * The before callback may be called many times in the case where many continuations have been made from the same promise. + * @since v17.1.0, v16.14.0 + */ + interface Before { + (promise: Promise): void; + } + /** + * Called immediately after a promise continuation executes. This may be after a `then()`, `catch()`, or `finally()` handler or before an await after another await. + * @since v17.1.0, v16.14.0 + */ + interface After { + (promise: Promise): void; + } + /** + * Called when the promise receives a resolution or rejection value. This may occur synchronously in the case of {@link Promise.resolve()} or + * {@link Promise.reject()}. + * @since v17.1.0, v16.14.0 + */ + interface Settled { + (promise: Promise): void; + } + /** + * Key events in the lifetime of a promise have been categorized into four areas: creation of a promise, before/after a continuation handler is called or + * around an await, and when the promise resolves or rejects. + * + * Because promises are asynchronous resources whose lifecycle is tracked via the promise hooks mechanism, the `init()`, `before()`, `after()`, and + * `settled()` callbacks must not be async functions as they create more promises which would produce an infinite loop. + * @since v17.1.0, v16.14.0 + */ + interface HookCallbacks { + init?: Init; + before?: Before; + after?: After; + settled?: Settled; + } + interface PromiseHooks { + /** + * The `init` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param init The {@link Init | `init` callback} to call when a promise is created. + * @return Call to stop the hook. + */ + onInit: (init: Init) => Function; + /** + * The `settled` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param settled The {@link Settled | `settled` callback} to call when a promise is created. + * @return Call to stop the hook. + */ + onSettled: (settled: Settled) => Function; + /** + * The `before` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param before The {@link Before | `before` callback} to call before a promise continuation executes. + * @return Call to stop the hook. + */ + onBefore: (before: Before) => Function; + /** + * The `after` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param after The {@link After | `after` callback} to call after a promise continuation executes. + * @return Call to stop the hook. + */ + onAfter: (after: After) => Function; + /** + * Registers functions to be called for different lifetime events of each promise. + * The callbacks `init()`/`before()`/`after()`/`settled()` are called for the respective events during a promise's lifetime. + * All callbacks are optional. For example, if only promise creation needs to be tracked, then only the init callback needs to be passed. + * The hook callbacks must be plain functions. Providing async functions will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param callbacks The {@link HookCallbacks | Hook Callbacks} to register + * @return Used for disabling hooks + */ + createHook: (callbacks: HookCallbacks) => Function; + } + /** + * The `promiseHooks` interface can be used to track promise lifecycle events. + * @since v17.1.0, v16.14.0 + */ + const promiseHooks: PromiseHooks; + type StartupSnapshotCallbackFn = (args: any) => any; + /** + * The `v8.startupSnapshot` interface can be used to add serialization and deserialization hooks for custom startup snapshots. + * + * ```bash + * $ node --snapshot-blob snapshot.blob --build-snapshot entry.js + * # This launches a process with the snapshot + * $ node --snapshot-blob snapshot.blob + * ``` + * + * In the example above, `entry.js` can use methods from the `v8.startupSnapshot` interface to specify how to save information for custom objects + * in the snapshot during serialization and how the information can be used to synchronize these objects during deserialization of the snapshot. + * For example, if the `entry.js` contains the following script: + * + * ```js + * 'use strict'; + * + * import fs from 'node:fs'; + * import zlib from 'node:zlib'; + * import path from 'node:path'; + * import assert from 'node:assert'; + * + * import v8 from 'node:v8'; + * + * class BookShelf { + * storage = new Map(); + * + * // Reading a series of files from directory and store them into storage. + * constructor(directory, books) { + * for (const book of books) { + * this.storage.set(book, fs.readFileSync(path.join(directory, book))); + * } + * } + * + * static compressAll(shelf) { + * for (const [ book, content ] of shelf.storage) { + * shelf.storage.set(book, zlib.gzipSync(content)); + * } + * } + * + * static decompressAll(shelf) { + * for (const [ book, content ] of shelf.storage) { + * shelf.storage.set(book, zlib.gunzipSync(content)); + * } + * } + * } + * + * // __dirname here is where the snapshot script is placed + * // during snapshot building time. + * const shelf = new BookShelf(__dirname, [ + * 'book1.en_US.txt', + * 'book1.es_ES.txt', + * 'book2.zh_CN.txt', + * ]); + * + * assert(v8.startupSnapshot.isBuildingSnapshot()); + * // On snapshot serialization, compress the books to reduce size. + * v8.startupSnapshot.addSerializeCallback(BookShelf.compressAll, shelf); + * // On snapshot deserialization, decompress the books. + * v8.startupSnapshot.addDeserializeCallback(BookShelf.decompressAll, shelf); + * v8.startupSnapshot.setDeserializeMainFunction((shelf) => { + * // process.env and process.argv are refreshed during snapshot + * // deserialization. + * const lang = process.env.BOOK_LANG || 'en_US'; + * const book = process.argv[1]; + * const name = `${book}.${lang}.txt`; + * console.log(shelf.storage.get(name)); + * }, shelf); + * ``` + * + * The resulted binary will get print the data deserialized from the snapshot during start up, using the refreshed `process.env` and `process.argv` of the launched process: + * + * ```bash + * $ BOOK_LANG=es_ES node --snapshot-blob snapshot.blob book1 + * # Prints content of book1.es_ES.txt deserialized from the snapshot. + * ``` + * + * Currently the application deserialized from a user-land snapshot cannot be snapshotted again, so these APIs are only available to applications that are not deserialized from a user-land snapshot. + * + * @since v18.6.0, v16.17.0 + */ + namespace startupSnapshot { + /** + * Add a callback that will be called when the Node.js instance is about to get serialized into a snapshot and exit. + * This can be used to release resources that should not or cannot be serialized or to convert user data into a form more suitable for serialization. + * @since v18.6.0, v16.17.0 + */ + function addSerializeCallback(callback: StartupSnapshotCallbackFn, data?: any): void; + /** + * Add a callback that will be called when the Node.js instance is deserialized from a snapshot. + * The `callback` and the `data` (if provided) will be serialized into the snapshot, they can be used to re-initialize the state of the application or + * to re-acquire resources that the application needs when the application is restarted from the snapshot. + * @since v18.6.0, v16.17.0 + */ + function addDeserializeCallback(callback: StartupSnapshotCallbackFn, data?: any): void; + /** + * This sets the entry point of the Node.js application when it is deserialized from a snapshot. This can be called only once in the snapshot building script. + * If called, the deserialized application no longer needs an additional entry point script to start up and will simply invoke the callback along with the deserialized + * data (if provided), otherwise an entry point script still needs to be provided to the deserialized application. + * @since v18.6.0, v16.17.0 + */ + function setDeserializeMainFunction(callback: StartupSnapshotCallbackFn, data?: any): void; + /** + * Returns true if the Node.js instance is run to build a snapshot. + * @since v18.6.0, v16.17.0 + */ + function isBuildingSnapshot(): boolean; + } +} +declare module "v8" { + export * from "node:v8"; +} diff --git a/backend/node_modules/@types/node/vm.d.ts b/backend/node_modules/@types/node/vm.d.ts new file mode 100644 index 0000000..b096c91 --- /dev/null +++ b/backend/node_modules/@types/node/vm.d.ts @@ -0,0 +1,1180 @@ +/** + * The `node:vm` module enables compiling and running code within V8 Virtual + * Machine contexts. + * + * **The `node:vm` module is not a security** + * **mechanism. Do not use it to run untrusted code.** + * + * JavaScript code can be compiled and run immediately or + * compiled, saved, and run later. + * + * A common use case is to run the code in a different V8 Context. This means + * invoked code has a different global object than the invoking code. + * + * One can provide the context by `contextifying` an + * object. The invoked code treats any property in the context like a + * global variable. Any changes to global variables caused by the invoked + * code are reflected in the context object. + * + * ```js + * import vm from 'node:vm'; + * + * const x = 1; + * + * const context = { x: 2 }; + * vm.createContext(context); // Contextify the object. + * + * const code = 'x += 40; var y = 17;'; + * // `x` and `y` are global variables in the context. + * // Initially, x has the value 2 because that is the value of context.x. + * vm.runInContext(code, context); + * + * console.log(context.x); // 42 + * console.log(context.y); // 17 + * + * console.log(x); // 1; y is not defined. + * ``` + * @see [source](https://github.com/nodejs/node/blob/v25.x/lib/vm.js) + */ +declare module "node:vm" { + import { NonSharedBuffer } from "node:buffer"; + import { ImportAttributes, ImportPhase } from "node:module"; + interface Context extends NodeJS.Dict {} + interface BaseOptions { + /** + * Specifies the filename used in stack traces produced by this script. + * @default '' + */ + filename?: string | undefined; + /** + * Specifies the line number offset that is displayed in stack traces produced by this script. + * @default 0 + */ + lineOffset?: number | undefined; + /** + * Specifies the column number offset that is displayed in stack traces produced by this script. + * @default 0 + */ + columnOffset?: number | undefined; + } + type DynamicModuleLoader = ( + specifier: string, + referrer: T, + importAttributes: ImportAttributes, + phase: ImportPhase, + ) => Module | Promise; + interface ScriptOptions extends BaseOptions { + /** + * Provides an optional data with V8's code cache data for the supplied source. + */ + cachedData?: NodeJS.ArrayBufferView | undefined; + /** @deprecated in favor of `script.createCachedData()` */ + produceCachedData?: boolean | undefined; + /** + * Used to specify how the modules should be loaded during the evaluation of this script when `import()` is called. This option is + * part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see + * [Support of dynamic `import()` in compilation APIs](https://nodejs.org/docs/latest-v25.x/api/vm.html#support-of-dynamic-import-in-compilation-apis). + * @experimental + */ + importModuleDynamically?: + | DynamicModuleLoader \ No newline at end of file diff --git a/backend/node_modules/tslib/tslib.es6.js b/backend/node_modules/tslib/tslib.es6.js new file mode 100644 index 0000000..67ba5c5 --- /dev/null +++ b/backend/node_modules/tslib/tslib.es6.js @@ -0,0 +1,402 @@ +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +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. +***************************************************************************** */ +/* global Reflect, Promise, SuppressedError, Symbol, Iterator */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); +}; + +export function __extends(d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} + +export var __assign = function() { + __assign = Object.assign || function __assign(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); +} + +export function __rest(s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +} + +export function __decorate(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +} + +export function __param(paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } +} + +export function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } + else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; +}; + +export function __runInitializers(thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; +}; + +export function __propKey(x) { + return typeof x === "symbol" ? x : "".concat(x); +}; + +export function __setFunctionName(f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); +}; + +export function __metadata(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); +} + +export function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} + +export function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); + return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +} + +export var __createBinding = Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +}); + +export function __exportStar(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); +} + +export function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} + +export function __read(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; +} + +/** @deprecated */ +export function __spread() { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; +} + +/** @deprecated */ +export function __spreadArrays() { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; +} + +export function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +} + +export function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} + +export function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; + function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } + function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +} + +export function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } +} + +export function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +} + +export function __makeTemplateObject(cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; +}; + +var __setModuleDefault = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}; + +var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); +}; + +export function __importStar(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; +} + +export function __importDefault(mod) { + return (mod && mod.__esModule) ? mod : { default: mod }; +} + +export function __classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} + +export function __classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +} + +export function __classPrivateFieldIn(state, receiver) { + if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); +} + +export function __addDisposableResource(env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose, inner; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; + } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + if (async) inner = dispose; + } + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } }; + env.stack.push({ value: value, dispose: dispose, async: async }); + } + else if (async) { + env.stack.push({ async: true }); + } + return value; + +} + +var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +}; + +export function __disposeResources(env) { + function fail(e) { + env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; + env.hasError = true; + } + var r, s = 0; + function next() { + while (r = env.stack.pop()) { + try { + if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); + if (r.dispose) { + var result = r.dispose.call(r.value); + if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); + } + else s |= 1; + } + catch (e) { + fail(e); + } + } + if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); + if (env.hasError) throw env.error; + } + return next(); +} + +export function __rewriteRelativeImportExtension(path, preserveJsx) { + if (typeof path === "string" && /^\.\.?\//.test(path)) { + return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) { + return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js"); + }); + } + return path; +} + +export default { + __extends: __extends, + __assign: __assign, + __rest: __rest, + __decorate: __decorate, + __param: __param, + __esDecorate: __esDecorate, + __runInitializers: __runInitializers, + __propKey: __propKey, + __setFunctionName: __setFunctionName, + __metadata: __metadata, + __awaiter: __awaiter, + __generator: __generator, + __createBinding: __createBinding, + __exportStar: __exportStar, + __values: __values, + __read: __read, + __spread: __spread, + __spreadArrays: __spreadArrays, + __spreadArray: __spreadArray, + __await: __await, + __asyncGenerator: __asyncGenerator, + __asyncDelegator: __asyncDelegator, + __asyncValues: __asyncValues, + __makeTemplateObject: __makeTemplateObject, + __importStar: __importStar, + __importDefault: __importDefault, + __classPrivateFieldGet: __classPrivateFieldGet, + __classPrivateFieldSet: __classPrivateFieldSet, + __classPrivateFieldIn: __classPrivateFieldIn, + __addDisposableResource: __addDisposableResource, + __disposeResources: __disposeResources, + __rewriteRelativeImportExtension: __rewriteRelativeImportExtension, +}; diff --git a/backend/node_modules/tslib/tslib.es6.mjs b/backend/node_modules/tslib/tslib.es6.mjs new file mode 100644 index 0000000..c17990a --- /dev/null +++ b/backend/node_modules/tslib/tslib.es6.mjs @@ -0,0 +1,401 @@ +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +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. +***************************************************************************** */ +/* global Reflect, Promise, SuppressedError, Symbol, Iterator */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); +}; + +export function __extends(d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} + +export var __assign = function() { + __assign = Object.assign || function __assign(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); +} + +export function __rest(s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +} + +export function __decorate(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +} + +export function __param(paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } +} + +export function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } + else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; +}; + +export function __runInitializers(thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; +}; + +export function __propKey(x) { + return typeof x === "symbol" ? x : "".concat(x); +}; + +export function __setFunctionName(f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); +}; + +export function __metadata(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); +} + +export function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} + +export function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); + return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +} + +export var __createBinding = Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +}); + +export function __exportStar(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); +} + +export function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} + +export function __read(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; +} + +/** @deprecated */ +export function __spread() { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; +} + +/** @deprecated */ +export function __spreadArrays() { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; +} + +export function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +} + +export function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} + +export function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; + function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } + function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +} + +export function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } +} + +export function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +} + +export function __makeTemplateObject(cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; +}; + +var __setModuleDefault = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}; + +var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); +}; + +export function __importStar(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; +} + +export function __importDefault(mod) { + return (mod && mod.__esModule) ? mod : { default: mod }; +} + +export function __classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} + +export function __classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +} + +export function __classPrivateFieldIn(state, receiver) { + if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); +} + +export function __addDisposableResource(env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose, inner; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; + } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + if (async) inner = dispose; + } + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } }; + env.stack.push({ value: value, dispose: dispose, async: async }); + } + else if (async) { + env.stack.push({ async: true }); + } + return value; +} + +var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +}; + +export function __disposeResources(env) { + function fail(e) { + env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; + env.hasError = true; + } + var r, s = 0; + function next() { + while (r = env.stack.pop()) { + try { + if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); + if (r.dispose) { + var result = r.dispose.call(r.value); + if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); + } + else s |= 1; + } + catch (e) { + fail(e); + } + } + if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); + if (env.hasError) throw env.error; + } + return next(); +} + +export function __rewriteRelativeImportExtension(path, preserveJsx) { + if (typeof path === "string" && /^\.\.?\//.test(path)) { + return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) { + return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js"); + }); + } + return path; +} + +export default { + __extends, + __assign, + __rest, + __decorate, + __param, + __esDecorate, + __runInitializers, + __propKey, + __setFunctionName, + __metadata, + __awaiter, + __generator, + __createBinding, + __exportStar, + __values, + __read, + __spread, + __spreadArrays, + __spreadArray, + __await, + __asyncGenerator, + __asyncDelegator, + __asyncValues, + __makeTemplateObject, + __importStar, + __importDefault, + __classPrivateFieldGet, + __classPrivateFieldSet, + __classPrivateFieldIn, + __addDisposableResource, + __disposeResources, + __rewriteRelativeImportExtension, +}; diff --git a/backend/node_modules/tslib/tslib.html b/backend/node_modules/tslib/tslib.html new file mode 100644 index 0000000..44c9ba5 --- /dev/null +++ b/backend/node_modules/tslib/tslib.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/backend/node_modules/tslib/tslib.js b/backend/node_modules/tslib/tslib.js new file mode 100644 index 0000000..b6509f7 --- /dev/null +++ b/backend/node_modules/tslib/tslib.js @@ -0,0 +1,484 @@ +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +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. +***************************************************************************** */ +/* global global, define, Symbol, Reflect, Promise, SuppressedError, Iterator */ +var __extends; +var __assign; +var __rest; +var __decorate; +var __param; +var __esDecorate; +var __runInitializers; +var __propKey; +var __setFunctionName; +var __metadata; +var __awaiter; +var __generator; +var __exportStar; +var __values; +var __read; +var __spread; +var __spreadArrays; +var __spreadArray; +var __await; +var __asyncGenerator; +var __asyncDelegator; +var __asyncValues; +var __makeTemplateObject; +var __importStar; +var __importDefault; +var __classPrivateFieldGet; +var __classPrivateFieldSet; +var __classPrivateFieldIn; +var __createBinding; +var __addDisposableResource; +var __disposeResources; +var __rewriteRelativeImportExtension; +(function (factory) { + var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; + if (typeof define === "function" && define.amd) { + define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); + } + else if (typeof module === "object" && typeof module.exports === "object") { + factory(createExporter(root, createExporter(module.exports))); + } + else { + factory(createExporter(root)); + } + function createExporter(exports, previous) { + if (exports !== root) { + if (typeof Object.create === "function") { + Object.defineProperty(exports, "__esModule", { value: true }); + } + else { + exports.__esModule = true; + } + } + return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; + } +}) +(function (exporter) { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + + __extends = function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + + __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; + }; + + __rest = function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; + }; + + __decorate = function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + + __param = function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + + __esDecorate = function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } + else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; + }; + + __runInitializers = function (thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; + }; + + __propKey = function (x) { + return typeof x === "symbol" ? x : "".concat(x); + }; + + __setFunctionName = function (f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); + }; + + __metadata = function (metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); + }; + + __awaiter = function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + + __generator = function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); + return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + + __exportStar = function(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); + }; + + __createBinding = Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); + + __values = function (o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + + __read = function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + + /** @deprecated */ + __spread = function () { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; + }; + + /** @deprecated */ + __spreadArrays = function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; + }; + + __spreadArray = function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + }; + + __await = function (v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + }; + + __asyncGenerator = function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; + function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } + function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } + }; + + __asyncDelegator = function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } + }; + + __asyncValues = function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } + }; + + __makeTemplateObject = function (cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; + }; + + var __setModuleDefault = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }; + + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + + __importStar = function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; + + __importDefault = function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + + __classPrivateFieldGet = function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); + }; + + __classPrivateFieldSet = function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; + }; + + __classPrivateFieldIn = function (state, receiver) { + if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); + }; + + __addDisposableResource = function (env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose, inner; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; + } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + if (async) inner = dispose; + } + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } }; + env.stack.push({ value: value, dispose: dispose, async: async }); + } + else if (async) { + env.stack.push({ async: true }); + } + return value; + }; + + var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; + }; + + __disposeResources = function (env) { + function fail(e) { + env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; + env.hasError = true; + } + var r, s = 0; + function next() { + while (r = env.stack.pop()) { + try { + if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); + if (r.dispose) { + var result = r.dispose.call(r.value); + if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); + } + else s |= 1; + } + catch (e) { + fail(e); + } + } + if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); + if (env.hasError) throw env.error; + } + return next(); + }; + + __rewriteRelativeImportExtension = function (path, preserveJsx) { + if (typeof path === "string" && /^\.\.?\//.test(path)) { + return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) { + return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js"); + }); + } + return path; + }; + + exporter("__extends", __extends); + exporter("__assign", __assign); + exporter("__rest", __rest); + exporter("__decorate", __decorate); + exporter("__param", __param); + exporter("__esDecorate", __esDecorate); + exporter("__runInitializers", __runInitializers); + exporter("__propKey", __propKey); + exporter("__setFunctionName", __setFunctionName); + exporter("__metadata", __metadata); + exporter("__awaiter", __awaiter); + exporter("__generator", __generator); + exporter("__exportStar", __exportStar); + exporter("__createBinding", __createBinding); + exporter("__values", __values); + exporter("__read", __read); + exporter("__spread", __spread); + exporter("__spreadArrays", __spreadArrays); + exporter("__spreadArray", __spreadArray); + exporter("__await", __await); + exporter("__asyncGenerator", __asyncGenerator); + exporter("__asyncDelegator", __asyncDelegator); + exporter("__asyncValues", __asyncValues); + exporter("__makeTemplateObject", __makeTemplateObject); + exporter("__importStar", __importStar); + exporter("__importDefault", __importDefault); + exporter("__classPrivateFieldGet", __classPrivateFieldGet); + exporter("__classPrivateFieldSet", __classPrivateFieldSet); + exporter("__classPrivateFieldIn", __classPrivateFieldIn); + exporter("__addDisposableResource", __addDisposableResource); + exporter("__disposeResources", __disposeResources); + exporter("__rewriteRelativeImportExtension", __rewriteRelativeImportExtension); +}); + +0 && (module.exports = { + __extends: __extends, + __assign: __assign, + __rest: __rest, + __decorate: __decorate, + __param: __param, + __esDecorate: __esDecorate, + __runInitializers: __runInitializers, + __propKey: __propKey, + __setFunctionName: __setFunctionName, + __metadata: __metadata, + __awaiter: __awaiter, + __generator: __generator, + __exportStar: __exportStar, + __createBinding: __createBinding, + __values: __values, + __read: __read, + __spread: __spread, + __spreadArrays: __spreadArrays, + __spreadArray: __spreadArray, + __await: __await, + __asyncGenerator: __asyncGenerator, + __asyncDelegator: __asyncDelegator, + __asyncValues: __asyncValues, + __makeTemplateObject: __makeTemplateObject, + __importStar: __importStar, + __importDefault: __importDefault, + __classPrivateFieldGet: __classPrivateFieldGet, + __classPrivateFieldSet: __classPrivateFieldSet, + __classPrivateFieldIn: __classPrivateFieldIn, + __addDisposableResource: __addDisposableResource, + __disposeResources: __disposeResources, + __rewriteRelativeImportExtension: __rewriteRelativeImportExtension, +}); diff --git a/backend/node_modules/type-is/HISTORY.md b/backend/node_modules/type-is/HISTORY.md new file mode 100644 index 0000000..6812655 --- /dev/null +++ b/backend/node_modules/type-is/HISTORY.md @@ -0,0 +1,292 @@ +2.0.1 / 2025-03-27 +========== + +2.0.0 / 2024-08-31 +========== + + * Drop node <18 + * Use `content-type@^1.0.5` and `media-typer@^1.0.0` for type validation + - No behavior changes, upgrades `media-typer` + * deps: mime-types@^3.0.0 + - Add `application/toml` with extension `.toml` + - Add `application/ubjson` with extension `.ubj` + - Add `application/x-keepass2` with extension `.kdbx` + - Add deprecated iWorks mime types and extensions + - Add extension `.amr` to `audio/amr` + - Add extension `.cjs` to `application/node` + - Add extension `.dbf` to `application/vnd.dbf` + - Add extension `.m4s` to `video/iso.segment` + - Add extension `.mvt` to `application/vnd.mapbox-vector-tile` + - Add extension `.mxmf` to `audio/mobile-xmf` + - Add extension `.opus` to `audio/ogg` + - Add extension `.rar` to `application/vnd.rar` + - Add extension `.td` to `application/urc-targetdesc+xml` + - Add extension `.trig` to `application/trig` + - Add extensions from IANA for `application/*+xml` types + - Add `image/avif` with extension `.avif` + - Add `image/ktx2` with extension `.ktx2` + - Add `image/vnd.ms-dds` with extension `.dds` + - Add new upstream MIME types + - Fix extension of `application/vnd.apple.keynote` to be `.key` + - Remove ambigious extensions from IANA for `application/*+xml` types + - Update primary extension to `.es` for `application/ecmascript` + +1.6.18 / 2019-04-26 +=================== + + * Fix regression passing request object to `typeis.is` + +1.6.17 / 2019-04-25 +=================== + + * deps: mime-types@~2.1.24 + - Add Apple file extensions from IANA + - Add extension `.csl` to `application/vnd.citationstyles.style+xml` + - Add extension `.es` to `application/ecmascript` + - Add extension `.nq` to `application/n-quads` + - Add extension `.nt` to `application/n-triples` + - Add extension `.owl` to `application/rdf+xml` + - Add extensions `.siv` and `.sieve` to `application/sieve` + - Add extensions from IANA for `image/*` types + - Add extensions from IANA for `model/*` types + - Add extensions to HEIC image types + - Add new mime types + - Add `text/mdx` with extension `.mdx` + * perf: prevent internal `throw` on invalid type + +1.6.16 / 2018-02-16 +=================== + + * deps: mime-types@~2.1.18 + - Add `application/raml+yaml` with extension `.raml` + - Add `application/wasm` with extension `.wasm` + - Add `text/shex` with extension `.shex` + - Add extensions for JPEG-2000 images + - Add extensions from IANA for `message/*` types + - Add extension `.mjs` to `application/javascript` + - Add extension `.wadl` to `application/vnd.sun.wadl+xml` + - Add extension `.gz` to `application/gzip` + - Add glTF types and extensions + - Add new mime types + - Update extensions `.md` and `.markdown` to be `text/markdown` + - Update font MIME types + - Update `text/hjson` to registered `application/hjson` + +1.6.15 / 2017-03-31 +=================== + + * deps: mime-types@~2.1.15 + - Add new mime types + +1.6.14 / 2016-11-18 +=================== + + * deps: mime-types@~2.1.13 + - Add new mime types + +1.6.13 / 2016-05-18 +=================== + + * deps: mime-types@~2.1.11 + - Add new mime types + +1.6.12 / 2016-02-28 +=================== + + * deps: mime-types@~2.1.10 + - Add new mime types + - Fix extension of `application/dash+xml` + - Update primary extension for `audio/mp4` + +1.6.11 / 2016-01-29 +=================== + + * deps: mime-types@~2.1.9 + - Add new mime types + +1.6.10 / 2015-12-01 +=================== + + * deps: mime-types@~2.1.8 + - Add new mime types + +1.6.9 / 2015-09-27 +================== + + * deps: mime-types@~2.1.7 + - Add new mime types + +1.6.8 / 2015-09-04 +================== + + * deps: mime-types@~2.1.6 + - Add new mime types + +1.6.7 / 2015-08-20 +================== + + * Fix type error when given invalid type to match against + * deps: mime-types@~2.1.5 + - Add new mime types + +1.6.6 / 2015-07-31 +================== + + * deps: mime-types@~2.1.4 + - Add new mime types + +1.6.5 / 2015-07-16 +================== + + * deps: mime-types@~2.1.3 + - Add new mime types + +1.6.4 / 2015-07-01 +================== + + * deps: mime-types@~2.1.2 + - Add new mime types + * perf: enable strict mode + * perf: remove argument reassignment + +1.6.3 / 2015-06-08 +================== + + * deps: mime-types@~2.1.1 + - Add new mime types + * perf: reduce try block size + * perf: remove bitwise operations + +1.6.2 / 2015-05-10 +================== + + * deps: mime-types@~2.0.11 + - Add new mime types + +1.6.1 / 2015-03-13 +================== + + * deps: mime-types@~2.0.10 + - Add new mime types + +1.6.0 / 2015-02-12 +================== + + * fix false-positives in `hasBody` `Transfer-Encoding` check + * support wildcard for both type and subtype (`*/*`) + +1.5.7 / 2015-02-09 +================== + + * fix argument reassignment + * deps: mime-types@~2.0.9 + - Add new mime types + +1.5.6 / 2015-01-29 +================== + + * deps: mime-types@~2.0.8 + - Add new mime types + +1.5.5 / 2014-12-30 +================== + + * deps: mime-types@~2.0.7 + - Add new mime types + - Fix missing extensions + - Fix various invalid MIME type entries + - Remove example template MIME types + - deps: mime-db@~1.5.0 + +1.5.4 / 2014-12-10 +================== + + * deps: mime-types@~2.0.4 + - Add new mime types + - deps: mime-db@~1.3.0 + +1.5.3 / 2014-11-09 +================== + + * deps: mime-types@~2.0.3 + - Add new mime types + - deps: mime-db@~1.2.0 + +1.5.2 / 2014-09-28 +================== + + * deps: mime-types@~2.0.2 + - Add new mime types + - deps: mime-db@~1.1.0 + +1.5.1 / 2014-09-07 +================== + + * Support Node.js 0.6 + * deps: media-typer@0.3.0 + * deps: mime-types@~2.0.1 + - Support Node.js 0.6 + +1.5.0 / 2014-09-05 +================== + + * fix `hasbody` to be true for `content-length: 0` + +1.4.0 / 2014-09-02 +================== + + * update mime-types + +1.3.2 / 2014-06-24 +================== + + * use `~` range on mime-types + +1.3.1 / 2014-06-19 +================== + + * fix global variable leak + +1.3.0 / 2014-06-19 +================== + + * improve type parsing + + - invalid media type never matches + - media type not case-sensitive + - extra LWS does not affect results + +1.2.2 / 2014-06-19 +================== + + * fix behavior on unknown type argument + +1.2.1 / 2014-06-03 +================== + + * switch dependency from `mime` to `mime-types@1.0.0` + +1.2.0 / 2014-05-11 +================== + + * support suffix matching: + + - `+json` matches `application/vnd+json` + - `*/vnd+json` matches `application/vnd+json` + - `application/*+json` matches `application/vnd+json` + +1.1.0 / 2014-04-12 +================== + + * add non-array values support + * expose internal utilities: + + - `.is()` + - `.hasBody()` + - `.normalize()` + - `.match()` + +1.0.1 / 2014-03-30 +================== + + * add `multipart` as a shorthand diff --git a/backend/node_modules/type-is/LICENSE b/backend/node_modules/type-is/LICENSE new file mode 100644 index 0000000..386b7b6 --- /dev/null +++ b/backend/node_modules/type-is/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2014-2015 Douglas Christopher Wilson + +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. diff --git a/backend/node_modules/type-is/README.md b/backend/node_modules/type-is/README.md new file mode 100644 index 0000000..d23946e --- /dev/null +++ b/backend/node_modules/type-is/README.md @@ -0,0 +1,198 @@ +# type-is + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Infer the content-type of a request. + +## Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install type-is +``` + +## API + +```js +var http = require('http') +var typeis = require('type-is') + +http.createServer(function (req, res) { + var istext = typeis(req, ['text/*']) + res.end('you ' + (istext ? 'sent' : 'did not send') + ' me text') +}) +``` + +### typeis(request, types) + +Checks if the `request` is one of the `types`. If the request has no body, +even if there is a `Content-Type` header, then `null` is returned. If the +`Content-Type` header is invalid or does not matches any of the `types`, then +`false` is returned. Otherwise, a string of the type that matched is returned. + +The `request` argument is expected to be a Node.js HTTP request. The `types` +argument is an array of type strings. + +Each type in the `types` array can be one of the following: + +- A file extension name such as `json`. This name will be returned if matched. +- A mime type such as `application/json`. +- A mime type with a wildcard such as `*/*` or `*/json` or `application/*`. + The full mime type will be returned if matched. +- A suffix such as `+json`. This can be combined with a wildcard such as + `*/vnd+json` or `application/*+json`. The full mime type will be returned + if matched. + +Some examples to illustrate the inputs and returned value: + +```js +// req.headers.content-type = 'application/json' + +typeis(req, ['json']) // => 'json' +typeis(req, ['html', 'json']) // => 'json' +typeis(req, ['application/*']) // => 'application/json' +typeis(req, ['application/json']) // => 'application/json' + +typeis(req, ['html']) // => false +``` + +### typeis.hasBody(request) + +Returns a Boolean if the given `request` has a body, regardless of the +`Content-Type` header. + +Having a body has no relation to how large the body is (it may be 0 bytes). +This is similar to how file existence works. If a body does exist, then this +indicates that there is data to read from the Node.js request stream. + +```js +if (typeis.hasBody(req)) { + // read the body, since there is one + + req.on('data', function (chunk) { + // ... + }) +} +``` + +### typeis.is(mediaType, types) + +Checks if the `mediaType` is one of the `types`. If the `mediaType` is invalid +or does not matches any of the `types`, then `false` is returned. Otherwise, a +string of the type that matched is returned. + +The `mediaType` argument is expected to be a +[media type](https://tools.ietf.org/html/rfc6838) string. The `types` argument +is an array of type strings. + +Each type in the `types` array can be one of the following: + +- A file extension name such as `json`. This name will be returned if matched. +- A mime type such as `application/json`. +- A mime type with a wildcard such as `*/*` or `*/json` or `application/*`. + The full mime type will be returned if matched. +- A suffix such as `+json`. This can be combined with a wildcard such as + `*/vnd+json` or `application/*+json`. The full mime type will be returned + if matched. + +Some examples to illustrate the inputs and returned value: + +```js +var mediaType = 'application/json' + +typeis.is(mediaType, ['json']) // => 'json' +typeis.is(mediaType, ['html', 'json']) // => 'json' +typeis.is(mediaType, ['application/*']) // => 'application/json' +typeis.is(mediaType, ['application/json']) // => 'application/json' + +typeis.is(mediaType, ['html']) // => false +``` + +### typeis.match(expected, actual) + +Match the type string `expected` with `actual`, taking in to account wildcards. +A wildcard can only be in the type of the subtype part of a media type and only +in the `expected` value (as `actual` should be the real media type to match). A +suffix can still be included even with a wildcard subtype. If an input is +malformed, `false` will be returned. + +```js +typeis.match('text/html', 'text/html') // => true +typeis.match('*/html', 'text/html') // => true +typeis.match('text/*', 'text/html') // => true +typeis.match('*/*', 'text/html') // => true +typeis.match('*/*+json', 'application/x-custom+json') // => true +``` + +### typeis.normalize(type) + +Normalize a `type` string. This works by performing the following: + +- If the `type` is not a string, `false` is returned. +- If the string starts with `+` (so it is a `+suffix` shorthand like `+json`), + then it is expanded to contain the complete wildcard notation of `*/*+suffix`. +- If the string contains a `/`, then it is returned as the type. +- Else the string is assumed to be a file extension and the mapped media type is + returned, or `false` is there is no mapping. + +This includes two special mappings: + +- `'multipart'` -> `'multipart/*'` +- `'urlencoded'` -> `'application/x-www-form-urlencoded'` + +## Examples + +### Example body parser + +```js +var express = require('express') +var typeis = require('type-is') + +var app = express() + +app.use(function bodyParser (req, res, next) { + if (!typeis.hasBody(req)) { + return next() + } + + switch (typeis(req, ['urlencoded', 'json', 'multipart'])) { + case 'urlencoded': + // parse urlencoded body + throw new Error('implement urlencoded body parsing') + case 'json': + // parse json body + throw new Error('implement json body parsing') + case 'multipart': + // parse multipart body + throw new Error('implement multipart body parsing') + default: + // 415 error code + res.statusCode = 415 + res.end() + break + } +}) +``` + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/type-is/master?label=ci +[ci-url]: https://github.com/jshttp/type-is/actions/workflows/ci.yml +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/type-is/master +[coveralls-url]: https://coveralls.io/r/jshttp/type-is?branch=master +[node-version-image]: https://badgen.net/npm/node/type-is +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/type-is +[npm-url]: https://npmjs.org/package/type-is +[npm-version-image]: https://badgen.net/npm/v/type-is +[travis-image]: https://badgen.net/travis/jshttp/type-is/master +[travis-url]: https://travis-ci.org/jshttp/type-is diff --git a/backend/node_modules/type-is/index.js b/backend/node_modules/type-is/index.js new file mode 100644 index 0000000..e773845 --- /dev/null +++ b/backend/node_modules/type-is/index.js @@ -0,0 +1,250 @@ +/*! + * type-is + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var contentType = require('content-type') +var mime = require('mime-types') +var typer = require('media-typer') + +/** + * Module exports. + * @public + */ + +module.exports = typeofrequest +module.exports.is = typeis +module.exports.hasBody = hasbody +module.exports.normalize = normalize +module.exports.match = mimeMatch + +/** + * Compare a `value` content-type with `types`. + * Each `type` can be an extension like `html`, + * a special shortcut like `multipart` or `urlencoded`, + * or a mime type. + * + * If no types match, `false` is returned. + * Otherwise, the first `type` that matches is returned. + * + * @param {String} value + * @param {Array} types + * @public + */ + +function typeis (value, types_) { + var i + var types = types_ + + // remove parameters and normalize + var val = tryNormalizeType(value) + + // no type or invalid + if (!val) { + return false + } + + // support flattened arguments + if (types && !Array.isArray(types)) { + types = new Array(arguments.length - 1) + for (i = 0; i < types.length; i++) { + types[i] = arguments[i + 1] + } + } + + // no types, return the content type + if (!types || !types.length) { + return val + } + + var type + for (i = 0; i < types.length; i++) { + if (mimeMatch(normalize(type = types[i]), val)) { + return type[0] === '+' || type.indexOf('*') !== -1 + ? val + : type + } + } + + // no matches + return false +} + +/** + * Check if a request has a request body. + * A request with a body __must__ either have `transfer-encoding` + * or `content-length` headers set. + * http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3 + * + * @param {Object} request + * @return {Boolean} + * @public + */ + +function hasbody (req) { + return req.headers['transfer-encoding'] !== undefined || + !isNaN(req.headers['content-length']) +} + +/** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains any of the give mime `type`s. + * If there is no request body, `null` is returned. + * If there is no content type, `false` is returned. + * Otherwise, it returns the first `type` that matches. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * this.is('html'); // => 'html' + * this.is('text/html'); // => 'text/html' + * this.is('text/*', 'application/json'); // => 'text/html' + * + * // When Content-Type is application/json + * this.is('json', 'urlencoded'); // => 'json' + * this.is('application/json'); // => 'application/json' + * this.is('html', 'application/*'); // => 'application/json' + * + * this.is('html'); // => false + * + * @param {Object} req + * @param {(String|Array)} types... + * @return {(String|false|null)} + * @public + */ + +function typeofrequest (req, types_) { + // no body + if (!hasbody(req)) return null + // support flattened arguments + var types = arguments.length > 2 + ? Array.prototype.slice.call(arguments, 1) + : types_ + // request content type + var value = req.headers['content-type'] + + return typeis(value, types) +} + +/** + * Normalize a mime type. + * If it's a shorthand, expand it to a valid mime type. + * + * In general, you probably want: + * + * var type = is(req, ['urlencoded', 'json', 'multipart']); + * + * Then use the appropriate body parsers. + * These three are the most common request body types + * and are thus ensured to work. + * + * @param {String} type + * @return {String|false|null} + * @public + */ + +function normalize (type) { + if (typeof type !== 'string') { + // invalid type + return false + } + + switch (type) { + case 'urlencoded': + return 'application/x-www-form-urlencoded' + case 'multipart': + return 'multipart/*' + } + + if (type[0] === '+') { + // "+json" -> "*/*+json" expando + return '*/*' + type + } + + return type.indexOf('/') === -1 + ? mime.lookup(type) + : type +} + +/** + * Check if `expected` mime type + * matches `actual` mime type with + * wildcard and +suffix support. + * + * @param {String} expected + * @param {String} actual + * @return {Boolean} + * @public + */ + +function mimeMatch (expected, actual) { + // invalid type + if (expected === false) { + return false + } + + // split types + var actualParts = actual.split('/') + var expectedParts = expected.split('/') + + // invalid format + if (actualParts.length !== 2 || expectedParts.length !== 2) { + return false + } + + // validate type + if (expectedParts[0] !== '*' && expectedParts[0] !== actualParts[0]) { + return false + } + + // validate suffix wildcard + if (expectedParts[1].slice(0, 2) === '*+') { + return expectedParts[1].length <= actualParts[1].length + 1 && + expectedParts[1].slice(1) === actualParts[1].slice(1 - expectedParts[1].length) + } + + // validate subtype + if (expectedParts[1] !== '*' && expectedParts[1] !== actualParts[1]) { + return false + } + + return true +} + +/** + * Normalize a type and remove parameters. + * + * @param {string} value + * @return {(string|null)} + * @private + */ +function normalizeType (value) { + // Parse the type + var type = contentType.parse(value).type + + return typer.test(type) ? type : null +} + +/** + * Try to normalize a type and remove parameters. + * + * @param {string} value + * @return {(string|null)} + * @private + */ +function tryNormalizeType (value) { + try { + return value ? normalizeType(value) : null + } catch (err) { + return null + } +} diff --git a/backend/node_modules/type-is/package.json b/backend/node_modules/type-is/package.json new file mode 100644 index 0000000..08586d2 --- /dev/null +++ b/backend/node_modules/type-is/package.json @@ -0,0 +1,47 @@ +{ + "name": "type-is", + "description": "Infer the content-type of a request.", + "version": "2.0.1", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "repository": "jshttp/type-is", + "dependencies": { + "content-type": "^1.0.5", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "devDependencies": { + "eslint": "7.32.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.25.4", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "5.2.0", + "eslint-plugin-standard": "4.1.0", + "mocha": "9.2.1", + "nyc": "15.1.0" + }, + "engines": { + "node": ">= 0.6" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test:debug": "mocha --reporter spec --check-leaks --inspect --inspect-brk test/", + "test-ci": "nyc --reporter=lcovonly --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + }, + "keywords": [ + "content", + "type", + "checking" + ] +} diff --git a/backend/node_modules/undici-types/LICENSE b/backend/node_modules/undici-types/LICENSE new file mode 100644 index 0000000..e7323bb --- /dev/null +++ b/backend/node_modules/undici-types/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Matteo Collina and Undici contributors + +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. diff --git a/backend/node_modules/undici-types/README.md b/backend/node_modules/undici-types/README.md new file mode 100644 index 0000000..20a721c --- /dev/null +++ b/backend/node_modules/undici-types/README.md @@ -0,0 +1,6 @@ +# undici-types + +This package is a dual-publish of the [undici](https://www.npmjs.com/package/undici) library types. The `undici` package **still contains types**. This package is for users who _only_ need undici types (such as for `@types/node`). It is published alongside every release of `undici`, so you can always use the same version. + +- [GitHub nodejs/undici](https://github.com/nodejs/undici) +- [Undici Documentation](https://undici.nodejs.org/#/) diff --git a/backend/node_modules/undici-types/agent.d.ts b/backend/node_modules/undici-types/agent.d.ts new file mode 100644 index 0000000..4bb3512 --- /dev/null +++ b/backend/node_modules/undici-types/agent.d.ts @@ -0,0 +1,32 @@ +import { URL } from 'url' +import Pool from './pool' +import Dispatcher from './dispatcher' +import TClientStats from './client-stats' +import TPoolStats from './pool-stats' + +export default Agent + +declare class Agent extends Dispatcher { + constructor (opts?: Agent.Options) + /** `true` after `dispatcher.close()` has been called. */ + closed: boolean + /** `true` after `dispatcher.destroyed()` has been called or `dispatcher.close()` has been called and the dispatcher shutdown has completed. */ + destroyed: boolean + /** Dispatches a request. */ + dispatch (options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandler): boolean + /** Aggregate stats for a Agent by origin. */ + readonly stats: Record +} + +declare namespace Agent { + export interface Options extends Pool.Options { + /** Default: `(origin, opts) => new Pool(origin, opts)`. */ + factory?(origin: string | URL, opts: Object): Dispatcher; + + interceptors?: { Agent?: readonly Dispatcher.DispatchInterceptor[] } & Pool.Options['interceptors'] + maxOrigins?: number + } + + export interface DispatchOptions extends Dispatcher.DispatchOptions { + } +} diff --git a/backend/node_modules/undici-types/api.d.ts b/backend/node_modules/undici-types/api.d.ts new file mode 100644 index 0000000..e58d08f --- /dev/null +++ b/backend/node_modules/undici-types/api.d.ts @@ -0,0 +1,43 @@ +import { URL, UrlObject } from 'url' +import { Duplex } from 'stream' +import Dispatcher from './dispatcher' + +/** Performs an HTTP request. */ +declare function request ( + url: string | URL | UrlObject, + options?: { dispatcher?: Dispatcher } & Omit, 'origin' | 'path' | 'method'> & Partial>, +): Promise> + +/** A faster version of `request`. */ +declare function stream ( + url: string | URL | UrlObject, + options: { dispatcher?: Dispatcher } & Omit, 'origin' | 'path'>, + factory: Dispatcher.StreamFactory +): Promise> + +/** For easy use with `stream.pipeline`. */ +declare function pipeline ( + url: string | URL | UrlObject, + options: { dispatcher?: Dispatcher } & Omit, 'origin' | 'path'>, + handler: Dispatcher.PipelineHandler +): Duplex + +/** Starts two-way communications with the requested resource. */ +declare function connect ( + url: string | URL | UrlObject, + options?: { dispatcher?: Dispatcher } & Omit, 'origin' | 'path'> +): Promise> + +/** Upgrade to a different protocol. */ +declare function upgrade ( + url: string | URL | UrlObject, + options?: { dispatcher?: Dispatcher } & Omit +): Promise + +export { + request, + stream, + pipeline, + connect, + upgrade +} diff --git a/backend/node_modules/undici-types/balanced-pool.d.ts b/backend/node_modules/undici-types/balanced-pool.d.ts new file mode 100644 index 0000000..733239c --- /dev/null +++ b/backend/node_modules/undici-types/balanced-pool.d.ts @@ -0,0 +1,29 @@ +import Pool from './pool' +import Dispatcher from './dispatcher' +import { URL } from 'url' + +export default BalancedPool + +type BalancedPoolConnectOptions = Omit + +declare class BalancedPool extends Dispatcher { + constructor (url: string | string[] | URL | URL[], options?: Pool.Options) + + addUpstream (upstream: string | URL): BalancedPool + removeUpstream (upstream: string | URL): BalancedPool + upstreams: Array + + /** `true` after `pool.close()` has been called. */ + closed: boolean + /** `true` after `pool.destroyed()` has been called or `pool.close()` has been called and the pool shutdown has completed. */ + destroyed: boolean + + // Override dispatcher APIs. + override connect ( + options: BalancedPoolConnectOptions + ): Promise + override connect ( + options: BalancedPoolConnectOptions, + callback: (err: Error | null, data: Dispatcher.ConnectData) => void + ): void +} diff --git a/backend/node_modules/undici-types/cache-interceptor.d.ts b/backend/node_modules/undici-types/cache-interceptor.d.ts new file mode 100644 index 0000000..e53be60 --- /dev/null +++ b/backend/node_modules/undici-types/cache-interceptor.d.ts @@ -0,0 +1,172 @@ +import { Readable, Writable } from 'node:stream' + +export default CacheHandler + +declare namespace CacheHandler { + export type CacheMethods = 'GET' | 'HEAD' | 'OPTIONS' | 'TRACE' + + export interface CacheHandlerOptions { + store: CacheStore + + cacheByDefault?: number + + type?: CacheOptions['type'] + } + + export interface CacheOptions { + store?: CacheStore + + /** + * The methods to cache + * Note we can only cache safe methods. Unsafe methods (i.e. PUT, POST) + * invalidate the cache for a origin. + * @see https://www.rfc-editor.org/rfc/rfc9111.html#name-invalidating-stored-respons + * @see https://www.rfc-editor.org/rfc/rfc9110#section-9.2.1 + */ + methods?: CacheMethods[] + + /** + * RFC9111 allows for caching responses that we aren't explicitly told to + * cache or to not cache. + * @see https://www.rfc-editor.org/rfc/rfc9111.html#section-3-5 + * @default undefined + */ + cacheByDefault?: number + + /** + * TODO docs + * @default 'shared' + */ + type?: 'shared' | 'private' + } + + export interface CacheControlDirectives { + 'max-stale'?: number; + 'min-fresh'?: number; + 'max-age'?: number; + 's-maxage'?: number; + 'stale-while-revalidate'?: number; + 'stale-if-error'?: number; + public?: true; + private?: true | string[]; + 'no-store'?: true; + 'no-cache'?: true | string[]; + 'must-revalidate'?: true; + 'proxy-revalidate'?: true; + immutable?: true; + 'no-transform'?: true; + 'must-understand'?: true; + 'only-if-cached'?: true; + } + + export interface CacheKey { + origin: string + method: string + path: string + headers?: Record + } + + export interface CacheValue { + statusCode: number + statusMessage: string + headers: Record + vary?: Record + etag?: string + cacheControlDirectives?: CacheControlDirectives + cachedAt: number + staleAt: number + deleteAt: number + } + + export interface DeleteByUri { + origin: string + method: string + path: string + } + + type GetResult = { + statusCode: number + statusMessage: string + headers: Record + vary?: Record + etag?: string + body?: Readable | Iterable | AsyncIterable | Buffer | Iterable | AsyncIterable | string + cacheControlDirectives: CacheControlDirectives, + cachedAt: number + staleAt: number + deleteAt: number + } + + /** + * Underlying storage provider for cached responses + */ + export interface CacheStore { + get(key: CacheKey): GetResult | Promise | undefined + + createWriteStream(key: CacheKey, val: CacheValue): Writable | undefined + + delete(key: CacheKey): void | Promise + } + + export interface MemoryCacheStoreOpts { + /** + * @default Infinity + */ + maxCount?: number + + /** + * @default Infinity + */ + maxSize?: number + + /** + * @default Infinity + */ + maxEntrySize?: number + + errorCallback?: (err: Error) => void + } + + export class MemoryCacheStore implements CacheStore { + constructor (opts?: MemoryCacheStoreOpts) + + get (key: CacheKey): GetResult | Promise | undefined + + createWriteStream (key: CacheKey, value: CacheValue): Writable | undefined + + delete (key: CacheKey): void | Promise + } + + export interface SqliteCacheStoreOpts { + /** + * Location of the database + * @default ':memory:' + */ + location?: string + + /** + * @default Infinity + */ + maxCount?: number + + /** + * @default Infinity + */ + maxEntrySize?: number + } + + export class SqliteCacheStore implements CacheStore { + constructor (opts?: SqliteCacheStoreOpts) + + /** + * Closes the connection to the database + */ + close (): void + + get (key: CacheKey): GetResult | Promise | undefined + + createWriteStream (key: CacheKey, value: CacheValue): Writable | undefined + + delete (key: CacheKey): void | Promise + } +} diff --git a/backend/node_modules/undici-types/cache.d.ts b/backend/node_modules/undici-types/cache.d.ts new file mode 100644 index 0000000..4c33335 --- /dev/null +++ b/backend/node_modules/undici-types/cache.d.ts @@ -0,0 +1,36 @@ +import type { RequestInfo, Response, Request } from './fetch' + +export interface CacheStorage { + match (request: RequestInfo, options?: MultiCacheQueryOptions): Promise, + has (cacheName: string): Promise, + open (cacheName: string): Promise, + delete (cacheName: string): Promise, + keys (): Promise +} + +declare const CacheStorage: { + prototype: CacheStorage + new(): CacheStorage +} + +export interface Cache { + match (request: RequestInfo, options?: CacheQueryOptions): Promise, + matchAll (request?: RequestInfo, options?: CacheQueryOptions): Promise, + add (request: RequestInfo): Promise, + addAll (requests: RequestInfo[]): Promise, + put (request: RequestInfo, response: Response): Promise, + delete (request: RequestInfo, options?: CacheQueryOptions): Promise, + keys (request?: RequestInfo, options?: CacheQueryOptions): Promise +} + +export interface CacheQueryOptions { + ignoreSearch?: boolean, + ignoreMethod?: boolean, + ignoreVary?: boolean +} + +export interface MultiCacheQueryOptions extends CacheQueryOptions { + cacheName?: string +} + +export declare const caches: CacheStorage diff --git a/backend/node_modules/undici-types/client-stats.d.ts b/backend/node_modules/undici-types/client-stats.d.ts new file mode 100644 index 0000000..ad9bd84 --- /dev/null +++ b/backend/node_modules/undici-types/client-stats.d.ts @@ -0,0 +1,15 @@ +import Client from './client' + +export default ClientStats + +declare class ClientStats { + constructor (pool: Client) + /** If socket has open connection. */ + connected: boolean + /** Number of open socket connections in this client that do not have an active request. */ + pending: number + /** Number of currently active requests of this client. */ + running: number + /** Number of active, pending, or queued requests of this client. */ + size: number +} diff --git a/backend/node_modules/undici-types/client.d.ts b/backend/node_modules/undici-types/client.d.ts new file mode 100644 index 0000000..bd1a32c --- /dev/null +++ b/backend/node_modules/undici-types/client.d.ts @@ -0,0 +1,108 @@ +import { URL } from 'url' +import Dispatcher from './dispatcher' +import buildConnector from './connector' +import TClientStats from './client-stats' + +type ClientConnectOptions = Omit + +/** + * A basic HTTP/1.1 client, mapped on top a single TCP/TLS connection. Pipelining is disabled by default. + */ +export class Client extends Dispatcher { + constructor (url: string | URL, options?: Client.Options) + /** Property to get and set the pipelining factor. */ + pipelining: number + /** `true` after `client.close()` has been called. */ + closed: boolean + /** `true` after `client.destroyed()` has been called or `client.close()` has been called and the client shutdown has completed. */ + destroyed: boolean + /** Aggregate stats for a Client. */ + readonly stats: TClientStats + + // Override dispatcher APIs. + override connect ( + options: ClientConnectOptions + ): Promise + override connect ( + options: ClientConnectOptions, + callback: (err: Error | null, data: Dispatcher.ConnectData) => void + ): void +} + +export declare namespace Client { + export interface OptionsInterceptors { + Client: readonly Dispatcher.DispatchInterceptor[]; + } + export interface Options { + /** TODO */ + interceptors?: OptionsInterceptors; + /** The maximum length of request headers in bytes. Default: Node.js' `--max-http-header-size` or `16384` (16KiB). */ + maxHeaderSize?: number; + /** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers (Node 14 and above only). Default: `300e3` milliseconds (300s). */ + headersTimeout?: number; + /** @deprecated unsupported socketTimeout, use headersTimeout & bodyTimeout instead */ + socketTimeout?: never; + /** @deprecated unsupported requestTimeout, use headersTimeout & bodyTimeout instead */ + requestTimeout?: never; + /** TODO */ + connectTimeout?: number; + /** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Default: `300e3` milliseconds (300s). */ + bodyTimeout?: number; + /** @deprecated unsupported idleTimeout, use keepAliveTimeout instead */ + idleTimeout?: never; + /** @deprecated unsupported keepAlive, use pipelining=0 instead */ + keepAlive?: never; + /** the timeout, in milliseconds, after which a socket without active requests will time out. Monitors time between activity on a connected socket. This value may be overridden by *keep-alive* hints from the server. Default: `4e3` milliseconds (4s). */ + keepAliveTimeout?: number; + /** @deprecated unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead */ + maxKeepAliveTimeout?: never; + /** the maximum allowed `idleTimeout`, in milliseconds, when overridden by *keep-alive* hints from the server. Default: `600e3` milliseconds (10min). */ + keepAliveMaxTimeout?: number; + /** A number of milliseconds subtracted from server *keep-alive* hints when overriding `idleTimeout` to account for timing inaccuracies caused by e.g. transport latency. Default: `1e3` milliseconds (1s). */ + keepAliveTimeoutThreshold?: number; + /** TODO */ + socketPath?: string; + /** The amount of concurrent requests to be sent over the single TCP/TLS connection according to [RFC7230](https://tools.ietf.org/html/rfc7230#section-6.3.2). Default: `1`. */ + pipelining?: number; + /** @deprecated use the connect option instead */ + tls?: never; + /** If `true`, an error is thrown when the request content-length header doesn't match the length of the request body. Default: `true`. */ + strictContentLength?: boolean; + /** TODO */ + maxCachedSessions?: number; + /** TODO */ + connect?: Partial | buildConnector.connector; + /** TODO */ + maxRequestsPerClient?: number; + /** TODO */ + localAddress?: string; + /** Max response body size in bytes, -1 is disabled */ + maxResponseSize?: number; + /** Enables a family autodetection algorithm that loosely implements section 5 of RFC 8305. */ + autoSelectFamily?: boolean; + /** The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the `autoSelectFamily` option. */ + autoSelectFamilyAttemptTimeout?: number; + /** + * @description Enables support for H2 if the server has assigned bigger priority to it through ALPN negotiation. + * @default false + */ + allowH2?: boolean; + /** + * @description Dictates the maximum number of concurrent streams for a single H2 session. It can be overridden by a SETTINGS remote frame. + * @default 100 + */ + maxConcurrentStreams?: number; + } + export interface SocketInfo { + localAddress?: string + localPort?: number + remoteAddress?: string + remotePort?: number + remoteFamily?: string + timeout?: number + bytesWritten?: number + bytesRead?: number + } +} + +export default Client diff --git a/backend/node_modules/undici-types/connector.d.ts b/backend/node_modules/undici-types/connector.d.ts new file mode 100644 index 0000000..bd92433 --- /dev/null +++ b/backend/node_modules/undici-types/connector.d.ts @@ -0,0 +1,34 @@ +import { TLSSocket, ConnectionOptions } from 'tls' +import { IpcNetConnectOpts, Socket, TcpNetConnectOpts } from 'net' + +export default buildConnector +declare function buildConnector (options?: buildConnector.BuildOptions): buildConnector.connector + +declare namespace buildConnector { + export type BuildOptions = (ConnectionOptions | TcpNetConnectOpts | IpcNetConnectOpts) & { + allowH2?: boolean; + maxCachedSessions?: number | null; + socketPath?: string | null; + timeout?: number | null; + port?: number; + keepAlive?: boolean | null; + keepAliveInitialDelay?: number | null; + } + + export interface Options { + hostname: string + host?: string + protocol: string + port: string + servername?: string + localAddress?: string | null + httpSocket?: Socket + } + + export type Callback = (...args: CallbackArgs) => void + type CallbackArgs = [null, Socket | TLSSocket] | [Error, null] + + export interface connector { + (options: buildConnector.Options, callback: buildConnector.Callback): void + } +} diff --git a/backend/node_modules/undici-types/content-type.d.ts b/backend/node_modules/undici-types/content-type.d.ts new file mode 100644 index 0000000..f2a87f1 --- /dev/null +++ b/backend/node_modules/undici-types/content-type.d.ts @@ -0,0 +1,21 @@ +/// + +interface MIMEType { + type: string + subtype: string + parameters: Map + essence: string +} + +/** + * Parse a string to a {@link MIMEType} object. Returns `failure` if the string + * couldn't be parsed. + * @see https://mimesniff.spec.whatwg.org/#parse-a-mime-type + */ +export function parseMIMEType (input: string): 'failure' | MIMEType + +/** + * Convert a MIMEType object to a string. + * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type + */ +export function serializeAMimeType (mimeType: MIMEType): string diff --git a/backend/node_modules/undici-types/cookies.d.ts b/backend/node_modules/undici-types/cookies.d.ts new file mode 100644 index 0000000..f746d35 --- /dev/null +++ b/backend/node_modules/undici-types/cookies.d.ts @@ -0,0 +1,30 @@ +/// + +import type { Headers } from './fetch' + +export interface Cookie { + name: string + value: string + expires?: Date | number + maxAge?: number + domain?: string + path?: string + secure?: boolean + httpOnly?: boolean + sameSite?: 'Strict' | 'Lax' | 'None' + unparsed?: string[] +} + +export function deleteCookie ( + headers: Headers, + name: string, + attributes?: { name?: string, domain?: string } +): void + +export function getCookies (headers: Headers): Record + +export function getSetCookies (headers: Headers): Cookie[] + +export function setCookie (headers: Headers, cookie: Cookie): void + +export function parseCookie (cookie: string): Cookie | null diff --git a/backend/node_modules/undici-types/diagnostics-channel.d.ts b/backend/node_modules/undici-types/diagnostics-channel.d.ts new file mode 100644 index 0000000..4925c87 --- /dev/null +++ b/backend/node_modules/undici-types/diagnostics-channel.d.ts @@ -0,0 +1,74 @@ +import { Socket } from 'net' +import { URL } from 'url' +import buildConnector from './connector' +import Dispatcher from './dispatcher' + +declare namespace DiagnosticsChannel { + interface Request { + origin?: string | URL; + completed: boolean; + method?: Dispatcher.HttpMethod; + path: string; + headers: any; + } + interface Response { + statusCode: number; + statusText: string; + headers: Array; + } + interface ConnectParams { + host: URL['host']; + hostname: URL['hostname']; + protocol: URL['protocol']; + port: URL['port']; + servername: string | null; + } + type Connector = buildConnector.connector + export interface RequestCreateMessage { + request: Request; + } + export interface RequestBodySentMessage { + request: Request; + } + + export interface RequestBodyChunkSentMessage { + request: Request; + chunk: Uint8Array | string; + } + export interface RequestBodyChunkReceivedMessage { + request: Request; + chunk: Buffer; + } + export interface RequestHeadersMessage { + request: Request; + response: Response; + } + export interface RequestTrailersMessage { + request: Request; + trailers: Array; + } + export interface RequestErrorMessage { + request: Request; + error: Error; + } + export interface ClientSendHeadersMessage { + request: Request; + headers: string; + socket: Socket; + } + export interface ClientBeforeConnectMessage { + connectParams: ConnectParams; + connector: Connector; + } + export interface ClientConnectedMessage { + socket: Socket; + connectParams: ConnectParams; + connector: Connector; + } + export interface ClientConnectErrorMessage { + error: Error; + socket: Socket; + connectParams: ConnectParams; + connector: Connector; + } +} diff --git a/backend/node_modules/undici-types/dispatcher.d.ts b/backend/node_modules/undici-types/dispatcher.d.ts new file mode 100644 index 0000000..fffe870 --- /dev/null +++ b/backend/node_modules/undici-types/dispatcher.d.ts @@ -0,0 +1,276 @@ +import { URL } from 'url' +import { Duplex, Readable, Writable } from 'stream' +import { EventEmitter } from 'events' +import { Blob } from 'buffer' +import { IncomingHttpHeaders } from './header' +import BodyReadable from './readable' +import { FormData } from './formdata' +import Errors from './errors' +import { Autocomplete } from './utility' + +type AbortSignal = unknown + +export default Dispatcher + +export type UndiciHeaders = Record | IncomingHttpHeaders | string[] | Iterable<[string, string | string[] | undefined]> | null + +/** Dispatcher is the core API used to dispatch requests. */ +declare class Dispatcher extends EventEmitter { + /** Dispatches a request. This API is expected to evolve through semver-major versions and is less stable than the preceding higher level APIs. It is primarily intended for library developers who implement higher level APIs on top of this. */ + dispatch (options: Dispatcher.DispatchOptions, handler: Dispatcher.DispatchHandler): boolean + /** Starts two-way communications with the requested resource. */ + connect(options: Dispatcher.ConnectOptions): Promise> + connect(options: Dispatcher.ConnectOptions, callback: (err: Error | null, data: Dispatcher.ConnectData) => void): void + /** Compose a chain of dispatchers */ + compose (dispatchers: Dispatcher.DispatcherComposeInterceptor[]): Dispatcher.ComposedDispatcher + compose (...dispatchers: Dispatcher.DispatcherComposeInterceptor[]): Dispatcher.ComposedDispatcher + /** Performs an HTTP request. */ + request(options: Dispatcher.RequestOptions): Promise> + request(options: Dispatcher.RequestOptions, callback: (err: Error | null, data: Dispatcher.ResponseData) => void): void + /** For easy use with `stream.pipeline`. */ + pipeline(options: Dispatcher.PipelineOptions, handler: Dispatcher.PipelineHandler): Duplex + /** A faster version of `Dispatcher.request`. */ + stream(options: Dispatcher.RequestOptions, factory: Dispatcher.StreamFactory): Promise> + stream(options: Dispatcher.RequestOptions, factory: Dispatcher.StreamFactory, callback: (err: Error | null, data: Dispatcher.StreamData) => void): void + /** Upgrade to a different protocol. */ + upgrade (options: Dispatcher.UpgradeOptions): Promise + upgrade (options: Dispatcher.UpgradeOptions, callback: (err: Error | null, data: Dispatcher.UpgradeData) => void): void + /** Closes the client and gracefully waits for enqueued requests to complete before invoking the callback (or returning a promise if no callback is provided). */ + close (): Promise + close (callback: () => void): void + /** Destroy the client abruptly with the given err. All the pending and running requests will be asynchronously aborted and error. Waits until socket is closed before invoking the callback (or returning a promise if no callback is provided). Since this operation is asynchronously dispatched there might still be some progress on dispatched requests. */ + destroy (): Promise + destroy (err: Error | null): Promise + destroy (callback: () => void): void + destroy (err: Error | null, callback: () => void): void + + on (eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this + on (eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + on (eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + on (eventName: 'drain', callback: (origin: URL) => void): this + + once (eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this + once (eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + once (eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + once (eventName: 'drain', callback: (origin: URL) => void): this + + off (eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this + off (eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + off (eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + off (eventName: 'drain', callback: (origin: URL) => void): this + + addListener (eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this + addListener (eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + addListener (eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + addListener (eventName: 'drain', callback: (origin: URL) => void): this + + removeListener (eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this + removeListener (eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + removeListener (eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + removeListener (eventName: 'drain', callback: (origin: URL) => void): this + + prependListener (eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this + prependListener (eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + prependListener (eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + prependListener (eventName: 'drain', callback: (origin: URL) => void): this + + prependOnceListener (eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this + prependOnceListener (eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + prependOnceListener (eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + prependOnceListener (eventName: 'drain', callback: (origin: URL) => void): this + + listeners (eventName: 'connect'): ((origin: URL, targets: readonly Dispatcher[]) => void)[] + listeners (eventName: 'disconnect'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[] + listeners (eventName: 'connectionError'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[] + listeners (eventName: 'drain'): ((origin: URL) => void)[] + + rawListeners (eventName: 'connect'): ((origin: URL, targets: readonly Dispatcher[]) => void)[] + rawListeners (eventName: 'disconnect'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[] + rawListeners (eventName: 'connectionError'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[] + rawListeners (eventName: 'drain'): ((origin: URL) => void)[] + + emit (eventName: 'connect', origin: URL, targets: readonly Dispatcher[]): boolean + emit (eventName: 'disconnect', origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError): boolean + emit (eventName: 'connectionError', origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError): boolean + emit (eventName: 'drain', origin: URL): boolean +} + +declare namespace Dispatcher { + export interface ComposedDispatcher extends Dispatcher {} + export type Dispatch = Dispatcher['dispatch'] + export type DispatcherComposeInterceptor = (dispatch: Dispatch) => Dispatch + export interface DispatchOptions { + origin?: string | URL; + path: string; + method: HttpMethod; + /** Default: `null` */ + body?: string | Buffer | Uint8Array | Readable | null | FormData; + /** Default: `null` */ + headers?: UndiciHeaders; + /** Query string params to be embedded in the request URL. Default: `null` */ + query?: Record; + /** Whether the requests can be safely retried or not. If `false` the request won't be sent until all preceding requests in the pipeline have completed. Default: `true` if `method` is `HEAD` or `GET`. */ + idempotent?: boolean; + /** Whether the response is expected to take a long time and would end up blocking the pipeline. When this is set to `true` further pipelining will be avoided on the same connection until headers have been received. Defaults to `method !== 'HEAD'`. */ + blocking?: boolean; + /** Upgrade the request. Should be used to specify the kind of upgrade i.e. `'Websocket'`. Default: `method === 'CONNECT' || null`. */ + upgrade?: boolean | string | null; + /** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers. Defaults to 300 seconds. */ + headersTimeout?: number | null; + /** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use 0 to disable it entirely. Defaults to 300 seconds. */ + bodyTimeout?: number | null; + /** Whether the request should stablish a keep-alive or not. Default `false` */ + reset?: boolean; + /** Whether Undici should throw an error upon receiving a 4xx or 5xx response from the server. Defaults to false */ + throwOnError?: boolean; + /** For H2, it appends the expect: 100-continue header, and halts the request body until a 100-continue is received from the remote server */ + expectContinue?: boolean; + } + export interface ConnectOptions { + origin: string | URL; + path: string; + /** Default: `null` */ + headers?: UndiciHeaders; + /** Default: `null` */ + signal?: AbortSignal | EventEmitter | null; + /** This argument parameter is passed through to `ConnectData` */ + opaque?: TOpaque; + /** Default: false */ + redirectionLimitReached?: boolean; + /** Default: `null` */ + responseHeaders?: 'raw' | null; + } + export interface RequestOptions extends DispatchOptions { + /** Default: `null` */ + opaque?: TOpaque; + /** Default: `null` */ + signal?: AbortSignal | EventEmitter | null; + /** Default: false */ + redirectionLimitReached?: boolean; + /** Default: `null` */ + onInfo?: (info: { statusCode: number, headers: Record }) => void; + /** Default: `null` */ + responseHeaders?: 'raw' | null; + /** Default: `64 KiB` */ + highWaterMark?: number; + } + export interface PipelineOptions extends RequestOptions { + /** `true` if the `handler` will return an object stream. Default: `false` */ + objectMode?: boolean; + } + export interface UpgradeOptions { + path: string; + /** Default: `'GET'` */ + method?: string; + /** Default: `null` */ + headers?: UndiciHeaders; + /** A string of comma separated protocols, in descending preference order. Default: `'Websocket'` */ + protocol?: string; + /** Default: `null` */ + signal?: AbortSignal | EventEmitter | null; + /** Default: false */ + redirectionLimitReached?: boolean; + /** Default: `null` */ + responseHeaders?: 'raw' | null; + } + export interface ConnectData { + statusCode: number; + headers: IncomingHttpHeaders; + socket: Duplex; + opaque: TOpaque; + } + export interface ResponseData { + statusCode: number; + headers: IncomingHttpHeaders; + body: BodyReadable & BodyMixin; + trailers: Record; + opaque: TOpaque; + context: object; + } + export interface PipelineHandlerData { + statusCode: number; + headers: IncomingHttpHeaders; + opaque: TOpaque; + body: BodyReadable; + context: object; + } + export interface StreamData { + opaque: TOpaque; + trailers: Record; + } + export interface UpgradeData { + headers: IncomingHttpHeaders; + socket: Duplex; + opaque: TOpaque; + } + export interface StreamFactoryData { + statusCode: number; + headers: IncomingHttpHeaders; + opaque: TOpaque; + context: object; + } + export type StreamFactory = (data: StreamFactoryData) => Writable + + export interface DispatchController { + get aborted () : boolean + get paused () : boolean + get reason () : Error | null + abort (reason: Error): void + pause(): void + resume(): void + } + + export interface DispatchHandler { + onRequestStart?(controller: DispatchController, context: any): void; + onRequestUpgrade?(controller: DispatchController, statusCode: number, headers: IncomingHttpHeaders, socket: Duplex): void; + onResponseStart?(controller: DispatchController, statusCode: number, headers: IncomingHttpHeaders, statusMessage?: string): void; + onResponseData?(controller: DispatchController, chunk: Buffer): void; + onResponseEnd?(controller: DispatchController, trailers: IncomingHttpHeaders): void; + onResponseError?(controller: DispatchController, error: Error): void; + + /** Invoked before request is dispatched on socket. May be invoked multiple times when a request is retried when the request at the head of the pipeline fails. */ + /** @deprecated */ + onConnect?(abort: (err?: Error) => void): void; + /** Invoked when an error has occurred. */ + /** @deprecated */ + onError?(err: Error): void; + /** Invoked when request is upgraded either due to a `Upgrade` header or `CONNECT` method. */ + /** @deprecated */ + onUpgrade?(statusCode: number, headers: Buffer[] | string[] | null, socket: Duplex): void; + /** Invoked when response is received, before headers have been read. **/ + /** @deprecated */ + onResponseStarted?(): void; + /** Invoked when statusCode and headers have been received. May be invoked multiple times due to 1xx informational headers. */ + /** @deprecated */ + onHeaders?(statusCode: number, headers: Buffer[], resume: () => void, statusText: string): boolean; + /** Invoked when response payload data is received. */ + /** @deprecated */ + onData?(chunk: Buffer): boolean; + /** Invoked when response payload and trailers have been received and the request has completed. */ + /** @deprecated */ + onComplete?(trailers: string[] | null): void; + /** Invoked when a body chunk is sent to the server. May be invoked multiple times for chunked requests */ + /** @deprecated */ + onBodySent?(chunkSize: number, totalBytesSent: number): void; + } + export type PipelineHandler = (data: PipelineHandlerData) => Readable + export type HttpMethod = Autocomplete<'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'CONNECT' | 'OPTIONS' | 'TRACE' | 'PATCH'> + + /** + * @link https://fetch.spec.whatwg.org/#body-mixin + */ + interface BodyMixin { + readonly body?: never; + readonly bodyUsed: boolean; + arrayBuffer(): Promise; + blob(): Promise; + bytes(): Promise; + formData(): Promise; + json(): Promise; + text(): Promise; + } + + export interface DispatchInterceptor { + (dispatch: Dispatch): Dispatch + } +} diff --git a/backend/node_modules/undici-types/env-http-proxy-agent.d.ts b/backend/node_modules/undici-types/env-http-proxy-agent.d.ts new file mode 100644 index 0000000..1733d7f --- /dev/null +++ b/backend/node_modules/undici-types/env-http-proxy-agent.d.ts @@ -0,0 +1,22 @@ +import Agent from './agent' +import ProxyAgent from './proxy-agent' +import Dispatcher from './dispatcher' + +export default EnvHttpProxyAgent + +declare class EnvHttpProxyAgent extends Dispatcher { + constructor (opts?: EnvHttpProxyAgent.Options) + + dispatch (options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandler): boolean +} + +declare namespace EnvHttpProxyAgent { + export interface Options extends Omit { + /** Overrides the value of the HTTP_PROXY environment variable */ + httpProxy?: string; + /** Overrides the value of the HTTPS_PROXY environment variable */ + httpsProxy?: string; + /** Overrides the value of the NO_PROXY environment variable */ + noProxy?: string; + } +} diff --git a/backend/node_modules/undici-types/errors.d.ts b/backend/node_modules/undici-types/errors.d.ts new file mode 100644 index 0000000..fbf3195 --- /dev/null +++ b/backend/node_modules/undici-types/errors.d.ts @@ -0,0 +1,161 @@ +import { IncomingHttpHeaders } from './header' +import Client from './client' + +export default Errors + +declare namespace Errors { + export class UndiciError extends Error { + name: string + code: string + } + + /** Connect timeout error. */ + export class ConnectTimeoutError extends UndiciError { + name: 'ConnectTimeoutError' + code: 'UND_ERR_CONNECT_TIMEOUT' + } + + /** A header exceeds the `headersTimeout` option. */ + export class HeadersTimeoutError extends UndiciError { + name: 'HeadersTimeoutError' + code: 'UND_ERR_HEADERS_TIMEOUT' + } + + /** Headers overflow error. */ + export class HeadersOverflowError extends UndiciError { + name: 'HeadersOverflowError' + code: 'UND_ERR_HEADERS_OVERFLOW' + } + + /** A body exceeds the `bodyTimeout` option. */ + export class BodyTimeoutError extends UndiciError { + name: 'BodyTimeoutError' + code: 'UND_ERR_BODY_TIMEOUT' + } + + export class ResponseError extends UndiciError { + constructor ( + message: string, + code: number, + options: { + headers?: IncomingHttpHeaders | string[] | null, + body?: null | Record | string + } + ) + name: 'ResponseError' + code: 'UND_ERR_RESPONSE' + statusCode: number + body: null | Record | string + headers: IncomingHttpHeaders | string[] | null + } + + /** Passed an invalid argument. */ + export class InvalidArgumentError extends UndiciError { + name: 'InvalidArgumentError' + code: 'UND_ERR_INVALID_ARG' + } + + /** Returned an invalid value. */ + export class InvalidReturnValueError extends UndiciError { + name: 'InvalidReturnValueError' + code: 'UND_ERR_INVALID_RETURN_VALUE' + } + + /** The request has been aborted by the user. */ + export class RequestAbortedError extends UndiciError { + name: 'AbortError' + code: 'UND_ERR_ABORTED' + } + + /** Expected error with reason. */ + export class InformationalError extends UndiciError { + name: 'InformationalError' + code: 'UND_ERR_INFO' + } + + /** Request body length does not match content-length header. */ + export class RequestContentLengthMismatchError extends UndiciError { + name: 'RequestContentLengthMismatchError' + code: 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH' + } + + /** Response body length does not match content-length header. */ + export class ResponseContentLengthMismatchError extends UndiciError { + name: 'ResponseContentLengthMismatchError' + code: 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH' + } + + /** Trying to use a destroyed client. */ + export class ClientDestroyedError extends UndiciError { + name: 'ClientDestroyedError' + code: 'UND_ERR_DESTROYED' + } + + /** Trying to use a closed client. */ + export class ClientClosedError extends UndiciError { + name: 'ClientClosedError' + code: 'UND_ERR_CLOSED' + } + + /** There is an error with the socket. */ + export class SocketError extends UndiciError { + name: 'SocketError' + code: 'UND_ERR_SOCKET' + socket: Client.SocketInfo | null + } + + /** Encountered unsupported functionality. */ + export class NotSupportedError extends UndiciError { + name: 'NotSupportedError' + code: 'UND_ERR_NOT_SUPPORTED' + } + + /** No upstream has been added to the BalancedPool. */ + export class BalancedPoolMissingUpstreamError extends UndiciError { + name: 'MissingUpstreamError' + code: 'UND_ERR_BPL_MISSING_UPSTREAM' + } + + export class HTTPParserError extends UndiciError { + name: 'HTTPParserError' + code: string + } + + /** The response exceed the length allowed. */ + export class ResponseExceededMaxSizeError extends UndiciError { + name: 'ResponseExceededMaxSizeError' + code: 'UND_ERR_RES_EXCEEDED_MAX_SIZE' + } + + export class RequestRetryError extends UndiciError { + constructor ( + message: string, + statusCode: number, + headers?: IncomingHttpHeaders | string[] | null, + body?: null | Record | string + ) + name: 'RequestRetryError' + code: 'UND_ERR_REQ_RETRY' + statusCode: number + data: { + count: number; + } + + headers: Record + } + + export class SecureProxyConnectionError extends UndiciError { + constructor ( + cause?: Error, + message?: string, + options?: Record + ) + name: 'SecureProxyConnectionError' + code: 'UND_ERR_PRX_TLS' + } + + class MaxOriginsReachedError extends UndiciError { + name: 'MaxOriginsReachedError' + code: 'UND_ERR_MAX_ORIGINS_REACHED' + } +} diff --git a/backend/node_modules/undici-types/eventsource.d.ts b/backend/node_modules/undici-types/eventsource.d.ts new file mode 100644 index 0000000..081ca09 --- /dev/null +++ b/backend/node_modules/undici-types/eventsource.d.ts @@ -0,0 +1,66 @@ +import { MessageEvent, ErrorEvent } from './websocket' +import Dispatcher from './dispatcher' + +import { + EventListenerOptions, + AddEventListenerOptions, + EventListenerOrEventListenerObject +} from './patch' + +interface EventSourceEventMap { + error: ErrorEvent + message: MessageEvent + open: Event +} + +interface EventSource extends EventTarget { + close(): void + readonly CLOSED: 2 + readonly CONNECTING: 0 + readonly OPEN: 1 + onerror: ((this: EventSource, ev: ErrorEvent) => any) | null + onmessage: ((this: EventSource, ev: MessageEvent) => any) | null + onopen: ((this: EventSource, ev: Event) => any) | null + readonly readyState: 0 | 1 | 2 + readonly url: string + readonly withCredentials: boolean + + addEventListener( + type: K, + listener: (this: EventSource, ev: EventSourceEventMap[K]) => any, + options?: boolean | AddEventListenerOptions + ): void + addEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions + ): void + removeEventListener( + type: K, + listener: (this: EventSource, ev: EventSourceEventMap[K]) => any, + options?: boolean | EventListenerOptions + ): void + removeEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | EventListenerOptions + ): void +} + +export declare const EventSource: { + prototype: EventSource + new (url: string | URL, init?: EventSourceInit): EventSource + readonly CLOSED: 2 + readonly CONNECTING: 0 + readonly OPEN: 1 +} + +interface EventSourceInit { + withCredentials?: boolean + // @deprecated use `node.dispatcher` instead + dispatcher?: Dispatcher + node?: { + dispatcher?: Dispatcher + reconnectionTime?: number + } +} diff --git a/backend/node_modules/undici-types/fetch.d.ts b/backend/node_modules/undici-types/fetch.d.ts new file mode 100644 index 0000000..2cf5029 --- /dev/null +++ b/backend/node_modules/undici-types/fetch.d.ts @@ -0,0 +1,211 @@ +// based on https://github.com/Ethan-Arrowood/undici-fetch/blob/249269714db874351589d2d364a0645d5160ae71/index.d.ts (MIT license) +// and https://github.com/node-fetch/node-fetch/blob/914ce6be5ec67a8bab63d68510aabf07cb818b6d/index.d.ts (MIT license) +/// + +import { Blob } from 'buffer' +import { URL, URLSearchParams } from 'url' +import { ReadableStream } from 'stream/web' +import { FormData } from './formdata' +import { HeaderRecord } from './header' +import Dispatcher from './dispatcher' + +export type RequestInfo = string | URL | Request + +export declare function fetch ( + input: RequestInfo, + init?: RequestInit +): Promise + +export type BodyInit = + | ArrayBuffer + | AsyncIterable + | Blob + | FormData + | Iterable + | NodeJS.ArrayBufferView + | URLSearchParams + | null + | string + +export class BodyMixin { + readonly body: ReadableStream | null + readonly bodyUsed: boolean + + readonly arrayBuffer: () => Promise + readonly blob: () => Promise + readonly bytes: () => Promise + /** + * @deprecated This method is not recommended for parsing multipart/form-data bodies in server environments. + * It is recommended to use a library such as [@fastify/busboy](https://www.npmjs.com/package/@fastify/busboy) as follows: + * + * @example + * ```js + * import { Busboy } from '@fastify/busboy' + * import { Readable } from 'node:stream' + * + * const response = await fetch('...') + * const busboy = new Busboy({ headers: { 'content-type': response.headers.get('content-type') } }) + * + * // handle events emitted from `busboy` + * + * Readable.fromWeb(response.body).pipe(busboy) + * ``` + */ + readonly formData: () => Promise + readonly json: () => Promise + readonly text: () => Promise +} + +export interface SpecIterator { + next(...args: [] | [TNext]): IteratorResult; +} + +export interface SpecIterableIterator extends SpecIterator { + [Symbol.iterator](): SpecIterableIterator; +} + +export interface SpecIterable { + [Symbol.iterator](): SpecIterator; +} + +export type HeadersInit = [string, string][] | HeaderRecord | Headers + +export declare class Headers implements SpecIterable<[string, string]> { + constructor (init?: HeadersInit) + readonly append: (name: string, value: string) => void + readonly delete: (name: string) => void + readonly get: (name: string) => string | null + readonly has: (name: string) => boolean + readonly set: (name: string, value: string) => void + readonly getSetCookie: () => string[] + readonly forEach: ( + callbackfn: (value: string, key: string, iterable: Headers) => void, + thisArg?: unknown + ) => void + + readonly keys: () => SpecIterableIterator + readonly values: () => SpecIterableIterator + readonly entries: () => SpecIterableIterator<[string, string]> + readonly [Symbol.iterator]: () => SpecIterableIterator<[string, string]> +} + +export type RequestCache = + | 'default' + | 'force-cache' + | 'no-cache' + | 'no-store' + | 'only-if-cached' + | 'reload' + +export type RequestCredentials = 'omit' | 'include' | 'same-origin' + +type RequestDestination = + | '' + | 'audio' + | 'audioworklet' + | 'document' + | 'embed' + | 'font' + | 'image' + | 'manifest' + | 'object' + | 'paintworklet' + | 'report' + | 'script' + | 'sharedworker' + | 'style' + | 'track' + | 'video' + | 'worker' + | 'xslt' + +export interface RequestInit { + body?: BodyInit | null + cache?: RequestCache + credentials?: RequestCredentials + dispatcher?: Dispatcher + duplex?: RequestDuplex + headers?: HeadersInit + integrity?: string + keepalive?: boolean + method?: string + mode?: RequestMode + redirect?: RequestRedirect + referrer?: string + referrerPolicy?: ReferrerPolicy + signal?: AbortSignal | null + window?: null +} + +export type ReferrerPolicy = + | '' + | 'no-referrer' + | 'no-referrer-when-downgrade' + | 'origin' + | 'origin-when-cross-origin' + | 'same-origin' + | 'strict-origin' + | 'strict-origin-when-cross-origin' + | 'unsafe-url' + +export type RequestMode = 'cors' | 'navigate' | 'no-cors' | 'same-origin' + +export type RequestRedirect = 'error' | 'follow' | 'manual' + +export type RequestDuplex = 'half' + +export declare class Request extends BodyMixin { + constructor (input: RequestInfo, init?: RequestInit) + + readonly cache: RequestCache + readonly credentials: RequestCredentials + readonly destination: RequestDestination + readonly headers: Headers + readonly integrity: string + readonly method: string + readonly mode: RequestMode + readonly redirect: RequestRedirect + readonly referrer: string + readonly referrerPolicy: ReferrerPolicy + readonly url: string + + readonly keepalive: boolean + readonly signal: AbortSignal + readonly duplex: RequestDuplex + + readonly clone: () => Request +} + +export interface ResponseInit { + readonly status?: number + readonly statusText?: string + readonly headers?: HeadersInit +} + +export type ResponseType = + | 'basic' + | 'cors' + | 'default' + | 'error' + | 'opaque' + | 'opaqueredirect' + +export type ResponseRedirectStatus = 301 | 302 | 303 | 307 | 308 + +export declare class Response extends BodyMixin { + constructor (body?: BodyInit, init?: ResponseInit) + + readonly headers: Headers + readonly ok: boolean + readonly status: number + readonly statusText: string + readonly type: ResponseType + readonly url: string + readonly redirected: boolean + + readonly clone: () => Response + + static error (): Response + static json (data: any, init?: ResponseInit): Response + static redirect (url: string | URL, status: ResponseRedirectStatus): Response +} diff --git a/backend/node_modules/undici-types/formdata.d.ts b/backend/node_modules/undici-types/formdata.d.ts new file mode 100644 index 0000000..030f548 --- /dev/null +++ b/backend/node_modules/undici-types/formdata.d.ts @@ -0,0 +1,108 @@ +// Based on https://github.com/octet-stream/form-data/blob/2d0f0dc371517444ce1f22cdde13f51995d0953a/lib/FormData.ts (MIT) +/// + +import { File } from 'buffer' +import { SpecIterableIterator } from './fetch' + +/** + * A `string` or `File` that represents a single value from a set of `FormData` key-value pairs. + */ +declare type FormDataEntryValue = string | File + +/** + * Provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using fetch(). + */ +export declare class FormData { + /** + * Appends a new value onto an existing key inside a FormData object, + * or adds the key if it does not already exist. + * + * The difference between `set()` and `append()` is that if the specified key already exists, `set()` will overwrite all existing values with the new one, whereas `append()` will append the new value onto the end of the existing set of values. + * + * @param name The name of the field whose data is contained in `value`. + * @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) + or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string. + * @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename. + */ + append (name: string, value: unknown, fileName?: string): void + + /** + * Set a new value for an existing key inside FormData, + * or add the new field if it does not already exist. + * + * @param name The name of the field whose data is contained in `value`. + * @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) + or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string. + * @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename. + * + */ + set (name: string, value: unknown, fileName?: string): void + + /** + * Returns the first value associated with a given key from within a `FormData` object. + * If you expect multiple values and want all of them, use the `getAll()` method instead. + * + * @param {string} name A name of the value you want to retrieve. + * + * @returns A `FormDataEntryValue` containing the value. If the key doesn't exist, the method returns null. + */ + get (name: string): FormDataEntryValue | null + + /** + * Returns all the values associated with a given key from within a `FormData` object. + * + * @param {string} name A name of the value you want to retrieve. + * + * @returns An array of `FormDataEntryValue` whose key matches the value passed in the `name` parameter. If the key doesn't exist, the method returns an empty list. + */ + getAll (name: string): FormDataEntryValue[] + + /** + * Returns a boolean stating whether a `FormData` object contains a certain key. + * + * @param name A string representing the name of the key you want to test for. + * + * @return A boolean value. + */ + has (name: string): boolean + + /** + * Deletes a key and its value(s) from a `FormData` object. + * + * @param name The name of the key you want to delete. + */ + delete (name: string): void + + /** + * Executes given callback function for each field of the FormData instance + */ + forEach: ( + callbackfn: (value: FormDataEntryValue, key: string, iterable: FormData) => void, + thisArg?: unknown + ) => void + + /** + * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all keys contained in this `FormData` object. + * Each key is a `string`. + */ + keys: () => SpecIterableIterator + + /** + * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all values contained in this object `FormData` object. + * Each value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue). + */ + values: () => SpecIterableIterator + + /** + * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through the `FormData` key/value pairs. + * The key of each pair is a string; the value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue). + */ + entries: () => SpecIterableIterator<[string, FormDataEntryValue]> + + /** + * An alias for FormData#entries() + */ + [Symbol.iterator]: () => SpecIterableIterator<[string, FormDataEntryValue]> + + readonly [Symbol.toStringTag]: string +} diff --git a/backend/node_modules/undici-types/global-dispatcher.d.ts b/backend/node_modules/undici-types/global-dispatcher.d.ts new file mode 100644 index 0000000..2760e13 --- /dev/null +++ b/backend/node_modules/undici-types/global-dispatcher.d.ts @@ -0,0 +1,9 @@ +import Dispatcher from './dispatcher' + +declare function setGlobalDispatcher (dispatcher: DispatcherImplementation): void +declare function getGlobalDispatcher (): Dispatcher + +export { + getGlobalDispatcher, + setGlobalDispatcher +} diff --git a/backend/node_modules/undici-types/global-origin.d.ts b/backend/node_modules/undici-types/global-origin.d.ts new file mode 100644 index 0000000..265769b --- /dev/null +++ b/backend/node_modules/undici-types/global-origin.d.ts @@ -0,0 +1,7 @@ +declare function setGlobalOrigin (origin: string | URL | undefined): void +declare function getGlobalOrigin (): URL | undefined + +export { + setGlobalOrigin, + getGlobalOrigin +} diff --git a/backend/node_modules/undici-types/h2c-client.d.ts b/backend/node_modules/undici-types/h2c-client.d.ts new file mode 100644 index 0000000..e7a6808 --- /dev/null +++ b/backend/node_modules/undici-types/h2c-client.d.ts @@ -0,0 +1,73 @@ +import { URL } from 'url' +import Dispatcher from './dispatcher' +import buildConnector from './connector' + +type H2ClientOptions = Omit + +/** + * A basic H2C client, mapped on top a single TCP connection. Pipelining is disabled by default. + */ +export class H2CClient extends Dispatcher { + constructor (url: string | URL, options?: H2CClient.Options) + /** Property to get and set the pipelining factor. */ + pipelining: number + /** `true` after `client.close()` has been called. */ + closed: boolean + /** `true` after `client.destroyed()` has been called or `client.close()` has been called and the client shutdown has completed. */ + destroyed: boolean + + // Override dispatcher APIs. + override connect ( + options: H2ClientOptions + ): Promise + override connect ( + options: H2ClientOptions, + callback: (err: Error | null, data: Dispatcher.ConnectData) => void + ): void +} + +export declare namespace H2CClient { + export interface Options { + /** The maximum length of request headers in bytes. Default: Node.js' `--max-http-header-size` or `16384` (16KiB). */ + maxHeaderSize?: number; + /** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers (Node 14 and above only). Default: `300e3` milliseconds (300s). */ + headersTimeout?: number; + /** TODO */ + connectTimeout?: number; + /** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Default: `300e3` milliseconds (300s). */ + bodyTimeout?: number; + /** the timeout, in milliseconds, after which a socket without active requests will time out. Monitors time between activity on a connected socket. This value may be overridden by *keep-alive* hints from the server. Default: `4e3` milliseconds (4s). */ + keepAliveTimeout?: number; + /** the maximum allowed `idleTimeout`, in milliseconds, when overridden by *keep-alive* hints from the server. Default: `600e3` milliseconds (10min). */ + keepAliveMaxTimeout?: number; + /** A number of milliseconds subtracted from server *keep-alive* hints when overriding `idleTimeout` to account for timing inaccuracies caused by e.g. transport latency. Default: `1e3` milliseconds (1s). */ + keepAliveTimeoutThreshold?: number; + /** TODO */ + socketPath?: string; + /** The amount of concurrent requests to be sent over the single TCP/TLS connection according to [RFC7230](https://tools.ietf.org/html/rfc7230#section-6.3.2). Default: `1`. */ + pipelining?: number; + /** If `true`, an error is thrown when the request content-length header doesn't match the length of the request body. Default: `true`. */ + strictContentLength?: boolean; + /** TODO */ + maxCachedSessions?: number; + /** TODO */ + connect?: Omit, 'allowH2'> | buildConnector.connector; + /** TODO */ + maxRequestsPerClient?: number; + /** TODO */ + localAddress?: string; + /** Max response body size in bytes, -1 is disabled */ + maxResponseSize?: number; + /** Enables a family autodetection algorithm that loosely implements section 5 of RFC 8305. */ + autoSelectFamily?: boolean; + /** The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the `autoSelectFamily` option. */ + autoSelectFamilyAttemptTimeout?: number; + /** + * @description Dictates the maximum number of concurrent streams for a single H2 session. It can be overridden by a SETTINGS remote frame. + * @default 100 + */ + maxConcurrentStreams?: number + } +} + +export default H2CClient diff --git a/backend/node_modules/undici-types/handlers.d.ts b/backend/node_modules/undici-types/handlers.d.ts new file mode 100644 index 0000000..8007dbf --- /dev/null +++ b/backend/node_modules/undici-types/handlers.d.ts @@ -0,0 +1,15 @@ +import Dispatcher from './dispatcher' + +export declare class RedirectHandler implements Dispatcher.DispatchHandler { + constructor ( + dispatch: Dispatcher.Dispatch, + maxRedirections: number, + opts: Dispatcher.DispatchOptions, + handler: Dispatcher.DispatchHandler, + redirectionLimitReached: boolean + ) +} + +export declare class DecoratorHandler implements Dispatcher.DispatchHandler { + constructor (handler: Dispatcher.DispatchHandler) +} diff --git a/backend/node_modules/undici-types/header.d.ts b/backend/node_modules/undici-types/header.d.ts new file mode 100644 index 0000000..efd7b1d --- /dev/null +++ b/backend/node_modules/undici-types/header.d.ts @@ -0,0 +1,160 @@ +import { Autocomplete } from './utility' + +/** + * The header type declaration of `undici`. + */ +export type IncomingHttpHeaders = Record + +type HeaderNames = Autocomplete< + | 'Accept' + | 'Accept-CH' + | 'Accept-Charset' + | 'Accept-Encoding' + | 'Accept-Language' + | 'Accept-Patch' + | 'Accept-Post' + | 'Accept-Ranges' + | 'Access-Control-Allow-Credentials' + | 'Access-Control-Allow-Headers' + | 'Access-Control-Allow-Methods' + | 'Access-Control-Allow-Origin' + | 'Access-Control-Expose-Headers' + | 'Access-Control-Max-Age' + | 'Access-Control-Request-Headers' + | 'Access-Control-Request-Method' + | 'Age' + | 'Allow' + | 'Alt-Svc' + | 'Alt-Used' + | 'Authorization' + | 'Cache-Control' + | 'Clear-Site-Data' + | 'Connection' + | 'Content-Disposition' + | 'Content-Encoding' + | 'Content-Language' + | 'Content-Length' + | 'Content-Location' + | 'Content-Range' + | 'Content-Security-Policy' + | 'Content-Security-Policy-Report-Only' + | 'Content-Type' + | 'Cookie' + | 'Cross-Origin-Embedder-Policy' + | 'Cross-Origin-Opener-Policy' + | 'Cross-Origin-Resource-Policy' + | 'Date' + | 'Device-Memory' + | 'ETag' + | 'Expect' + | 'Expect-CT' + | 'Expires' + | 'Forwarded' + | 'From' + | 'Host' + | 'If-Match' + | 'If-Modified-Since' + | 'If-None-Match' + | 'If-Range' + | 'If-Unmodified-Since' + | 'Keep-Alive' + | 'Last-Modified' + | 'Link' + | 'Location' + | 'Max-Forwards' + | 'Origin' + | 'Permissions-Policy' + | 'Priority' + | 'Proxy-Authenticate' + | 'Proxy-Authorization' + | 'Range' + | 'Referer' + | 'Referrer-Policy' + | 'Retry-After' + | 'Sec-Fetch-Dest' + | 'Sec-Fetch-Mode' + | 'Sec-Fetch-Site' + | 'Sec-Fetch-User' + | 'Sec-Purpose' + | 'Sec-WebSocket-Accept' + | 'Server' + | 'Server-Timing' + | 'Service-Worker-Navigation-Preload' + | 'Set-Cookie' + | 'SourceMap' + | 'Strict-Transport-Security' + | 'TE' + | 'Timing-Allow-Origin' + | 'Trailer' + | 'Transfer-Encoding' + | 'Upgrade' + | 'Upgrade-Insecure-Requests' + | 'User-Agent' + | 'Vary' + | 'Via' + | 'WWW-Authenticate' + | 'X-Content-Type-Options' + | 'X-Frame-Options' +> + +type IANARegisteredMimeType = Autocomplete< + | 'audio/aac' + | 'video/x-msvideo' + | 'image/avif' + | 'video/av1' + | 'application/octet-stream' + | 'image/bmp' + | 'text/css' + | 'text/csv' + | 'application/vnd.ms-fontobject' + | 'application/epub+zip' + | 'image/gif' + | 'application/gzip' + | 'text/html' + | 'image/x-icon' + | 'text/calendar' + | 'image/jpeg' + | 'text/javascript' + | 'application/json' + | 'application/ld+json' + | 'audio/x-midi' + | 'audio/mpeg' + | 'video/mp4' + | 'video/mpeg' + | 'audio/ogg' + | 'video/ogg' + | 'application/ogg' + | 'audio/opus' + | 'font/otf' + | 'application/pdf' + | 'image/png' + | 'application/rtf' + | 'image/svg+xml' + | 'image/tiff' + | 'video/mp2t' + | 'font/ttf' + | 'text/plain' + | 'application/wasm' + | 'video/webm' + | 'audio/webm' + | 'image/webp' + | 'font/woff' + | 'font/woff2' + | 'application/xhtml+xml' + | 'application/xml' + | 'application/zip' + | 'video/3gpp' + | 'video/3gpp2' + | 'model/gltf+json' + | 'model/gltf-binary' +> + +type KnownHeaderValues = { + 'content-type': IANARegisteredMimeType +} + +export type HeaderRecord = { + [K in HeaderNames | Lowercase]?: Lowercase extends keyof KnownHeaderValues + ? KnownHeaderValues[Lowercase] + : string +} diff --git a/backend/node_modules/undici-types/index.d.ts b/backend/node_modules/undici-types/index.d.ts new file mode 100644 index 0000000..be0bc28 --- /dev/null +++ b/backend/node_modules/undici-types/index.d.ts @@ -0,0 +1,80 @@ +import Dispatcher from './dispatcher' +import { setGlobalDispatcher, getGlobalDispatcher } from './global-dispatcher' +import { setGlobalOrigin, getGlobalOrigin } from './global-origin' +import Pool from './pool' +import { RedirectHandler, DecoratorHandler } from './handlers' + +import BalancedPool from './balanced-pool' +import Client from './client' +import H2CClient from './h2c-client' +import buildConnector from './connector' +import errors from './errors' +import Agent from './agent' +import MockClient from './mock-client' +import MockPool from './mock-pool' +import MockAgent from './mock-agent' +import { SnapshotAgent } from './snapshot-agent' +import { MockCallHistory, MockCallHistoryLog } from './mock-call-history' +import mockErrors from './mock-errors' +import ProxyAgent from './proxy-agent' +import EnvHttpProxyAgent from './env-http-proxy-agent' +import RetryHandler from './retry-handler' +import RetryAgent from './retry-agent' +import { request, pipeline, stream, connect, upgrade } from './api' +import interceptors from './interceptors' + +export * from './util' +export * from './cookies' +export * from './eventsource' +export * from './fetch' +export * from './formdata' +export * from './diagnostics-channel' +export * from './websocket' +export * from './content-type' +export * from './cache' +export { Interceptable } from './mock-interceptor' + +declare function globalThisInstall (): void + +export { Dispatcher, BalancedPool, Pool, Client, buildConnector, errors, Agent, request, stream, pipeline, connect, upgrade, setGlobalDispatcher, getGlobalDispatcher, setGlobalOrigin, getGlobalOrigin, interceptors, MockClient, MockPool, MockAgent, SnapshotAgent, MockCallHistory, MockCallHistoryLog, mockErrors, ProxyAgent, EnvHttpProxyAgent, RedirectHandler, DecoratorHandler, RetryHandler, RetryAgent, H2CClient, globalThisInstall as install } +export default Undici + +declare namespace Undici { + const Dispatcher: typeof import('./dispatcher').default + const Pool: typeof import('./pool').default + const RedirectHandler: typeof import ('./handlers').RedirectHandler + const DecoratorHandler: typeof import ('./handlers').DecoratorHandler + const RetryHandler: typeof import ('./retry-handler').default + const BalancedPool: typeof import('./balanced-pool').default + const Client: typeof import('./client').default + const H2CClient: typeof import('./h2c-client').default + const buildConnector: typeof import('./connector').default + const errors: typeof import('./errors').default + const Agent: typeof import('./agent').default + const setGlobalDispatcher: typeof import('./global-dispatcher').setGlobalDispatcher + const getGlobalDispatcher: typeof import('./global-dispatcher').getGlobalDispatcher + const request: typeof import('./api').request + const stream: typeof import('./api').stream + const pipeline: typeof import('./api').pipeline + const connect: typeof import('./api').connect + const upgrade: typeof import('./api').upgrade + const MockClient: typeof import('./mock-client').default + const MockPool: typeof import('./mock-pool').default + const MockAgent: typeof import('./mock-agent').default + const SnapshotAgent: typeof import('./snapshot-agent').SnapshotAgent + const MockCallHistory: typeof import('./mock-call-history').MockCallHistory + const MockCallHistoryLog: typeof import('./mock-call-history').MockCallHistoryLog + const mockErrors: typeof import('./mock-errors').default + const fetch: typeof import('./fetch').fetch + const Headers: typeof import('./fetch').Headers + const Response: typeof import('./fetch').Response + const Request: typeof import('./fetch').Request + const FormData: typeof import('./formdata').FormData + const caches: typeof import('./cache').caches + const interceptors: typeof import('./interceptors').default + const cacheStores: { + MemoryCacheStore: typeof import('./cache-interceptor').default.MemoryCacheStore, + SqliteCacheStore: typeof import('./cache-interceptor').default.SqliteCacheStore + } + const install: typeof globalThisInstall +} diff --git a/backend/node_modules/undici-types/interceptors.d.ts b/backend/node_modules/undici-types/interceptors.d.ts new file mode 100644 index 0000000..74389db --- /dev/null +++ b/backend/node_modules/undici-types/interceptors.d.ts @@ -0,0 +1,39 @@ +import CacheHandler from './cache-interceptor' +import Dispatcher from './dispatcher' +import RetryHandler from './retry-handler' +import { LookupOptions } from 'node:dns' + +export default Interceptors + +declare namespace Interceptors { + export type DumpInterceptorOpts = { maxSize?: number } + export type RetryInterceptorOpts = RetryHandler.RetryOptions + export type RedirectInterceptorOpts = { maxRedirections?: number } + export type DecompressInterceptorOpts = { + skipErrorResponses?: boolean + skipStatusCodes?: number[] + } + + export type ResponseErrorInterceptorOpts = { throwOnError: boolean } + export type CacheInterceptorOpts = CacheHandler.CacheOptions + + // DNS interceptor + export type DNSInterceptorRecord = { address: string, ttl: number, family: 4 | 6 } + export type DNSInterceptorOriginRecords = { 4: { ips: DNSInterceptorRecord[] } | null, 6: { ips: DNSInterceptorRecord[] } | null } + export type DNSInterceptorOpts = { + maxTTL?: number + maxItems?: number + lookup?: (hostname: string, options: LookupOptions, callback: (err: NodeJS.ErrnoException | null, addresses: DNSInterceptorRecord[]) => void) => void + pick?: (origin: URL, records: DNSInterceptorOriginRecords, affinity: 4 | 6) => DNSInterceptorRecord + dualStack?: boolean + affinity?: 4 | 6 + } + + export function dump (opts?: DumpInterceptorOpts): Dispatcher.DispatcherComposeInterceptor + export function retry (opts?: RetryInterceptorOpts): Dispatcher.DispatcherComposeInterceptor + export function redirect (opts?: RedirectInterceptorOpts): Dispatcher.DispatcherComposeInterceptor + export function decompress (opts?: DecompressInterceptorOpts): Dispatcher.DispatcherComposeInterceptor + export function responseError (opts?: ResponseErrorInterceptorOpts): Dispatcher.DispatcherComposeInterceptor + export function dns (opts?: DNSInterceptorOpts): Dispatcher.DispatcherComposeInterceptor + export function cache (opts?: CacheInterceptorOpts): Dispatcher.DispatcherComposeInterceptor +} diff --git a/backend/node_modules/undici-types/mock-agent.d.ts b/backend/node_modules/undici-types/mock-agent.d.ts new file mode 100644 index 0000000..330926b --- /dev/null +++ b/backend/node_modules/undici-types/mock-agent.d.ts @@ -0,0 +1,68 @@ +import Agent from './agent' +import Dispatcher from './dispatcher' +import { Interceptable, MockInterceptor } from './mock-interceptor' +import MockDispatch = MockInterceptor.MockDispatch +import { MockCallHistory } from './mock-call-history' + +export default MockAgent + +interface PendingInterceptor extends MockDispatch { + origin: string; +} + +/** A mocked Agent class that implements the Agent API. It allows one to intercept HTTP requests made through undici and return mocked responses instead. */ +declare class MockAgent extends Dispatcher { + constructor (options?: TMockAgentOptions) + /** Creates and retrieves mock Dispatcher instances which can then be used to intercept HTTP requests. If the number of connections on the mock agent is set to 1, a MockClient instance is returned. Otherwise a MockPool instance is returned. */ + get(origin: string): TInterceptable + get(origin: RegExp): TInterceptable + get(origin: ((origin: string) => boolean)): TInterceptable + /** Dispatches a mocked request. */ + dispatch (options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandler): boolean + /** Closes the mock agent and waits for registered mock pools and clients to also close before resolving. */ + close (): Promise + /** Disables mocking in MockAgent. */ + deactivate (): void + /** Enables mocking in a MockAgent instance. When instantiated, a MockAgent is automatically activated. Therefore, this method is only effective after `MockAgent.deactivate` has been called. */ + activate (): void + /** Define host matchers so only matching requests that aren't intercepted by the mock dispatchers will be attempted. */ + enableNetConnect (): void + enableNetConnect (host: string): void + enableNetConnect (host: RegExp): void + enableNetConnect (host: ((host: string) => boolean)): void + /** Causes all requests to throw when requests are not matched in a MockAgent intercept. */ + disableNetConnect (): void + /** get call history. returns the MockAgent call history or undefined if the option is not enabled. */ + getCallHistory (): MockCallHistory | undefined + /** clear every call history. Any MockCallHistoryLog will be deleted on the MockCallHistory instance */ + clearCallHistory (): void + /** Enable call history. Any subsequence calls will then be registered. */ + enableCallHistory (): this + /** Disable call history. Any subsequence calls will then not be registered. */ + disableCallHistory (): this + pendingInterceptors (): PendingInterceptor[] + assertNoPendingInterceptors (options?: { + pendingInterceptorsFormatter?: PendingInterceptorsFormatter; + }): void +} + +interface PendingInterceptorsFormatter { + format(pendingInterceptors: readonly PendingInterceptor[]): string; +} + +declare namespace MockAgent { + /** MockAgent options. */ + export interface Options extends Agent.Options { + /** A custom agent to be encapsulated by the MockAgent. */ + agent?: Dispatcher; + + /** Ignore trailing slashes in the path */ + ignoreTrailingSlash?: boolean; + + /** Accept URLs with search parameters using non standard syntaxes. default false */ + acceptNonStandardSearchParameters?: boolean; + + /** Enable call history. you can either call MockAgent.enableCallHistory(). default false */ + enableCallHistory?: boolean + } +} diff --git a/backend/node_modules/undici-types/mock-call-history.d.ts b/backend/node_modules/undici-types/mock-call-history.d.ts new file mode 100644 index 0000000..df07fa0 --- /dev/null +++ b/backend/node_modules/undici-types/mock-call-history.d.ts @@ -0,0 +1,111 @@ +import Dispatcher from './dispatcher' + +declare namespace MockCallHistoryLog { + /** request's configuration properties */ + export type MockCallHistoryLogProperties = 'protocol' | 'host' | 'port' | 'origin' | 'path' | 'hash' | 'fullUrl' | 'method' | 'searchParams' | 'body' | 'headers' +} + +/** a log reflecting request configuration */ +declare class MockCallHistoryLog { + constructor (requestInit: Dispatcher.DispatchOptions) + /** protocol used. ie. 'https:' or 'http:' etc... */ + protocol: string + /** request's host. */ + host: string + /** request's port. */ + port: string + /** request's origin. ie. https://localhost:3000. */ + origin: string + /** path. never contains searchParams. */ + path: string + /** request's hash. */ + hash: string + /** the full url requested. */ + fullUrl: string + /** request's method. */ + method: string + /** search params. */ + searchParams: Record + /** request's body */ + body: string | null | undefined + /** request's headers */ + headers: Record | null | undefined + + /** returns an Map of property / value pair */ + toMap (): Map | null | undefined> + + /** returns a string computed with all key value pair */ + toString (): string +} + +declare namespace MockCallHistory { + export type FilterCallsOperator = 'AND' | 'OR' + + /** modify the filtering behavior */ + export interface FilterCallsOptions { + /** the operator to apply when filtering. 'OR' will adds any MockCallHistoryLog matching any criteria given. 'AND' will adds only MockCallHistoryLog matching every criteria given. (default 'OR') */ + operator?: FilterCallsOperator | Lowercase + } + /** a function to be executed for filtering MockCallHistoryLog */ + export type FilterCallsFunctionCriteria = (log: MockCallHistoryLog) => boolean + + /** parameter to filter MockCallHistoryLog */ + export type FilterCallsParameter = string | RegExp | undefined | null + + /** an object to execute multiple filtering at once */ + export interface FilterCallsObjectCriteria extends Record { + /** filter by request protocol. ie https: */ + protocol?: FilterCallsParameter; + /** filter by request host. */ + host?: FilterCallsParameter; + /** filter by request port. */ + port?: FilterCallsParameter; + /** filter by request origin. */ + origin?: FilterCallsParameter; + /** filter by request path. */ + path?: FilterCallsParameter; + /** filter by request hash. */ + hash?: FilterCallsParameter; + /** filter by request fullUrl. */ + fullUrl?: FilterCallsParameter; + /** filter by request method. */ + method?: FilterCallsParameter; + } +} + +/** a call history to track requests configuration */ +declare class MockCallHistory { + constructor (name: string) + /** returns an array of MockCallHistoryLog. */ + calls (): Array + /** returns the first MockCallHistoryLog */ + firstCall (): MockCallHistoryLog | undefined + /** returns the last MockCallHistoryLog. */ + lastCall (): MockCallHistoryLog | undefined + /** returns the nth MockCallHistoryLog. */ + nthCall (position: number): MockCallHistoryLog | undefined + /** return all MockCallHistoryLog matching any of criteria given. if an object is used with multiple properties, you can change the operator to apply during filtering on options */ + filterCalls (criteria: MockCallHistory.FilterCallsFunctionCriteria | MockCallHistory.FilterCallsObjectCriteria | RegExp, options?: MockCallHistory.FilterCallsOptions): Array + /** return all MockCallHistoryLog matching the given protocol. if a string is given, it is matched with includes */ + filterCallsByProtocol (protocol: MockCallHistory.FilterCallsParameter): Array + /** return all MockCallHistoryLog matching the given host. if a string is given, it is matched with includes */ + filterCallsByHost (host: MockCallHistory.FilterCallsParameter): Array + /** return all MockCallHistoryLog matching the given port. if a string is given, it is matched with includes */ + filterCallsByPort (port: MockCallHistory.FilterCallsParameter): Array + /** return all MockCallHistoryLog matching the given origin. if a string is given, it is matched with includes */ + filterCallsByOrigin (origin: MockCallHistory.FilterCallsParameter): Array + /** return all MockCallHistoryLog matching the given path. if a string is given, it is matched with includes */ + filterCallsByPath (path: MockCallHistory.FilterCallsParameter): Array + /** return all MockCallHistoryLog matching the given hash. if a string is given, it is matched with includes */ + filterCallsByHash (hash: MockCallHistory.FilterCallsParameter): Array + /** return all MockCallHistoryLog matching the given fullUrl. if a string is given, it is matched with includes */ + filterCallsByFullUrl (fullUrl: MockCallHistory.FilterCallsParameter): Array + /** return all MockCallHistoryLog matching the given method. if a string is given, it is matched with includes */ + filterCallsByMethod (method: MockCallHistory.FilterCallsParameter): Array + /** clear all MockCallHistoryLog on this MockCallHistory. */ + clear (): void + /** use it with for..of loop or spread operator */ + [Symbol.iterator]: () => Generator +} + +export { MockCallHistoryLog, MockCallHistory } diff --git a/backend/node_modules/undici-types/mock-client.d.ts b/backend/node_modules/undici-types/mock-client.d.ts new file mode 100644 index 0000000..702e824 --- /dev/null +++ b/backend/node_modules/undici-types/mock-client.d.ts @@ -0,0 +1,27 @@ +import Client from './client' +import Dispatcher from './dispatcher' +import MockAgent from './mock-agent' +import { MockInterceptor, Interceptable } from './mock-interceptor' + +export default MockClient + +/** MockClient extends the Client API and allows one to mock requests. */ +declare class MockClient extends Client implements Interceptable { + constructor (origin: string, options: MockClient.Options) + /** Intercepts any matching requests that use the same origin as this mock client. */ + intercept (options: MockInterceptor.Options): MockInterceptor + /** Dispatches a mocked request. */ + dispatch (options: Dispatcher.DispatchOptions, handlers: Dispatcher.DispatchHandler): boolean + /** Closes the mock client and gracefully waits for enqueued requests to complete. */ + close (): Promise + /** Clean up all the prepared mocks. */ + cleanMocks (): void +} + +declare namespace MockClient { + /** MockClient options. */ + export interface Options extends Client.Options { + /** The agent to associate this MockClient with. */ + agent: MockAgent; + } +} diff --git a/backend/node_modules/undici-types/mock-errors.d.ts b/backend/node_modules/undici-types/mock-errors.d.ts new file mode 100644 index 0000000..eefeecd --- /dev/null +++ b/backend/node_modules/undici-types/mock-errors.d.ts @@ -0,0 +1,12 @@ +import Errors from './errors' + +export default MockErrors + +declare namespace MockErrors { + /** The request does not match any registered mock dispatches. */ + export class MockNotMatchedError extends Errors.UndiciError { + constructor (message?: string) + name: 'MockNotMatchedError' + code: 'UND_MOCK_ERR_MOCK_NOT_MATCHED' + } +} diff --git a/backend/node_modules/undici-types/mock-interceptor.d.ts b/backend/node_modules/undici-types/mock-interceptor.d.ts new file mode 100644 index 0000000..a48d715 --- /dev/null +++ b/backend/node_modules/undici-types/mock-interceptor.d.ts @@ -0,0 +1,94 @@ +import { IncomingHttpHeaders } from './header' +import Dispatcher from './dispatcher' +import { BodyInit, Headers } from './fetch' + +/** The scope associated with a mock dispatch. */ +declare class MockScope { + constructor (mockDispatch: MockInterceptor.MockDispatch) + /** Delay a reply by a set amount of time in ms. */ + delay (waitInMs: number): MockScope + /** Persist the defined mock data for the associated reply. It will return the defined mock data indefinitely. */ + persist (): MockScope + /** Define a reply for a set amount of matching requests. */ + times (repeatTimes: number): MockScope +} + +/** The interceptor for a Mock. */ +declare class MockInterceptor { + constructor (options: MockInterceptor.Options, mockDispatches: MockInterceptor.MockDispatch[]) + /** Mock an undici request with the defined reply. */ + reply(replyOptionsCallback: MockInterceptor.MockReplyOptionsCallback): MockScope + reply( + statusCode: number, + data?: TData | Buffer | string | MockInterceptor.MockResponseDataHandler, + responseOptions?: MockInterceptor.MockResponseOptions + ): MockScope + /** Mock an undici request by throwing the defined reply error. */ + replyWithError(error: TError): MockScope + /** Set default reply headers on the interceptor for subsequent mocked replies. */ + defaultReplyHeaders (headers: IncomingHttpHeaders): MockInterceptor + /** Set default reply trailers on the interceptor for subsequent mocked replies. */ + defaultReplyTrailers (trailers: Record): MockInterceptor + /** Set automatically calculated content-length header on subsequent mocked replies. */ + replyContentLength (): MockInterceptor +} + +declare namespace MockInterceptor { + /** MockInterceptor options. */ + export interface Options { + /** Path to intercept on. */ + path: string | RegExp | ((path: string) => boolean); + /** Method to intercept on. Defaults to GET. */ + method?: string | RegExp | ((method: string) => boolean); + /** Body to intercept on. */ + body?: string | RegExp | ((body: string) => boolean); + /** Headers to intercept on. */ + headers?: Record boolean)> | ((headers: Record) => boolean); + /** Query params to intercept on */ + query?: Record; + } + export interface MockDispatch extends Options { + times: number | null; + persist: boolean; + consumed: boolean; + data: MockDispatchData; + } + export interface MockDispatchData extends MockResponseOptions { + error: TError | null; + statusCode?: number; + data?: TData | string; + } + export interface MockResponseOptions { + headers?: IncomingHttpHeaders; + trailers?: Record; + } + + export interface MockResponseCallbackOptions { + path: string; + method: string; + headers?: Headers | Record; + origin?: string; + body?: BodyInit | Dispatcher.DispatchOptions['body'] | null; + } + + export type MockResponseDataHandler = ( + opts: MockResponseCallbackOptions + ) => TData | Buffer | string + + export type MockReplyOptionsCallback = ( + opts: MockResponseCallbackOptions + ) => { statusCode: number, data?: TData | Buffer | string, responseOptions?: MockResponseOptions } +} + +interface Interceptable extends Dispatcher { + /** Intercepts any matching requests that use the same origin as this mock client. */ + intercept(options: MockInterceptor.Options): MockInterceptor; + /** Clean up all the prepared mocks. */ + cleanMocks (): void +} + +export { + Interceptable, + MockInterceptor, + MockScope +} diff --git a/backend/node_modules/undici-types/mock-pool.d.ts b/backend/node_modules/undici-types/mock-pool.d.ts new file mode 100644 index 0000000..f35f357 --- /dev/null +++ b/backend/node_modules/undici-types/mock-pool.d.ts @@ -0,0 +1,27 @@ +import Pool from './pool' +import MockAgent from './mock-agent' +import { Interceptable, MockInterceptor } from './mock-interceptor' +import Dispatcher from './dispatcher' + +export default MockPool + +/** MockPool extends the Pool API and allows one to mock requests. */ +declare class MockPool extends Pool implements Interceptable { + constructor (origin: string, options: MockPool.Options) + /** Intercepts any matching requests that use the same origin as this mock pool. */ + intercept (options: MockInterceptor.Options): MockInterceptor + /** Dispatches a mocked request. */ + dispatch (options: Dispatcher.DispatchOptions, handlers: Dispatcher.DispatchHandler): boolean + /** Closes the mock pool and gracefully waits for enqueued requests to complete. */ + close (): Promise + /** Clean up all the prepared mocks. */ + cleanMocks (): void +} + +declare namespace MockPool { + /** MockPool options. */ + export interface Options extends Pool.Options { + /** The agent to associate this MockPool with. */ + agent: MockAgent; + } +} diff --git a/backend/node_modules/undici-types/package.json b/backend/node_modules/undici-types/package.json new file mode 100644 index 0000000..a5e7d9d --- /dev/null +++ b/backend/node_modules/undici-types/package.json @@ -0,0 +1,55 @@ +{ + "name": "undici-types", + "version": "7.16.0", + "description": "A stand-alone types package for Undici", + "homepage": "https://undici.nodejs.org", + "bugs": { + "url": "https://github.com/nodejs/undici/issues" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/nodejs/undici.git" + }, + "license": "MIT", + "types": "index.d.ts", + "files": [ + "*.d.ts" + ], + "contributors": [ + { + "name": "Daniele Belardi", + "url": "https://github.com/dnlup", + "author": true + }, + { + "name": "Ethan Arrowood", + "url": "https://github.com/ethan-arrowood", + "author": true + }, + { + "name": "Matteo Collina", + "url": "https://github.com/mcollina", + "author": true + }, + { + "name": "Matthew Aitken", + "url": "https://github.com/KhafraDev", + "author": true + }, + { + "name": "Robert Nagy", + "url": "https://github.com/ronag", + "author": true + }, + { + "name": "Szymon Marczak", + "url": "https://github.com/szmarczak", + "author": true + }, + { + "name": "Tomas Della Vedova", + "url": "https://github.com/delvedor", + "author": true + } + ] +} \ No newline at end of file diff --git a/backend/node_modules/undici-types/patch.d.ts b/backend/node_modules/undici-types/patch.d.ts new file mode 100644 index 0000000..8f7acbb --- /dev/null +++ b/backend/node_modules/undici-types/patch.d.ts @@ -0,0 +1,29 @@ +/// + +// See https://github.com/nodejs/undici/issues/1740 + +export interface EventInit { + bubbles?: boolean + cancelable?: boolean + composed?: boolean +} + +export interface EventListenerOptions { + capture?: boolean +} + +export interface AddEventListenerOptions extends EventListenerOptions { + once?: boolean + passive?: boolean + signal?: AbortSignal +} + +export type EventListenerOrEventListenerObject = EventListener | EventListenerObject + +export interface EventListenerObject { + handleEvent (object: Event): void +} + +export interface EventListener { + (evt: Event): void +} diff --git a/backend/node_modules/undici-types/pool-stats.d.ts b/backend/node_modules/undici-types/pool-stats.d.ts new file mode 100644 index 0000000..f76a5f6 --- /dev/null +++ b/backend/node_modules/undici-types/pool-stats.d.ts @@ -0,0 +1,19 @@ +import Pool from './pool' + +export default PoolStats + +declare class PoolStats { + constructor (pool: Pool) + /** Number of open socket connections in this pool. */ + connected: number + /** Number of open socket connections in this pool that do not have an active request. */ + free: number + /** Number of pending requests across all clients in this pool. */ + pending: number + /** Number of queued requests across all clients in this pool. */ + queued: number + /** Number of currently active requests across all clients in this pool. */ + running: number + /** Number of active, pending, or queued requests across all clients in this pool. */ + size: number +} diff --git a/backend/node_modules/undici-types/pool.d.ts b/backend/node_modules/undici-types/pool.d.ts new file mode 100644 index 0000000..5198476 --- /dev/null +++ b/backend/node_modules/undici-types/pool.d.ts @@ -0,0 +1,41 @@ +import Client from './client' +import TPoolStats from './pool-stats' +import { URL } from 'url' +import Dispatcher from './dispatcher' + +export default Pool + +type PoolConnectOptions = Omit + +declare class Pool extends Dispatcher { + constructor (url: string | URL, options?: Pool.Options) + /** `true` after `pool.close()` has been called. */ + closed: boolean + /** `true` after `pool.destroyed()` has been called or `pool.close()` has been called and the pool shutdown has completed. */ + destroyed: boolean + /** Aggregate stats for a Pool. */ + readonly stats: TPoolStats + + // Override dispatcher APIs. + override connect ( + options: PoolConnectOptions + ): Promise + override connect ( + options: PoolConnectOptions, + callback: (err: Error | null, data: Dispatcher.ConnectData) => void + ): void +} + +declare namespace Pool { + export type PoolStats = TPoolStats + export interface Options extends Client.Options { + /** Default: `(origin, opts) => new Client(origin, opts)`. */ + factory?(origin: URL, opts: object): Dispatcher; + /** The max number of clients to create. `null` if no limit. Default `null`. */ + connections?: number | null; + /** The amount of time before a client is removed from the pool and closed. `null` if no time limit. Default `null` */ + clientTtl?: number | null; + + interceptors?: { Pool?: readonly Dispatcher.DispatchInterceptor[] } & Client.Options['interceptors'] + } +} diff --git a/backend/node_modules/undici-types/proxy-agent.d.ts b/backend/node_modules/undici-types/proxy-agent.d.ts new file mode 100644 index 0000000..4155542 --- /dev/null +++ b/backend/node_modules/undici-types/proxy-agent.d.ts @@ -0,0 +1,29 @@ +import Agent from './agent' +import buildConnector from './connector' +import Dispatcher from './dispatcher' +import { IncomingHttpHeaders } from './header' + +export default ProxyAgent + +declare class ProxyAgent extends Dispatcher { + constructor (options: ProxyAgent.Options | string) + + dispatch (options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandler): boolean + close (): Promise +} + +declare namespace ProxyAgent { + export interface Options extends Agent.Options { + uri: string; + /** + * @deprecated use opts.token + */ + auth?: string; + token?: string; + headers?: IncomingHttpHeaders; + requestTls?: buildConnector.BuildOptions; + proxyTls?: buildConnector.BuildOptions; + clientFactory?(origin: URL, opts: object): Dispatcher; + proxyTunnel?: boolean; + } +} diff --git a/backend/node_modules/undici-types/readable.d.ts b/backend/node_modules/undici-types/readable.d.ts new file mode 100644 index 0000000..e4f314b --- /dev/null +++ b/backend/node_modules/undici-types/readable.d.ts @@ -0,0 +1,68 @@ +import { Readable } from 'stream' +import { Blob } from 'buffer' + +export default BodyReadable + +declare class BodyReadable extends Readable { + constructor (opts: { + resume: (this: Readable, size: number) => void | null; + abort: () => void | null; + contentType?: string; + contentLength?: number; + highWaterMark?: number; + }) + + /** Consumes and returns the body as a string + * https://fetch.spec.whatwg.org/#dom-body-text + */ + text (): Promise + + /** Consumes and returns the body as a JavaScript Object + * https://fetch.spec.whatwg.org/#dom-body-json + */ + json (): Promise + + /** Consumes and returns the body as a Blob + * https://fetch.spec.whatwg.org/#dom-body-blob + */ + blob (): Promise + + /** Consumes and returns the body as an Uint8Array + * https://fetch.spec.whatwg.org/#dom-body-bytes + */ + bytes (): Promise + + /** Consumes and returns the body as an ArrayBuffer + * https://fetch.spec.whatwg.org/#dom-body-arraybuffer + */ + arrayBuffer (): Promise + + /** Not implemented + * + * https://fetch.spec.whatwg.org/#dom-body-formdata + */ + formData (): Promise + + /** Returns true if the body is not null and the body has been consumed + * + * Otherwise, returns false + * + * https://fetch.spec.whatwg.org/#dom-body-bodyused + */ + readonly bodyUsed: boolean + + /** + * If body is null, it should return null as the body + * + * If body is not null, should return the body as a ReadableStream + * + * https://fetch.spec.whatwg.org/#dom-body-body + */ + readonly body: never | undefined + + /** Dumps the response body by reading `limit` number of bytes. + * @param opts.limit Number of bytes to read (optional) - Default: 131072 + * @param opts.signal AbortSignal to cancel the operation (optional) + */ + dump (opts?: { limit: number; signal?: AbortSignal }): Promise +} diff --git a/backend/node_modules/undici-types/retry-agent.d.ts b/backend/node_modules/undici-types/retry-agent.d.ts new file mode 100644 index 0000000..82268c3 --- /dev/null +++ b/backend/node_modules/undici-types/retry-agent.d.ts @@ -0,0 +1,8 @@ +import Dispatcher from './dispatcher' +import RetryHandler from './retry-handler' + +export default RetryAgent + +declare class RetryAgent extends Dispatcher { + constructor (dispatcher: Dispatcher, options?: RetryHandler.RetryOptions) +} diff --git a/backend/node_modules/undici-types/retry-handler.d.ts b/backend/node_modules/undici-types/retry-handler.d.ts new file mode 100644 index 0000000..3bc484b --- /dev/null +++ b/backend/node_modules/undici-types/retry-handler.d.ts @@ -0,0 +1,125 @@ +import Dispatcher from './dispatcher' + +export default RetryHandler + +declare class RetryHandler implements Dispatcher.DispatchHandler { + constructor ( + options: Dispatcher.DispatchOptions & { + retryOptions?: RetryHandler.RetryOptions; + }, + retryHandlers: RetryHandler.RetryHandlers + ) +} + +declare namespace RetryHandler { + export type RetryState = { counter: number; } + + export type RetryContext = { + state: RetryState; + opts: Dispatcher.DispatchOptions & { + retryOptions?: RetryHandler.RetryOptions; + }; + } + + export type OnRetryCallback = (result?: Error | null) => void + + export type RetryCallback = ( + err: Error, + context: { + state: RetryState; + opts: Dispatcher.DispatchOptions & { + retryOptions?: RetryHandler.RetryOptions; + }; + }, + callback: OnRetryCallback + ) => void + + export interface RetryOptions { + /** + * If true, the retry handler will throw an error if the request fails, + * this will prevent the folling handlers from being called, and will destroy the socket. + * + * @type {boolean} + * @memberof RetryOptions + * @default true + */ + throwOnError?: boolean; + /** + * Callback to be invoked on every retry iteration. + * It receives the error, current state of the retry object and the options object + * passed when instantiating the retry handler. + * + * @type {RetryCallback} + * @memberof RetryOptions + */ + retry?: RetryCallback; + /** + * Maximum number of retries to allow. + * + * @type {number} + * @memberof RetryOptions + * @default 5 + */ + maxRetries?: number; + /** + * Max number of milliseconds allow between retries + * + * @type {number} + * @memberof RetryOptions + * @default 30000 + */ + maxTimeout?: number; + /** + * Initial number of milliseconds to wait before retrying for the first time. + * + * @type {number} + * @memberof RetryOptions + * @default 500 + */ + minTimeout?: number; + /** + * Factior to multiply the timeout factor between retries. + * + * @type {number} + * @memberof RetryOptions + * @default 2 + */ + timeoutFactor?: number; + /** + * It enables to automatically infer timeout between retries based on the `Retry-After` header. + * + * @type {boolean} + * @memberof RetryOptions + * @default true + */ + retryAfter?: boolean; + /** + * HTTP methods to retry. + * + * @type {Dispatcher.HttpMethod[]} + * @memberof RetryOptions + * @default ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE'], + */ + methods?: Dispatcher.HttpMethod[]; + /** + * Error codes to be retried. e.g. `ECONNRESET`, `ENOTFOUND`, `ETIMEDOUT`, `ECONNREFUSED`, etc. + * + * @type {string[]} + * @default ['ECONNRESET','ECONNREFUSED','ENOTFOUND','ENETDOWN','ENETUNREACH','EHOSTDOWN','EHOSTUNREACH','EPIPE'] + */ + errorCodes?: string[]; + /** + * HTTP status codes to be retried. + * + * @type {number[]} + * @memberof RetryOptions + * @default [500, 502, 503, 504, 429], + */ + statusCodes?: number[]; + } + + export interface RetryHandlers { + dispatch: Dispatcher['dispatch']; + handler: Dispatcher.DispatchHandler; + } +} diff --git a/backend/node_modules/undici-types/snapshot-agent.d.ts b/backend/node_modules/undici-types/snapshot-agent.d.ts new file mode 100644 index 0000000..f1d1ccd --- /dev/null +++ b/backend/node_modules/undici-types/snapshot-agent.d.ts @@ -0,0 +1,109 @@ +import MockAgent from './mock-agent' + +declare class SnapshotRecorder { + constructor (options?: SnapshotRecorder.Options) + + record (requestOpts: any, response: any): Promise + findSnapshot (requestOpts: any): SnapshotRecorder.Snapshot | undefined + loadSnapshots (filePath?: string): Promise + saveSnapshots (filePath?: string): Promise + clear (): void + getSnapshots (): SnapshotRecorder.Snapshot[] + size (): number + resetCallCounts (): void + deleteSnapshot (requestOpts: any): boolean + getSnapshotInfo (requestOpts: any): SnapshotRecorder.SnapshotInfo | null + replaceSnapshots (snapshotData: SnapshotRecorder.SnapshotData[]): void + destroy (): void +} + +declare namespace SnapshotRecorder { + type SnapshotRecorderMode = 'record' | 'playback' | 'update' + + export interface Options { + snapshotPath?: string + mode?: SnapshotRecorderMode + maxSnapshots?: number + autoFlush?: boolean + flushInterval?: number + matchHeaders?: string[] + ignoreHeaders?: string[] + excludeHeaders?: string[] + matchBody?: boolean + matchQuery?: boolean + caseSensitive?: boolean + shouldRecord?: (requestOpts: any) => boolean + shouldPlayback?: (requestOpts: any) => boolean + excludeUrls?: (string | RegExp)[] + } + + export interface Snapshot { + request: { + method: string + url: string + headers: Record + body?: string + } + responses: { + statusCode: number + headers: Record + body: string + trailers: Record + }[] + callCount: number + timestamp: string + } + + export interface SnapshotInfo { + hash: string + request: { + method: string + url: string + headers: Record + body?: string + } + responseCount: number + callCount: number + timestamp: string + } + + export interface SnapshotData { + hash: string + snapshot: Snapshot + } +} + +declare class SnapshotAgent extends MockAgent { + constructor (options?: SnapshotAgent.Options) + + saveSnapshots (filePath?: string): Promise + loadSnapshots (filePath?: string): Promise + getRecorder (): SnapshotRecorder + getMode (): SnapshotRecorder.SnapshotRecorderMode + clearSnapshots (): void + resetCallCounts (): void + deleteSnapshot (requestOpts: any): boolean + getSnapshotInfo (requestOpts: any): SnapshotRecorder.SnapshotInfo | null + replaceSnapshots (snapshotData: SnapshotRecorder.SnapshotData[]): void +} + +declare namespace SnapshotAgent { + export interface Options extends MockAgent.Options { + mode?: SnapshotRecorder.SnapshotRecorderMode + snapshotPath?: string + maxSnapshots?: number + autoFlush?: boolean + flushInterval?: number + matchHeaders?: string[] + ignoreHeaders?: string[] + excludeHeaders?: string[] + matchBody?: boolean + matchQuery?: boolean + caseSensitive?: boolean + shouldRecord?: (requestOpts: any) => boolean + shouldPlayback?: (requestOpts: any) => boolean + excludeUrls?: (string | RegExp)[] + } +} + +export { SnapshotAgent, SnapshotRecorder } diff --git a/backend/node_modules/undici-types/util.d.ts b/backend/node_modules/undici-types/util.d.ts new file mode 100644 index 0000000..8fc50cc --- /dev/null +++ b/backend/node_modules/undici-types/util.d.ts @@ -0,0 +1,18 @@ +export namespace util { + /** + * Retrieves a header name and returns its lowercase value. + * @param value Header name + */ + export function headerNameToString (value: string | Buffer): string + + /** + * Receives a header object and returns the parsed value. + * @param headers Header object + * @param obj Object to specify a proxy object. Used to assign parsed values. + * @returns If `obj` is specified, it is equivalent to `obj`. + */ + export function parseHeaders ( + headers: (Buffer | string | (Buffer | string)[])[], + obj?: Record + ): Record +} diff --git a/backend/node_modules/undici-types/utility.d.ts b/backend/node_modules/undici-types/utility.d.ts new file mode 100644 index 0000000..bfb3ca7 --- /dev/null +++ b/backend/node_modules/undici-types/utility.d.ts @@ -0,0 +1,7 @@ +type AutocompletePrimitiveBaseType = + T extends string ? string : + T extends number ? number : + T extends boolean ? boolean : + never + +export type Autocomplete = T | (AutocompletePrimitiveBaseType & Record) diff --git a/backend/node_modules/undici-types/webidl.d.ts b/backend/node_modules/undici-types/webidl.d.ts new file mode 100644 index 0000000..d2a8eb9 --- /dev/null +++ b/backend/node_modules/undici-types/webidl.d.ts @@ -0,0 +1,341 @@ +// These types are not exported, and are only used internally +import * as undici from './index' + +/** + * Take in an unknown value and return one that is of type T + */ +type Converter = (object: unknown) => T + +type SequenceConverter = (object: unknown, iterable?: IterableIterator) => T[] + +type RecordConverter = (object: unknown) => Record + +interface WebidlErrors { + /** + * @description Instantiate an error + */ + exception (opts: { header: string, message: string }): TypeError + /** + * @description Instantiate an error when conversion from one type to another has failed + */ + conversionFailed (opts: { + prefix: string + argument: string + types: string[] + }): TypeError + /** + * @description Throw an error when an invalid argument is provided + */ + invalidArgument (opts: { + prefix: string + value: string + type: string + }): TypeError +} + +interface WebIDLTypes { + UNDEFINED: 1, + BOOLEAN: 2, + STRING: 3, + SYMBOL: 4, + NUMBER: 5, + BIGINT: 6, + NULL: 7 + OBJECT: 8 +} + +interface WebidlUtil { + /** + * @see https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values + */ + Type (object: unknown): WebIDLTypes[keyof WebIDLTypes] + + TypeValueToString (o: unknown): + | 'Undefined' + | 'Boolean' + | 'String' + | 'Symbol' + | 'Number' + | 'BigInt' + | 'Null' + | 'Object' + + Types: WebIDLTypes + + /** + * @see https://webidl.spec.whatwg.org/#abstract-opdef-converttoint + */ + ConvertToInt ( + V: unknown, + bitLength: number, + signedness: 'signed' | 'unsigned', + flags?: number + ): number + + /** + * @see https://webidl.spec.whatwg.org/#abstract-opdef-integerpart + */ + IntegerPart (N: number): number + + /** + * Stringifies {@param V} + */ + Stringify (V: any): string + + MakeTypeAssertion (I: I): (arg: any) => arg is I + + /** + * Mark a value as uncloneable for Node.js. + * This is only effective in some newer Node.js versions. + */ + markAsUncloneable (V: any): void + + IsResizableArrayBuffer (V: ArrayBufferLike): boolean + + HasFlag (flag: number, attributes: number): boolean +} + +interface WebidlConverters { + /** + * @see https://webidl.spec.whatwg.org/#es-DOMString + */ + DOMString (V: unknown, prefix: string, argument: string, flags?: number): string + + /** + * @see https://webidl.spec.whatwg.org/#es-ByteString + */ + ByteString (V: unknown, prefix: string, argument: string): string + + /** + * @see https://webidl.spec.whatwg.org/#es-USVString + */ + USVString (V: unknown): string + + /** + * @see https://webidl.spec.whatwg.org/#es-boolean + */ + boolean (V: unknown): boolean + + /** + * @see https://webidl.spec.whatwg.org/#es-any + */ + any (V: Value): Value + + /** + * @see https://webidl.spec.whatwg.org/#es-long-long + */ + ['long long'] (V: unknown): number + + /** + * @see https://webidl.spec.whatwg.org/#es-unsigned-long-long + */ + ['unsigned long long'] (V: unknown): number + + /** + * @see https://webidl.spec.whatwg.org/#es-unsigned-long + */ + ['unsigned long'] (V: unknown): number + + /** + * @see https://webidl.spec.whatwg.org/#es-unsigned-short + */ + ['unsigned short'] (V: unknown, flags?: number): number + + /** + * @see https://webidl.spec.whatwg.org/#idl-ArrayBuffer + */ + ArrayBuffer ( + V: unknown, + prefix: string, + argument: string, + options?: { allowResizable: boolean } + ): ArrayBuffer + + /** + * @see https://webidl.spec.whatwg.org/#idl-SharedArrayBuffer + */ + SharedArrayBuffer ( + V: unknown, + prefix: string, + argument: string, + options?: { allowResizable: boolean } + ): SharedArrayBuffer + + /** + * @see https://webidl.spec.whatwg.org/#es-buffer-source-types + */ + TypedArray ( + V: unknown, + T: new () => NodeJS.TypedArray, + prefix: string, + argument: string, + flags?: number + ): NodeJS.TypedArray + + /** + * @see https://webidl.spec.whatwg.org/#es-buffer-source-types + */ + DataView ( + V: unknown, + prefix: string, + argument: string, + flags?: number + ): DataView + + /** + * @see https://webidl.spec.whatwg.org/#es-buffer-source-types + */ + ArrayBufferView ( + V: unknown, + prefix: string, + argument: string, + flags?: number + ): NodeJS.ArrayBufferView + + /** + * @see https://webidl.spec.whatwg.org/#BufferSource + */ + BufferSource ( + V: unknown, + prefix: string, + argument: string, + flags?: number + ): ArrayBuffer | NodeJS.ArrayBufferView + + /** + * @see https://webidl.spec.whatwg.org/#AllowSharedBufferSource + */ + AllowSharedBufferSource ( + V: unknown, + prefix: string, + argument: string, + flags?: number + ): ArrayBuffer | SharedArrayBuffer | NodeJS.ArrayBufferView + + ['sequence']: SequenceConverter + + ['sequence>']: SequenceConverter + + ['record']: RecordConverter + + /** + * @see https://fetch.spec.whatwg.org/#requestinfo + */ + RequestInfo (V: unknown): undici.Request | string + + /** + * @see https://fetch.spec.whatwg.org/#requestinit + */ + RequestInit (V: unknown): undici.RequestInit + + /** + * @see https://html.spec.whatwg.org/multipage/webappapis.html#eventhandlernonnull + */ + EventHandlerNonNull (V: unknown): Function | null + + WebSocketStreamWrite (V: unknown): ArrayBuffer | NodeJS.TypedArray | string + + [Key: string]: (...args: any[]) => unknown +} + +type WebidlIsFunction = (arg: any) => arg is T + +interface WebidlIs { + Request: WebidlIsFunction + Response: WebidlIsFunction + ReadableStream: WebidlIsFunction + Blob: WebidlIsFunction + URLSearchParams: WebidlIsFunction + File: WebidlIsFunction + FormData: WebidlIsFunction + URL: WebidlIsFunction + WebSocketError: WebidlIsFunction + AbortSignal: WebidlIsFunction + MessagePort: WebidlIsFunction + USVString: WebidlIsFunction + /** + * @see https://webidl.spec.whatwg.org/#BufferSource + */ + BufferSource: WebidlIsFunction +} + +export interface Webidl { + errors: WebidlErrors + util: WebidlUtil + converters: WebidlConverters + is: WebidlIs + attributes: WebIDLExtendedAttributes + + /** + * @description Performs a brand-check on {@param V} to ensure it is a + * {@param cls} object. + */ + brandCheck unknown>(V: unknown, cls: Interface): asserts V is Interface + + brandCheckMultiple unknown)[]> (list: Interfaces): (V: any) => asserts V is Interfaces[number] + + /** + * @see https://webidl.spec.whatwg.org/#es-sequence + * @description Convert a value, V, to a WebIDL sequence type. + */ + sequenceConverter (C: Converter): SequenceConverter + + illegalConstructor (): never + + /** + * @see https://webidl.spec.whatwg.org/#es-to-record + * @description Convert a value, V, to a WebIDL record type. + */ + recordConverter ( + keyConverter: Converter, + valueConverter: Converter + ): RecordConverter + + /** + * Similar to {@link Webidl.brandCheck} but allows skipping the check if third party + * interfaces are allowed. + */ + interfaceConverter (typeCheck: WebidlIsFunction, name: string): ( + V: unknown, + prefix: string, + argument: string + ) => asserts V is Interface + + // TODO(@KhafraDev): a type could likely be implemented that can infer the return type + // from the converters given? + /** + * Converts a value, V, to a WebIDL dictionary types. Allows limiting which keys are + * allowed, values allowed, optional and required keys. Auto converts the value to + * a type given a converter. + */ + dictionaryConverter (converters: { + key: string, + defaultValue?: () => unknown, + required?: boolean, + converter: (...args: unknown[]) => unknown, + allowedValues?: unknown[] + }[]): (V: unknown) => Record + + /** + * @see https://webidl.spec.whatwg.org/#idl-nullable-type + * @description allows a type, V, to be null + */ + nullableConverter ( + converter: Converter + ): (V: unknown) => ReturnType | null + + argumentLengthCheck (args: { length: number }, min: number, context: string): void +} + +interface WebIDLExtendedAttributes { + /** https://webidl.spec.whatwg.org/#Clamp */ + Clamp: number + /** https://webidl.spec.whatwg.org/#EnforceRange */ + EnforceRange: number + /** https://webidl.spec.whatwg.org/#AllowShared */ + AllowShared: number + /** https://webidl.spec.whatwg.org/#AllowResizable */ + AllowResizable: number + /** https://webidl.spec.whatwg.org/#LegacyNullToEmptyString */ + LegacyNullToEmptyString: number +} diff --git a/backend/node_modules/undici-types/websocket.d.ts b/backend/node_modules/undici-types/websocket.d.ts new file mode 100644 index 0000000..a8477c1 --- /dev/null +++ b/backend/node_modules/undici-types/websocket.d.ts @@ -0,0 +1,186 @@ +/// + +import type { Blob } from 'buffer' +import type { ReadableStream, WritableStream } from 'stream/web' +import type { MessagePort } from 'worker_threads' +import { + EventInit, + EventListenerOptions, + AddEventListenerOptions, + EventListenerOrEventListenerObject +} from './patch' +import Dispatcher from './dispatcher' +import { HeadersInit } from './fetch' + +export type BinaryType = 'blob' | 'arraybuffer' + +interface WebSocketEventMap { + close: CloseEvent + error: ErrorEvent + message: MessageEvent + open: Event +} + +interface WebSocket extends EventTarget { + binaryType: BinaryType + + readonly bufferedAmount: number + readonly extensions: string + + onclose: ((this: WebSocket, ev: WebSocketEventMap['close']) => any) | null + onerror: ((this: WebSocket, ev: WebSocketEventMap['error']) => any) | null + onmessage: ((this: WebSocket, ev: WebSocketEventMap['message']) => any) | null + onopen: ((this: WebSocket, ev: WebSocketEventMap['open']) => any) | null + + readonly protocol: string + readonly readyState: number + readonly url: string + + close(code?: number, reason?: string): void + send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void + + readonly CLOSED: number + readonly CLOSING: number + readonly CONNECTING: number + readonly OPEN: number + + addEventListener( + type: K, + listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, + options?: boolean | AddEventListenerOptions + ): void + addEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions + ): void + removeEventListener( + type: K, + listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, + options?: boolean | EventListenerOptions + ): void + removeEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | EventListenerOptions + ): void +} + +export declare const WebSocket: { + prototype: WebSocket + new (url: string | URL, protocols?: string | string[] | WebSocketInit): WebSocket + readonly CLOSED: number + readonly CLOSING: number + readonly CONNECTING: number + readonly OPEN: number +} + +interface CloseEventInit extends EventInit { + code?: number + reason?: string + wasClean?: boolean +} + +interface CloseEvent extends Event { + readonly code: number + readonly reason: string + readonly wasClean: boolean +} + +export declare const CloseEvent: { + prototype: CloseEvent + new (type: string, eventInitDict?: CloseEventInit): CloseEvent +} + +interface MessageEventInit extends EventInit { + data?: T + lastEventId?: string + origin?: string + ports?: (typeof MessagePort)[] + source?: typeof MessagePort | null +} + +interface MessageEvent extends Event { + readonly data: T + readonly lastEventId: string + readonly origin: string + readonly ports: ReadonlyArray + readonly source: typeof MessagePort | null + initMessageEvent( + type: string, + bubbles?: boolean, + cancelable?: boolean, + data?: any, + origin?: string, + lastEventId?: string, + source?: typeof MessagePort | null, + ports?: (typeof MessagePort)[] + ): void; +} + +export declare const MessageEvent: { + prototype: MessageEvent + new(type: string, eventInitDict?: MessageEventInit): MessageEvent +} + +interface ErrorEventInit extends EventInit { + message?: string + filename?: string + lineno?: number + colno?: number + error?: any +} + +interface ErrorEvent extends Event { + readonly message: string + readonly filename: string + readonly lineno: number + readonly colno: number + readonly error: Error +} + +export declare const ErrorEvent: { + prototype: ErrorEvent + new (type: string, eventInitDict?: ErrorEventInit): ErrorEvent +} + +interface WebSocketInit { + protocols?: string | string[], + dispatcher?: Dispatcher, + headers?: HeadersInit +} + +interface WebSocketStreamOptions { + protocols?: string | string[] + signal?: AbortSignal +} + +interface WebSocketCloseInfo { + closeCode: number + reason: string +} + +interface WebSocketStream { + closed: Promise + opened: Promise<{ + extensions: string + protocol: string + readable: ReadableStream + writable: WritableStream + }> + url: string +} + +export declare const WebSocketStream: { + prototype: WebSocketStream + new (url: string | URL, options?: WebSocketStreamOptions): WebSocketStream +} + +interface WebSocketError extends Event, WebSocketCloseInfo {} + +export declare const WebSocketError: { + prototype: WebSocketError + new (type: string, init?: WebSocketCloseInfo): WebSocketError +} + +export declare const ping: (ws: WebSocket, body?: Buffer) => void diff --git a/backend/node_modules/unpipe/HISTORY.md b/backend/node_modules/unpipe/HISTORY.md new file mode 100644 index 0000000..85e0f8d --- /dev/null +++ b/backend/node_modules/unpipe/HISTORY.md @@ -0,0 +1,4 @@ +1.0.0 / 2015-06-14 +================== + + * Initial release diff --git a/backend/node_modules/unpipe/LICENSE b/backend/node_modules/unpipe/LICENSE new file mode 100644 index 0000000..aed0138 --- /dev/null +++ b/backend/node_modules/unpipe/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2015 Douglas Christopher Wilson + +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. diff --git a/backend/node_modules/unpipe/README.md b/backend/node_modules/unpipe/README.md new file mode 100644 index 0000000..e536ad2 --- /dev/null +++ b/backend/node_modules/unpipe/README.md @@ -0,0 +1,43 @@ +# unpipe + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Unpipe a stream from all destinations. + +## Installation + +```sh +$ npm install unpipe +``` + +## API + +```js +var unpipe = require('unpipe') +``` + +### unpipe(stream) + +Unpipes all destinations from a given stream. With stream 2+, this is +equivalent to `stream.unpipe()`. When used with streams 1 style streams +(typically Node.js 0.8 and below), this module attempts to undo the +actions done in `stream.pipe(dest)`. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/unpipe.svg +[npm-url]: https://npmjs.org/package/unpipe +[node-image]: https://img.shields.io/node/v/unpipe.svg +[node-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/stream-utils/unpipe.svg +[travis-url]: https://travis-ci.org/stream-utils/unpipe +[coveralls-image]: https://img.shields.io/coveralls/stream-utils/unpipe.svg +[coveralls-url]: https://coveralls.io/r/stream-utils/unpipe?branch=master +[downloads-image]: https://img.shields.io/npm/dm/unpipe.svg +[downloads-url]: https://npmjs.org/package/unpipe diff --git a/backend/node_modules/unpipe/index.js b/backend/node_modules/unpipe/index.js new file mode 100644 index 0000000..15c3d97 --- /dev/null +++ b/backend/node_modules/unpipe/index.js @@ -0,0 +1,69 @@ +/*! + * unpipe + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = unpipe + +/** + * Determine if there are Node.js pipe-like data listeners. + * @private + */ + +function hasPipeDataListeners(stream) { + var listeners = stream.listeners('data') + + for (var i = 0; i < listeners.length; i++) { + if (listeners[i].name === 'ondata') { + return true + } + } + + return false +} + +/** + * Unpipe a stream from all destinations. + * + * @param {object} stream + * @public + */ + +function unpipe(stream) { + if (!stream) { + throw new TypeError('argument stream is required') + } + + if (typeof stream.unpipe === 'function') { + // new-style + stream.unpipe() + return + } + + // Node.js 0.8 hack + if (!hasPipeDataListeners(stream)) { + return + } + + var listener + var listeners = stream.listeners('close') + + for (var i = 0; i < listeners.length; i++) { + listener = listeners[i] + + if (listener.name !== 'cleanup' && listener.name !== 'onclose') { + continue + } + + // invoke the listener + listener.call(stream) + } +} diff --git a/backend/node_modules/unpipe/package.json b/backend/node_modules/unpipe/package.json new file mode 100644 index 0000000..a2b7358 --- /dev/null +++ b/backend/node_modules/unpipe/package.json @@ -0,0 +1,27 @@ +{ + "name": "unpipe", + "description": "Unpipe a stream from all destinations", + "version": "1.0.0", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "repository": "stream-utils/unpipe", + "devDependencies": { + "istanbul": "0.3.15", + "mocha": "2.2.5", + "readable-stream": "1.1.13" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + } +} diff --git a/backend/node_modules/vary/HISTORY.md b/backend/node_modules/vary/HISTORY.md new file mode 100644 index 0000000..f6cbcf7 --- /dev/null +++ b/backend/node_modules/vary/HISTORY.md @@ -0,0 +1,39 @@ +1.1.2 / 2017-09-23 +================== + + * perf: improve header token parsing speed + +1.1.1 / 2017-03-20 +================== + + * perf: hoist regular expression + +1.1.0 / 2015-09-29 +================== + + * Only accept valid field names in the `field` argument + - Ensures the resulting string is a valid HTTP header value + +1.0.1 / 2015-07-08 +================== + + * Fix setting empty header from empty `field` + * perf: enable strict mode + * perf: remove argument reassignments + +1.0.0 / 2014-08-10 +================== + + * Accept valid `Vary` header string as `field` + * Add `vary.append` for low-level string manipulation + * Move to `jshttp` orgainzation + +0.1.0 / 2014-06-05 +================== + + * Support array of fields to set + +0.0.0 / 2014-06-04 +================== + + * Initial release diff --git a/backend/node_modules/vary/LICENSE b/backend/node_modules/vary/LICENSE new file mode 100644 index 0000000..84441fb --- /dev/null +++ b/backend/node_modules/vary/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2017 Douglas Christopher Wilson + +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. diff --git a/backend/node_modules/vary/README.md b/backend/node_modules/vary/README.md new file mode 100644 index 0000000..cc000b3 --- /dev/null +++ b/backend/node_modules/vary/README.md @@ -0,0 +1,101 @@ +# vary + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Manipulate the HTTP Vary header + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install vary +``` + +## API + + + +```js +var vary = require('vary') +``` + +### vary(res, field) + +Adds the given header `field` to the `Vary` response header of `res`. +This can be a string of a single field, a string of a valid `Vary` +header, or an array of multiple fields. + +This will append the header if not already listed, otherwise leaves +it listed in the current location. + + + +```js +// Append "Origin" to the Vary header of the response +vary(res, 'Origin') +``` + +### vary.append(header, field) + +Adds the given header `field` to the `Vary` response header string `header`. +This can be a string of a single field, a string of a valid `Vary` header, +or an array of multiple fields. + +This will append the header if not already listed, otherwise leaves +it listed in the current location. The new header string is returned. + + + +```js +// Get header string appending "Origin" to "Accept, User-Agent" +vary.append('Accept, User-Agent', 'Origin') +``` + +## Examples + +### Updating the Vary header when content is based on it + +```js +var http = require('http') +var vary = require('vary') + +http.createServer(function onRequest (req, res) { + // about to user-agent sniff + vary(res, 'User-Agent') + + var ua = req.headers['user-agent'] || '' + var isMobile = /mobi|android|touch|mini/i.test(ua) + + // serve site, depending on isMobile + res.setHeader('Content-Type', 'text/html') + res.end('You are (probably) ' + (isMobile ? '' : 'not ') + 'a mobile user') +}) +``` + +## Testing + +```sh +$ npm test +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/vary.svg +[npm-url]: https://npmjs.org/package/vary +[node-version-image]: https://img.shields.io/node/v/vary.svg +[node-version-url]: https://nodejs.org/en/download +[travis-image]: https://img.shields.io/travis/jshttp/vary/master.svg +[travis-url]: https://travis-ci.org/jshttp/vary +[coveralls-image]: https://img.shields.io/coveralls/jshttp/vary/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/vary +[downloads-image]: https://img.shields.io/npm/dm/vary.svg +[downloads-url]: https://npmjs.org/package/vary diff --git a/backend/node_modules/vary/index.js b/backend/node_modules/vary/index.js new file mode 100644 index 0000000..5b5e741 --- /dev/null +++ b/backend/node_modules/vary/index.js @@ -0,0 +1,149 @@ +/*! + * vary + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + */ + +module.exports = vary +module.exports.append = append + +/** + * RegExp to match field-name in RFC 7230 sec 3.2 + * + * field-name = token + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" + * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + * / DIGIT / ALPHA + * ; any VCHAR, except delimiters + */ + +var FIELD_NAME_REGEXP = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/ + +/** + * Append a field to a vary header. + * + * @param {String} header + * @param {String|Array} field + * @return {String} + * @public + */ + +function append (header, field) { + if (typeof header !== 'string') { + throw new TypeError('header argument is required') + } + + if (!field) { + throw new TypeError('field argument is required') + } + + // get fields array + var fields = !Array.isArray(field) + ? parse(String(field)) + : field + + // assert on invalid field names + for (var j = 0; j < fields.length; j++) { + if (!FIELD_NAME_REGEXP.test(fields[j])) { + throw new TypeError('field argument contains an invalid header name') + } + } + + // existing, unspecified vary + if (header === '*') { + return header + } + + // enumerate current values + var val = header + var vals = parse(header.toLowerCase()) + + // unspecified vary + if (fields.indexOf('*') !== -1 || vals.indexOf('*') !== -1) { + return '*' + } + + for (var i = 0; i < fields.length; i++) { + var fld = fields[i].toLowerCase() + + // append value (case-preserving) + if (vals.indexOf(fld) === -1) { + vals.push(fld) + val = val + ? val + ', ' + fields[i] + : fields[i] + } + } + + return val +} + +/** + * Parse a vary header into an array. + * + * @param {String} header + * @return {Array} + * @private + */ + +function parse (header) { + var end = 0 + var list = [] + var start = 0 + + // gather tokens + for (var i = 0, len = header.length; i < len; i++) { + switch (header.charCodeAt(i)) { + case 0x20: /* */ + if (start === end) { + start = end = i + 1 + } + break + case 0x2c: /* , */ + list.push(header.substring(start, end)) + start = end = i + 1 + break + default: + end = i + 1 + break + } + } + + // final token + list.push(header.substring(start, end)) + + return list +} + +/** + * Mark that a request is varied on a header field. + * + * @param {Object} res + * @param {String|Array} field + * @public + */ + +function vary (res, field) { + if (!res || !res.getHeader || !res.setHeader) { + // quack quack + throw new TypeError('res argument is required') + } + + // get existing header + var val = res.getHeader('Vary') || '' + var header = Array.isArray(val) + ? val.join(', ') + : String(val) + + // set new header + if ((val = append(header, field))) { + res.setHeader('Vary', val) + } +} diff --git a/backend/node_modules/vary/package.json b/backend/node_modules/vary/package.json new file mode 100644 index 0000000..028f72a --- /dev/null +++ b/backend/node_modules/vary/package.json @@ -0,0 +1,43 @@ +{ + "name": "vary", + "description": "Manipulate the HTTP Vary header", + "version": "1.1.2", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "keywords": [ + "http", + "res", + "vary" + ], + "repository": "jshttp/vary", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "eslint": "3.19.0", + "eslint-config-standard": "10.2.1", + "eslint-plugin-import": "2.7.0", + "eslint-plugin-markdown": "1.0.0-beta.6", + "eslint-plugin-node": "5.1.1", + "eslint-plugin-promise": "3.5.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "2.5.3", + "supertest": "1.1.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + } +} diff --git a/backend/node_modules/wrappy/LICENSE b/backend/node_modules/wrappy/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/backend/node_modules/wrappy/LICENSE @@ -0,0 +1,15 @@ +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. diff --git a/backend/node_modules/wrappy/README.md b/backend/node_modules/wrappy/README.md new file mode 100644 index 0000000..98eab25 --- /dev/null +++ b/backend/node_modules/wrappy/README.md @@ -0,0 +1,36 @@ +# wrappy + +Callback wrapping utility + +## USAGE + +```javascript +var wrappy = require("wrappy") + +// var wrapper = wrappy(wrapperFunction) + +// make sure a cb is called only once +// See also: http://npm.im/once for this specific use case +var once = wrappy(function (cb) { + var called = false + return function () { + if (called) return + called = true + return cb.apply(this, arguments) + } +}) + +function printBoo () { + console.log('boo') +} +// has some rando property +printBoo.iAmBooPrinter = true + +var onlyPrintOnce = once(printBoo) + +onlyPrintOnce() // prints 'boo' +onlyPrintOnce() // does nothing + +// random property is retained! +assert.equal(onlyPrintOnce.iAmBooPrinter, true) +``` diff --git a/backend/node_modules/wrappy/package.json b/backend/node_modules/wrappy/package.json new file mode 100644 index 0000000..1307520 --- /dev/null +++ b/backend/node_modules/wrappy/package.json @@ -0,0 +1,29 @@ +{ + "name": "wrappy", + "version": "1.0.2", + "description": "Callback wrapping utility", + "main": "wrappy.js", + "files": [ + "wrappy.js" + ], + "directories": { + "test": "test" + }, + "dependencies": {}, + "devDependencies": { + "tap": "^2.3.1" + }, + "scripts": { + "test": "tap --coverage test/*.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/npm/wrappy" + }, + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "license": "ISC", + "bugs": { + "url": "https://github.com/npm/wrappy/issues" + }, + "homepage": "https://github.com/npm/wrappy" +} diff --git a/backend/node_modules/wrappy/wrappy.js b/backend/node_modules/wrappy/wrappy.js new file mode 100644 index 0000000..bb7e7d6 --- /dev/null +++ b/backend/node_modules/wrappy/wrappy.js @@ -0,0 +1,33 @@ +// Returns a wrapper function that returns a wrapped callback +// The wrapper function should do some stuff, and return a +// presumably different callback function. +// This makes sure that own properties are retained, so that +// decorations and such are not lost along the way. +module.exports = wrappy +function wrappy (fn, cb) { + if (fn && cb) return wrappy(fn)(cb) + + if (typeof fn !== 'function') + throw new TypeError('need wrapper function') + + Object.keys(fn).forEach(function (k) { + wrapper[k] = fn[k] + }) + + return wrapper + + function wrapper() { + var args = new Array(arguments.length) + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + var ret = fn.apply(this, args) + var cb = args[args.length-1] + if (typeof ret === 'function' && ret !== cb) { + Object.keys(cb).forEach(function (k) { + ret[k] = cb[k] + }) + } + return ret + } +} diff --git a/backend/node_modules/ws/LICENSE b/backend/node_modules/ws/LICENSE new file mode 100644 index 0000000..1da5b96 --- /dev/null +++ b/backend/node_modules/ws/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2011 Einar Otto Stangvik +Copyright (c) 2013 Arnout Kazemier and contributors +Copyright (c) 2016 Luigi Pinca and contributors + +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. diff --git a/backend/node_modules/ws/README.md b/backend/node_modules/ws/README.md new file mode 100644 index 0000000..21f10df --- /dev/null +++ b/backend/node_modules/ws/README.md @@ -0,0 +1,548 @@ +# ws: a Node.js WebSocket library + +[![Version npm](https://img.shields.io/npm/v/ws.svg?logo=npm)](https://www.npmjs.com/package/ws) +[![CI](https://img.shields.io/github/actions/workflow/status/websockets/ws/ci.yml?branch=master&label=CI&logo=github)](https://github.com/websockets/ws/actions?query=workflow%3ACI+branch%3Amaster) +[![Coverage Status](https://img.shields.io/coveralls/websockets/ws/master.svg?logo=coveralls)](https://coveralls.io/github/websockets/ws) + +ws is a simple to use, blazing fast, and thoroughly tested WebSocket client and +server implementation. + +Passes the quite extensive Autobahn test suite: [server][server-report], +[client][client-report]. + +**Note**: This module does not work in the browser. The client in the docs is a +reference to a backend with the role of a client in the WebSocket communication. +Browser clients must use the native +[`WebSocket`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) +object. To make the same code work seamlessly on Node.js and the browser, you +can use one of the many wrappers available on npm, like +[isomorphic-ws](https://github.com/heineiuo/isomorphic-ws). + +## Table of Contents + +- [Protocol support](#protocol-support) +- [Installing](#installing) + - [Opt-in for performance](#opt-in-for-performance) + - [Legacy opt-in for performance](#legacy-opt-in-for-performance) +- [API docs](#api-docs) +- [WebSocket compression](#websocket-compression) +- [Usage examples](#usage-examples) + - [Sending and receiving text data](#sending-and-receiving-text-data) + - [Sending binary data](#sending-binary-data) + - [Simple server](#simple-server) + - [External HTTP/S server](#external-https-server) + - [Multiple servers sharing a single HTTP/S server](#multiple-servers-sharing-a-single-https-server) + - [Client authentication](#client-authentication) + - [Server broadcast](#server-broadcast) + - [Round-trip time](#round-trip-time) + - [Use the Node.js streams API](#use-the-nodejs-streams-api) + - [Other examples](#other-examples) +- [FAQ](#faq) + - [How to get the IP address of the client?](#how-to-get-the-ip-address-of-the-client) + - [How to detect and close broken connections?](#how-to-detect-and-close-broken-connections) + - [How to connect via a proxy?](#how-to-connect-via-a-proxy) +- [Changelog](#changelog) +- [License](#license) + +## Protocol support + +- **HyBi drafts 07-12** (Use the option `protocolVersion: 8`) +- **HyBi drafts 13-17** (Current default, alternatively option + `protocolVersion: 13`) + +## Installing + +``` +npm install ws +``` + +### Opt-in for performance + +[bufferutil][] is an optional module that can be installed alongside the ws +module: + +``` +npm install --save-optional bufferutil +``` + +This is a binary addon that improves the performance of certain operations such +as masking and unmasking the data payload of the WebSocket frames. Prebuilt +binaries are available for the most popular platforms, so you don't necessarily +need to have a C++ compiler installed on your machine. + +To force ws to not use bufferutil, use the +[`WS_NO_BUFFER_UTIL`](./doc/ws.md#ws_no_buffer_util) environment variable. This +can be useful to enhance security in systems where a user can put a package in +the package search path of an application of another user, due to how the +Node.js resolver algorithm works. + +#### Legacy opt-in for performance + +If you are running on an old version of Node.js (prior to v18.14.0), ws also +supports the [utf-8-validate][] module: + +``` +npm install --save-optional utf-8-validate +``` + +This contains a binary polyfill for [`buffer.isUtf8()`][]. + +To force ws not to use utf-8-validate, use the +[`WS_NO_UTF_8_VALIDATE`](./doc/ws.md#ws_no_utf_8_validate) environment variable. + +## API docs + +See [`/doc/ws.md`](./doc/ws.md) for Node.js-like documentation of ws classes and +utility functions. + +## WebSocket compression + +ws supports the [permessage-deflate extension][permessage-deflate] which enables +the client and server to negotiate a compression algorithm and its parameters, +and then selectively apply it to the data payloads of each WebSocket message. + +The extension is disabled by default on the server and enabled by default on the +client. It adds a significant overhead in terms of performance and memory +consumption so we suggest to enable it only if it is really needed. + +Note that Node.js has a variety of issues with high-performance compression, +where increased concurrency, especially on Linux, can lead to [catastrophic +memory fragmentation][node-zlib-bug] and slow performance. If you intend to use +permessage-deflate in production, it is worthwhile to set up a test +representative of your workload and ensure Node.js/zlib will handle it with +acceptable performance and memory usage. + +Tuning of permessage-deflate can be done via the options defined below. You can +also use `zlibDeflateOptions` and `zlibInflateOptions`, which is passed directly +into the creation of [raw deflate/inflate streams][node-zlib-deflaterawdocs]. + +See [the docs][ws-server-options] for more options. + +```js +import WebSocket, { WebSocketServer } from 'ws'; + +const wss = new WebSocketServer({ + port: 8080, + perMessageDeflate: { + zlibDeflateOptions: { + // See zlib defaults. + chunkSize: 1024, + memLevel: 7, + level: 3 + }, + zlibInflateOptions: { + chunkSize: 10 * 1024 + }, + // Other options settable: + clientNoContextTakeover: true, // Defaults to negotiated value. + serverNoContextTakeover: true, // Defaults to negotiated value. + serverMaxWindowBits: 10, // Defaults to negotiated value. + // Below options specified as default values. + concurrencyLimit: 10, // Limits zlib concurrency for perf. + threshold: 1024 // Size (in bytes) below which messages + // should not be compressed if context takeover is disabled. + } +}); +``` + +The client will only use the extension if it is supported and enabled on the +server. To always disable the extension on the client, set the +`perMessageDeflate` option to `false`. + +```js +import WebSocket from 'ws'; + +const ws = new WebSocket('ws://www.host.com/path', { + perMessageDeflate: false +}); +``` + +## Usage examples + +### Sending and receiving text data + +```js +import WebSocket from 'ws'; + +const ws = new WebSocket('ws://www.host.com/path'); + +ws.on('error', console.error); + +ws.on('open', function open() { + ws.send('something'); +}); + +ws.on('message', function message(data) { + console.log('received: %s', data); +}); +``` + +### Sending binary data + +```js +import WebSocket from 'ws'; + +const ws = new WebSocket('ws://www.host.com/path'); + +ws.on('error', console.error); + +ws.on('open', function open() { + const array = new Float32Array(5); + + for (var i = 0; i < array.length; ++i) { + array[i] = i / 2; + } + + ws.send(array); +}); +``` + +### Simple server + +```js +import { WebSocketServer } from 'ws'; + +const wss = new WebSocketServer({ port: 8080 }); + +wss.on('connection', function connection(ws) { + ws.on('error', console.error); + + ws.on('message', function message(data) { + console.log('received: %s', data); + }); + + ws.send('something'); +}); +``` + +### External HTTP/S server + +```js +import { createServer } from 'https'; +import { readFileSync } from 'fs'; +import { WebSocketServer } from 'ws'; + +const server = createServer({ + cert: readFileSync('/path/to/cert.pem'), + key: readFileSync('/path/to/key.pem') +}); +const wss = new WebSocketServer({ server }); + +wss.on('connection', function connection(ws) { + ws.on('error', console.error); + + ws.on('message', function message(data) { + console.log('received: %s', data); + }); + + ws.send('something'); +}); + +server.listen(8080); +``` + +### Multiple servers sharing a single HTTP/S server + +```js +import { createServer } from 'http'; +import { WebSocketServer } from 'ws'; + +const server = createServer(); +const wss1 = new WebSocketServer({ noServer: true }); +const wss2 = new WebSocketServer({ noServer: true }); + +wss1.on('connection', function connection(ws) { + ws.on('error', console.error); + + // ... +}); + +wss2.on('connection', function connection(ws) { + ws.on('error', console.error); + + // ... +}); + +server.on('upgrade', function upgrade(request, socket, head) { + const { pathname } = new URL(request.url, 'wss://base.url'); + + if (pathname === '/foo') { + wss1.handleUpgrade(request, socket, head, function done(ws) { + wss1.emit('connection', ws, request); + }); + } else if (pathname === '/bar') { + wss2.handleUpgrade(request, socket, head, function done(ws) { + wss2.emit('connection', ws, request); + }); + } else { + socket.destroy(); + } +}); + +server.listen(8080); +``` + +### Client authentication + +```js +import { createServer } from 'http'; +import { WebSocketServer } from 'ws'; + +function onSocketError(err) { + console.error(err); +} + +const server = createServer(); +const wss = new WebSocketServer({ noServer: true }); + +wss.on('connection', function connection(ws, request, client) { + ws.on('error', console.error); + + ws.on('message', function message(data) { + console.log(`Received message ${data} from user ${client}`); + }); +}); + +server.on('upgrade', function upgrade(request, socket, head) { + socket.on('error', onSocketError); + + // This function is not defined on purpose. Implement it with your own logic. + authenticate(request, function next(err, client) { + if (err || !client) { + socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n'); + socket.destroy(); + return; + } + + socket.removeListener('error', onSocketError); + + wss.handleUpgrade(request, socket, head, function done(ws) { + wss.emit('connection', ws, request, client); + }); + }); +}); + +server.listen(8080); +``` + +Also see the provided [example][session-parse-example] using `express-session`. + +### Server broadcast + +A client WebSocket broadcasting to all connected WebSocket clients, including +itself. + +```js +import WebSocket, { WebSocketServer } from 'ws'; + +const wss = new WebSocketServer({ port: 8080 }); + +wss.on('connection', function connection(ws) { + ws.on('error', console.error); + + ws.on('message', function message(data, isBinary) { + wss.clients.forEach(function each(client) { + if (client.readyState === WebSocket.OPEN) { + client.send(data, { binary: isBinary }); + } + }); + }); +}); +``` + +A client WebSocket broadcasting to every other connected WebSocket clients, +excluding itself. + +```js +import WebSocket, { WebSocketServer } from 'ws'; + +const wss = new WebSocketServer({ port: 8080 }); + +wss.on('connection', function connection(ws) { + ws.on('error', console.error); + + ws.on('message', function message(data, isBinary) { + wss.clients.forEach(function each(client) { + if (client !== ws && client.readyState === WebSocket.OPEN) { + client.send(data, { binary: isBinary }); + } + }); + }); +}); +``` + +### Round-trip time + +```js +import WebSocket from 'ws'; + +const ws = new WebSocket('wss://websocket-echo.com/'); + +ws.on('error', console.error); + +ws.on('open', function open() { + console.log('connected'); + ws.send(Date.now()); +}); + +ws.on('close', function close() { + console.log('disconnected'); +}); + +ws.on('message', function message(data) { + console.log(`Round-trip time: ${Date.now() - data} ms`); + + setTimeout(function timeout() { + ws.send(Date.now()); + }, 500); +}); +``` + +### Use the Node.js streams API + +```js +import WebSocket, { createWebSocketStream } from 'ws'; + +const ws = new WebSocket('wss://websocket-echo.com/'); + +const duplex = createWebSocketStream(ws, { encoding: 'utf8' }); + +duplex.on('error', console.error); + +duplex.pipe(process.stdout); +process.stdin.pipe(duplex); +``` + +### Other examples + +For a full example with a browser client communicating with a ws server, see the +examples folder. + +Otherwise, see the test cases. + +## FAQ + +### How to get the IP address of the client? + +The remote IP address can be obtained from the raw socket. + +```js +import { WebSocketServer } from 'ws'; + +const wss = new WebSocketServer({ port: 8080 }); + +wss.on('connection', function connection(ws, req) { + const ip = req.socket.remoteAddress; + + ws.on('error', console.error); +}); +``` + +When the server runs behind a proxy like NGINX, the de-facto standard is to use +the `X-Forwarded-For` header. + +```js +wss.on('connection', function connection(ws, req) { + const ip = req.headers['x-forwarded-for'].split(',')[0].trim(); + + ws.on('error', console.error); +}); +``` + +### How to detect and close broken connections? + +Sometimes, the link between the server and the client can be interrupted in a +way that keeps both the server and the client unaware of the broken state of the +connection (e.g. when pulling the cord). + +In these cases, ping messages can be used as a means to verify that the remote +endpoint is still responsive. + +```js +import { WebSocketServer } from 'ws'; + +function heartbeat() { + this.isAlive = true; +} + +const wss = new WebSocketServer({ port: 8080 }); + +wss.on('connection', function connection(ws) { + ws.isAlive = true; + ws.on('error', console.error); + ws.on('pong', heartbeat); +}); + +const interval = setInterval(function ping() { + wss.clients.forEach(function each(ws) { + if (ws.isAlive === false) return ws.terminate(); + + ws.isAlive = false; + ws.ping(); + }); +}, 30000); + +wss.on('close', function close() { + clearInterval(interval); +}); +``` + +Pong messages are automatically sent in response to ping messages as required by +the spec. + +Just like the server example above, your clients might as well lose connection +without knowing it. You might want to add a ping listener on your clients to +prevent that. A simple implementation would be: + +```js +import WebSocket from 'ws'; + +function heartbeat() { + clearTimeout(this.pingTimeout); + + // Use `WebSocket#terminate()`, which immediately destroys the connection, + // instead of `WebSocket#close()`, which waits for the close timer. + // Delay should be equal to the interval at which your server + // sends out pings plus a conservative assumption of the latency. + this.pingTimeout = setTimeout(() => { + this.terminate(); + }, 30000 + 1000); +} + +const client = new WebSocket('wss://websocket-echo.com/'); + +client.on('error', console.error); +client.on('open', heartbeat); +client.on('ping', heartbeat); +client.on('close', function clear() { + clearTimeout(this.pingTimeout); +}); +``` + +### How to connect via a proxy? + +Use a custom `http.Agent` implementation like [https-proxy-agent][] or +[socks-proxy-agent][]. + +## Changelog + +We're using the GitHub [releases][changelog] for changelog entries. + +## License + +[MIT](LICENSE) + +[`buffer.isutf8()`]: https://nodejs.org/api/buffer.html#bufferisutf8input +[bufferutil]: https://github.com/websockets/bufferutil +[changelog]: https://github.com/websockets/ws/releases +[client-report]: http://websockets.github.io/ws/autobahn/clients/ +[https-proxy-agent]: https://github.com/TooTallNate/node-https-proxy-agent +[node-zlib-bug]: https://github.com/nodejs/node/issues/8871 +[node-zlib-deflaterawdocs]: + https://nodejs.org/api/zlib.html#zlib_zlib_createdeflateraw_options +[permessage-deflate]: https://tools.ietf.org/html/rfc7692 +[server-report]: http://websockets.github.io/ws/autobahn/servers/ +[session-parse-example]: ./examples/express-session-parse +[socks-proxy-agent]: https://github.com/TooTallNate/node-socks-proxy-agent +[utf-8-validate]: https://github.com/websockets/utf-8-validate +[ws-server-options]: ./doc/ws.md#new-websocketserveroptions-callback diff --git a/backend/node_modules/ws/browser.js b/backend/node_modules/ws/browser.js new file mode 100644 index 0000000..ca4f628 --- /dev/null +++ b/backend/node_modules/ws/browser.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = function () { + throw new Error( + 'ws does not work in the browser. Browser clients must use the native ' + + 'WebSocket object' + ); +}; diff --git a/backend/node_modules/ws/index.js b/backend/node_modules/ws/index.js new file mode 100644 index 0000000..41edb3b --- /dev/null +++ b/backend/node_modules/ws/index.js @@ -0,0 +1,13 @@ +'use strict'; + +const WebSocket = require('./lib/websocket'); + +WebSocket.createWebSocketStream = require('./lib/stream'); +WebSocket.Server = require('./lib/websocket-server'); +WebSocket.Receiver = require('./lib/receiver'); +WebSocket.Sender = require('./lib/sender'); + +WebSocket.WebSocket = WebSocket; +WebSocket.WebSocketServer = WebSocket.Server; + +module.exports = WebSocket; diff --git a/backend/node_modules/ws/lib/buffer-util.js b/backend/node_modules/ws/lib/buffer-util.js new file mode 100644 index 0000000..f7536e2 --- /dev/null +++ b/backend/node_modules/ws/lib/buffer-util.js @@ -0,0 +1,131 @@ +'use strict'; + +const { EMPTY_BUFFER } = require('./constants'); + +const FastBuffer = Buffer[Symbol.species]; + +/** + * Merges an array of buffers into a new buffer. + * + * @param {Buffer[]} list The array of buffers to concat + * @param {Number} totalLength The total length of buffers in the list + * @return {Buffer} The resulting buffer + * @public + */ +function concat(list, totalLength) { + if (list.length === 0) return EMPTY_BUFFER; + if (list.length === 1) return list[0]; + + const target = Buffer.allocUnsafe(totalLength); + let offset = 0; + + for (let i = 0; i < list.length; i++) { + const buf = list[i]; + target.set(buf, offset); + offset += buf.length; + } + + if (offset < totalLength) { + return new FastBuffer(target.buffer, target.byteOffset, offset); + } + + return target; +} + +/** + * Masks a buffer using the given mask. + * + * @param {Buffer} source The buffer to mask + * @param {Buffer} mask The mask to use + * @param {Buffer} output The buffer where to store the result + * @param {Number} offset The offset at which to start writing + * @param {Number} length The number of bytes to mask. + * @public + */ +function _mask(source, mask, output, offset, length) { + for (let i = 0; i < length; i++) { + output[offset + i] = source[i] ^ mask[i & 3]; + } +} + +/** + * Unmasks a buffer using the given mask. + * + * @param {Buffer} buffer The buffer to unmask + * @param {Buffer} mask The mask to use + * @public + */ +function _unmask(buffer, mask) { + for (let i = 0; i < buffer.length; i++) { + buffer[i] ^= mask[i & 3]; + } +} + +/** + * Converts a buffer to an `ArrayBuffer`. + * + * @param {Buffer} buf The buffer to convert + * @return {ArrayBuffer} Converted buffer + * @public + */ +function toArrayBuffer(buf) { + if (buf.length === buf.buffer.byteLength) { + return buf.buffer; + } + + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length); +} + +/** + * Converts `data` to a `Buffer`. + * + * @param {*} data The data to convert + * @return {Buffer} The buffer + * @throws {TypeError} + * @public + */ +function toBuffer(data) { + toBuffer.readOnly = true; + + if (Buffer.isBuffer(data)) return data; + + let buf; + + if (data instanceof ArrayBuffer) { + buf = new FastBuffer(data); + } else if (ArrayBuffer.isView(data)) { + buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength); + } else { + buf = Buffer.from(data); + toBuffer.readOnly = false; + } + + return buf; +} + +module.exports = { + concat, + mask: _mask, + toArrayBuffer, + toBuffer, + unmask: _unmask +}; + +/* istanbul ignore else */ +if (!process.env.WS_NO_BUFFER_UTIL) { + try { + const bufferUtil = require('bufferutil'); + + module.exports.mask = function (source, mask, output, offset, length) { + if (length < 48) _mask(source, mask, output, offset, length); + else bufferUtil.mask(source, mask, output, offset, length); + }; + + module.exports.unmask = function (buffer, mask) { + if (buffer.length < 32) _unmask(buffer, mask); + else bufferUtil.unmask(buffer, mask); + }; + } catch (e) { + // Continue regardless of the error. + } +} diff --git a/backend/node_modules/ws/lib/constants.js b/backend/node_modules/ws/lib/constants.js new file mode 100644 index 0000000..74214d4 --- /dev/null +++ b/backend/node_modules/ws/lib/constants.js @@ -0,0 +1,18 @@ +'use strict'; + +const BINARY_TYPES = ['nodebuffer', 'arraybuffer', 'fragments']; +const hasBlob = typeof Blob !== 'undefined'; + +if (hasBlob) BINARY_TYPES.push('blob'); + +module.exports = { + BINARY_TYPES, + EMPTY_BUFFER: Buffer.alloc(0), + GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', + hasBlob, + kForOnEventAttribute: Symbol('kIsForOnEventAttribute'), + kListener: Symbol('kListener'), + kStatusCode: Symbol('status-code'), + kWebSocket: Symbol('websocket'), + NOOP: () => {} +}; diff --git a/backend/node_modules/ws/lib/event-target.js b/backend/node_modules/ws/lib/event-target.js new file mode 100644 index 0000000..fea4cbc --- /dev/null +++ b/backend/node_modules/ws/lib/event-target.js @@ -0,0 +1,292 @@ +'use strict'; + +const { kForOnEventAttribute, kListener } = require('./constants'); + +const kCode = Symbol('kCode'); +const kData = Symbol('kData'); +const kError = Symbol('kError'); +const kMessage = Symbol('kMessage'); +const kReason = Symbol('kReason'); +const kTarget = Symbol('kTarget'); +const kType = Symbol('kType'); +const kWasClean = Symbol('kWasClean'); + +/** + * Class representing an event. + */ +class Event { + /** + * Create a new `Event`. + * + * @param {String} type The name of the event + * @throws {TypeError} If the `type` argument is not specified + */ + constructor(type) { + this[kTarget] = null; + this[kType] = type; + } + + /** + * @type {*} + */ + get target() { + return this[kTarget]; + } + + /** + * @type {String} + */ + get type() { + return this[kType]; + } +} + +Object.defineProperty(Event.prototype, 'target', { enumerable: true }); +Object.defineProperty(Event.prototype, 'type', { enumerable: true }); + +/** + * Class representing a close event. + * + * @extends Event + */ +class CloseEvent extends Event { + /** + * Create a new `CloseEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {Number} [options.code=0] The status code explaining why the + * connection was closed + * @param {String} [options.reason=''] A human-readable string explaining why + * the connection was closed + * @param {Boolean} [options.wasClean=false] Indicates whether or not the + * connection was cleanly closed + */ + constructor(type, options = {}) { + super(type); + + this[kCode] = options.code === undefined ? 0 : options.code; + this[kReason] = options.reason === undefined ? '' : options.reason; + this[kWasClean] = options.wasClean === undefined ? false : options.wasClean; + } + + /** + * @type {Number} + */ + get code() { + return this[kCode]; + } + + /** + * @type {String} + */ + get reason() { + return this[kReason]; + } + + /** + * @type {Boolean} + */ + get wasClean() { + return this[kWasClean]; + } +} + +Object.defineProperty(CloseEvent.prototype, 'code', { enumerable: true }); +Object.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true }); +Object.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true }); + +/** + * Class representing an error event. + * + * @extends Event + */ +class ErrorEvent extends Event { + /** + * Create a new `ErrorEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {*} [options.error=null] The error that generated this event + * @param {String} [options.message=''] The error message + */ + constructor(type, options = {}) { + super(type); + + this[kError] = options.error === undefined ? null : options.error; + this[kMessage] = options.message === undefined ? '' : options.message; + } + + /** + * @type {*} + */ + get error() { + return this[kError]; + } + + /** + * @type {String} + */ + get message() { + return this[kMessage]; + } +} + +Object.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true }); +Object.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true }); + +/** + * Class representing a message event. + * + * @extends Event + */ +class MessageEvent extends Event { + /** + * Create a new `MessageEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {*} [options.data=null] The message content + */ + constructor(type, options = {}) { + super(type); + + this[kData] = options.data === undefined ? null : options.data; + } + + /** + * @type {*} + */ + get data() { + return this[kData]; + } +} + +Object.defineProperty(MessageEvent.prototype, 'data', { enumerable: true }); + +/** + * This provides methods for emulating the `EventTarget` interface. It's not + * meant to be used directly. + * + * @mixin + */ +const EventTarget = { + /** + * Register an event listener. + * + * @param {String} type A string representing the event type to listen for + * @param {(Function|Object)} handler The listener to add + * @param {Object} [options] An options object specifies characteristics about + * the event listener + * @param {Boolean} [options.once=false] A `Boolean` indicating that the + * listener should be invoked at most once after being added. If `true`, + * the listener would be automatically removed when invoked. + * @public + */ + addEventListener(type, handler, options = {}) { + for (const listener of this.listeners(type)) { + if ( + !options[kForOnEventAttribute] && + listener[kListener] === handler && + !listener[kForOnEventAttribute] + ) { + return; + } + } + + let wrapper; + + if (type === 'message') { + wrapper = function onMessage(data, isBinary) { + const event = new MessageEvent('message', { + data: isBinary ? data : data.toString() + }); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === 'close') { + wrapper = function onClose(code, message) { + const event = new CloseEvent('close', { + code, + reason: message.toString(), + wasClean: this._closeFrameReceived && this._closeFrameSent + }); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === 'error') { + wrapper = function onError(error) { + const event = new ErrorEvent('error', { + error, + message: error.message + }); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === 'open') { + wrapper = function onOpen() { + const event = new Event('open'); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else { + return; + } + + wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute]; + wrapper[kListener] = handler; + + if (options.once) { + this.once(type, wrapper); + } else { + this.on(type, wrapper); + } + }, + + /** + * Remove an event listener. + * + * @param {String} type A string representing the event type to remove + * @param {(Function|Object)} handler The listener to remove + * @public + */ + removeEventListener(type, handler) { + for (const listener of this.listeners(type)) { + if (listener[kListener] === handler && !listener[kForOnEventAttribute]) { + this.removeListener(type, listener); + break; + } + } + } +}; + +module.exports = { + CloseEvent, + ErrorEvent, + Event, + EventTarget, + MessageEvent +}; + +/** + * Call an event listener + * + * @param {(Function|Object)} listener The listener to call + * @param {*} thisArg The value to use as `this`` when calling the listener + * @param {Event} event The event to pass to the listener + * @private + */ +function callListener(listener, thisArg, event) { + if (typeof listener === 'object' && listener.handleEvent) { + listener.handleEvent.call(listener, event); + } else { + listener.call(thisArg, event); + } +} diff --git a/backend/node_modules/ws/lib/extension.js b/backend/node_modules/ws/lib/extension.js new file mode 100644 index 0000000..3d7895c --- /dev/null +++ b/backend/node_modules/ws/lib/extension.js @@ -0,0 +1,203 @@ +'use strict'; + +const { tokenChars } = require('./validation'); + +/** + * Adds an offer to the map of extension offers or a parameter to the map of + * parameters. + * + * @param {Object} dest The map of extension offers or parameters + * @param {String} name The extension or parameter name + * @param {(Object|Boolean|String)} elem The extension parameters or the + * parameter value + * @private + */ +function push(dest, name, elem) { + if (dest[name] === undefined) dest[name] = [elem]; + else dest[name].push(elem); +} + +/** + * Parses the `Sec-WebSocket-Extensions` header into an object. + * + * @param {String} header The field value of the header + * @return {Object} The parsed object + * @public + */ +function parse(header) { + const offers = Object.create(null); + let params = Object.create(null); + let mustUnescape = false; + let isEscaping = false; + let inQuotes = false; + let extensionName; + let paramName; + let start = -1; + let code = -1; + let end = -1; + let i = 0; + + for (; i < header.length; i++) { + code = header.charCodeAt(i); + + if (extensionName === undefined) { + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if ( + i !== 0 && + (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */ + ) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + const name = header.slice(start, end); + if (code === 0x2c) { + push(offers, name, params); + params = Object.create(null); + } else { + extensionName = name; + } + + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else if (paramName === undefined) { + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (code === 0x20 || code === 0x09) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x3b || code === 0x2c) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + push(params, header.slice(start, end), true); + if (code === 0x2c) { + push(offers, extensionName, params); + params = Object.create(null); + extensionName = undefined; + } + + start = end = -1; + } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) { + paramName = header.slice(start, i); + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else { + // + // The value of a quoted-string after unescaping must conform to the + // token ABNF, so only token characters are valid. + // Ref: https://tools.ietf.org/html/rfc6455#section-9.1 + // + if (isEscaping) { + if (tokenChars[code] !== 1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + if (start === -1) start = i; + else if (!mustUnescape) mustUnescape = true; + isEscaping = false; + } else if (inQuotes) { + if (tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (code === 0x22 /* '"' */ && start !== -1) { + inQuotes = false; + end = i; + } else if (code === 0x5c /* '\' */) { + isEscaping = true; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) { + inQuotes = true; + } else if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (start !== -1 && (code === 0x20 || code === 0x09)) { + if (end === -1) end = i; + } else if (code === 0x3b || code === 0x2c) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + let value = header.slice(start, end); + if (mustUnescape) { + value = value.replace(/\\/g, ''); + mustUnescape = false; + } + push(params, paramName, value); + if (code === 0x2c) { + push(offers, extensionName, params); + params = Object.create(null); + extensionName = undefined; + } + + paramName = undefined; + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } + } + + if (start === -1 || inQuotes || code === 0x20 || code === 0x09) { + throw new SyntaxError('Unexpected end of input'); + } + + if (end === -1) end = i; + const token = header.slice(start, end); + if (extensionName === undefined) { + push(offers, token, params); + } else { + if (paramName === undefined) { + push(params, token, true); + } else if (mustUnescape) { + push(params, paramName, token.replace(/\\/g, '')); + } else { + push(params, paramName, token); + } + push(offers, extensionName, params); + } + + return offers; +} + +/** + * Builds the `Sec-WebSocket-Extensions` header field value. + * + * @param {Object} extensions The map of extensions and parameters to format + * @return {String} A string representing the given object + * @public + */ +function format(extensions) { + return Object.keys(extensions) + .map((extension) => { + let configurations = extensions[extension]; + if (!Array.isArray(configurations)) configurations = [configurations]; + return configurations + .map((params) => { + return [extension] + .concat( + Object.keys(params).map((k) => { + let values = params[k]; + if (!Array.isArray(values)) values = [values]; + return values + .map((v) => (v === true ? k : `${k}=${v}`)) + .join('; '); + }) + ) + .join('; '); + }) + .join(', '); + }) + .join(', '); +} + +module.exports = { format, parse }; diff --git a/backend/node_modules/ws/lib/limiter.js b/backend/node_modules/ws/lib/limiter.js new file mode 100644 index 0000000..3fd3578 --- /dev/null +++ b/backend/node_modules/ws/lib/limiter.js @@ -0,0 +1,55 @@ +'use strict'; + +const kDone = Symbol('kDone'); +const kRun = Symbol('kRun'); + +/** + * A very simple job queue with adjustable concurrency. Adapted from + * https://github.com/STRML/async-limiter + */ +class Limiter { + /** + * Creates a new `Limiter`. + * + * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed + * to run concurrently + */ + constructor(concurrency) { + this[kDone] = () => { + this.pending--; + this[kRun](); + }; + this.concurrency = concurrency || Infinity; + this.jobs = []; + this.pending = 0; + } + + /** + * Adds a job to the queue. + * + * @param {Function} job The job to run + * @public + */ + add(job) { + this.jobs.push(job); + this[kRun](); + } + + /** + * Removes a job from the queue and runs it if possible. + * + * @private + */ + [kRun]() { + if (this.pending === this.concurrency) return; + + if (this.jobs.length) { + const job = this.jobs.shift(); + + this.pending++; + job(this[kDone]); + } + } +} + +module.exports = Limiter; diff --git a/backend/node_modules/ws/lib/permessage-deflate.js b/backend/node_modules/ws/lib/permessage-deflate.js new file mode 100644 index 0000000..41ff70e --- /dev/null +++ b/backend/node_modules/ws/lib/permessage-deflate.js @@ -0,0 +1,528 @@ +'use strict'; + +const zlib = require('zlib'); + +const bufferUtil = require('./buffer-util'); +const Limiter = require('./limiter'); +const { kStatusCode } = require('./constants'); + +const FastBuffer = Buffer[Symbol.species]; +const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]); +const kPerMessageDeflate = Symbol('permessage-deflate'); +const kTotalLength = Symbol('total-length'); +const kCallback = Symbol('callback'); +const kBuffers = Symbol('buffers'); +const kError = Symbol('error'); + +// +// We limit zlib concurrency, which prevents severe memory fragmentation +// as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913 +// and https://github.com/websockets/ws/issues/1202 +// +// Intentionally global; it's the global thread pool that's an issue. +// +let zlibLimiter; + +/** + * permessage-deflate implementation. + */ +class PerMessageDeflate { + /** + * Creates a PerMessageDeflate instance. + * + * @param {Object} [options] Configuration options + * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support + * for, or request, a custom client window size + * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/ + * acknowledge disabling of client context takeover + * @param {Number} [options.concurrencyLimit=10] The number of concurrent + * calls to zlib + * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the + * use of a custom server window size + * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept + * disabling of server context takeover + * @param {Number} [options.threshold=1024] Size (in bytes) below which + * messages should not be compressed if context takeover is disabled + * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on + * deflate + * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on + * inflate + * @param {Boolean} [isServer=false] Create the instance in either server or + * client mode + * @param {Number} [maxPayload=0] The maximum allowed message length + */ + constructor(options, isServer, maxPayload) { + this._maxPayload = maxPayload | 0; + this._options = options || {}; + this._threshold = + this._options.threshold !== undefined ? this._options.threshold : 1024; + this._isServer = !!isServer; + this._deflate = null; + this._inflate = null; + + this.params = null; + + if (!zlibLimiter) { + const concurrency = + this._options.concurrencyLimit !== undefined + ? this._options.concurrencyLimit + : 10; + zlibLimiter = new Limiter(concurrency); + } + } + + /** + * @type {String} + */ + static get extensionName() { + return 'permessage-deflate'; + } + + /** + * Create an extension negotiation offer. + * + * @return {Object} Extension parameters + * @public + */ + offer() { + const params = {}; + + if (this._options.serverNoContextTakeover) { + params.server_no_context_takeover = true; + } + if (this._options.clientNoContextTakeover) { + params.client_no_context_takeover = true; + } + if (this._options.serverMaxWindowBits) { + params.server_max_window_bits = this._options.serverMaxWindowBits; + } + if (this._options.clientMaxWindowBits) { + params.client_max_window_bits = this._options.clientMaxWindowBits; + } else if (this._options.clientMaxWindowBits == null) { + params.client_max_window_bits = true; + } + + return params; + } + + /** + * Accept an extension negotiation offer/response. + * + * @param {Array} configurations The extension negotiation offers/reponse + * @return {Object} Accepted configuration + * @public + */ + accept(configurations) { + configurations = this.normalizeParams(configurations); + + this.params = this._isServer + ? this.acceptAsServer(configurations) + : this.acceptAsClient(configurations); + + return this.params; + } + + /** + * Releases all resources used by the extension. + * + * @public + */ + cleanup() { + if (this._inflate) { + this._inflate.close(); + this._inflate = null; + } + + if (this._deflate) { + const callback = this._deflate[kCallback]; + + this._deflate.close(); + this._deflate = null; + + if (callback) { + callback( + new Error( + 'The deflate stream was closed while data was being processed' + ) + ); + } + } + } + + /** + * Accept an extension negotiation offer. + * + * @param {Array} offers The extension negotiation offers + * @return {Object} Accepted configuration + * @private + */ + acceptAsServer(offers) { + const opts = this._options; + const accepted = offers.find((params) => { + if ( + (opts.serverNoContextTakeover === false && + params.server_no_context_takeover) || + (params.server_max_window_bits && + (opts.serverMaxWindowBits === false || + (typeof opts.serverMaxWindowBits === 'number' && + opts.serverMaxWindowBits > params.server_max_window_bits))) || + (typeof opts.clientMaxWindowBits === 'number' && + !params.client_max_window_bits) + ) { + return false; + } + + return true; + }); + + if (!accepted) { + throw new Error('None of the extension offers can be accepted'); + } + + if (opts.serverNoContextTakeover) { + accepted.server_no_context_takeover = true; + } + if (opts.clientNoContextTakeover) { + accepted.client_no_context_takeover = true; + } + if (typeof opts.serverMaxWindowBits === 'number') { + accepted.server_max_window_bits = opts.serverMaxWindowBits; + } + if (typeof opts.clientMaxWindowBits === 'number') { + accepted.client_max_window_bits = opts.clientMaxWindowBits; + } else if ( + accepted.client_max_window_bits === true || + opts.clientMaxWindowBits === false + ) { + delete accepted.client_max_window_bits; + } + + return accepted; + } + + /** + * Accept the extension negotiation response. + * + * @param {Array} response The extension negotiation response + * @return {Object} Accepted configuration + * @private + */ + acceptAsClient(response) { + const params = response[0]; + + if ( + this._options.clientNoContextTakeover === false && + params.client_no_context_takeover + ) { + throw new Error('Unexpected parameter "client_no_context_takeover"'); + } + + if (!params.client_max_window_bits) { + if (typeof this._options.clientMaxWindowBits === 'number') { + params.client_max_window_bits = this._options.clientMaxWindowBits; + } + } else if ( + this._options.clientMaxWindowBits === false || + (typeof this._options.clientMaxWindowBits === 'number' && + params.client_max_window_bits > this._options.clientMaxWindowBits) + ) { + throw new Error( + 'Unexpected or invalid parameter "client_max_window_bits"' + ); + } + + return params; + } + + /** + * Normalize parameters. + * + * @param {Array} configurations The extension negotiation offers/reponse + * @return {Array} The offers/response with normalized parameters + * @private + */ + normalizeParams(configurations) { + configurations.forEach((params) => { + Object.keys(params).forEach((key) => { + let value = params[key]; + + if (value.length > 1) { + throw new Error(`Parameter "${key}" must have only a single value`); + } + + value = value[0]; + + if (key === 'client_max_window_bits') { + if (value !== true) { + const num = +value; + if (!Number.isInteger(num) || num < 8 || num > 15) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + value = num; + } else if (!this._isServer) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + } else if (key === 'server_max_window_bits') { + const num = +value; + if (!Number.isInteger(num) || num < 8 || num > 15) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + value = num; + } else if ( + key === 'client_no_context_takeover' || + key === 'server_no_context_takeover' + ) { + if (value !== true) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + } else { + throw new Error(`Unknown parameter "${key}"`); + } + + params[key] = value; + }); + }); + + return configurations; + } + + /** + * Decompress data. Concurrency limited. + * + * @param {Buffer} data Compressed data + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @public + */ + decompress(data, fin, callback) { + zlibLimiter.add((done) => { + this._decompress(data, fin, (err, result) => { + done(); + callback(err, result); + }); + }); + } + + /** + * Compress data. Concurrency limited. + * + * @param {(Buffer|String)} data Data to compress + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @public + */ + compress(data, fin, callback) { + zlibLimiter.add((done) => { + this._compress(data, fin, (err, result) => { + done(); + callback(err, result); + }); + }); + } + + /** + * Decompress data. + * + * @param {Buffer} data Compressed data + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @private + */ + _decompress(data, fin, callback) { + const endpoint = this._isServer ? 'client' : 'server'; + + if (!this._inflate) { + const key = `${endpoint}_max_window_bits`; + const windowBits = + typeof this.params[key] !== 'number' + ? zlib.Z_DEFAULT_WINDOWBITS + : this.params[key]; + + this._inflate = zlib.createInflateRaw({ + ...this._options.zlibInflateOptions, + windowBits + }); + this._inflate[kPerMessageDeflate] = this; + this._inflate[kTotalLength] = 0; + this._inflate[kBuffers] = []; + this._inflate.on('error', inflateOnError); + this._inflate.on('data', inflateOnData); + } + + this._inflate[kCallback] = callback; + + this._inflate.write(data); + if (fin) this._inflate.write(TRAILER); + + this._inflate.flush(() => { + const err = this._inflate[kError]; + + if (err) { + this._inflate.close(); + this._inflate = null; + callback(err); + return; + } + + const data = bufferUtil.concat( + this._inflate[kBuffers], + this._inflate[kTotalLength] + ); + + if (this._inflate._readableState.endEmitted) { + this._inflate.close(); + this._inflate = null; + } else { + this._inflate[kTotalLength] = 0; + this._inflate[kBuffers] = []; + + if (fin && this.params[`${endpoint}_no_context_takeover`]) { + this._inflate.reset(); + } + } + + callback(null, data); + }); + } + + /** + * Compress data. + * + * @param {(Buffer|String)} data Data to compress + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @private + */ + _compress(data, fin, callback) { + const endpoint = this._isServer ? 'server' : 'client'; + + if (!this._deflate) { + const key = `${endpoint}_max_window_bits`; + const windowBits = + typeof this.params[key] !== 'number' + ? zlib.Z_DEFAULT_WINDOWBITS + : this.params[key]; + + this._deflate = zlib.createDeflateRaw({ + ...this._options.zlibDeflateOptions, + windowBits + }); + + this._deflate[kTotalLength] = 0; + this._deflate[kBuffers] = []; + + this._deflate.on('data', deflateOnData); + } + + this._deflate[kCallback] = callback; + + this._deflate.write(data); + this._deflate.flush(zlib.Z_SYNC_FLUSH, () => { + if (!this._deflate) { + // + // The deflate stream was closed while data was being processed. + // + return; + } + + let data = bufferUtil.concat( + this._deflate[kBuffers], + this._deflate[kTotalLength] + ); + + if (fin) { + data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4); + } + + // + // Ensure that the callback will not be called again in + // `PerMessageDeflate#cleanup()`. + // + this._deflate[kCallback] = null; + + this._deflate[kTotalLength] = 0; + this._deflate[kBuffers] = []; + + if (fin && this.params[`${endpoint}_no_context_takeover`]) { + this._deflate.reset(); + } + + callback(null, data); + }); + } +} + +module.exports = PerMessageDeflate; + +/** + * The listener of the `zlib.DeflateRaw` stream `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function deflateOnData(chunk) { + this[kBuffers].push(chunk); + this[kTotalLength] += chunk.length; +} + +/** + * The listener of the `zlib.InflateRaw` stream `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function inflateOnData(chunk) { + this[kTotalLength] += chunk.length; + + if ( + this[kPerMessageDeflate]._maxPayload < 1 || + this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload + ) { + this[kBuffers].push(chunk); + return; + } + + this[kError] = new RangeError('Max payload size exceeded'); + this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'; + this[kError][kStatusCode] = 1009; + this.removeListener('data', inflateOnData); + + // + // The choice to employ `zlib.reset()` over `zlib.close()` is dictated by the + // fact that in Node.js versions prior to 13.10.0, the callback for + // `zlib.flush()` is not called if `zlib.close()` is used. Utilizing + // `zlib.reset()` ensures that either the callback is invoked or an error is + // emitted. + // + this.reset(); +} + +/** + * The listener of the `zlib.InflateRaw` stream `'error'` event. + * + * @param {Error} err The emitted error + * @private + */ +function inflateOnError(err) { + // + // There is no need to call `Zlib#close()` as the handle is automatically + // closed when an error is emitted. + // + this[kPerMessageDeflate]._inflate = null; + + if (this[kError]) { + this[kCallback](this[kError]); + return; + } + + err[kStatusCode] = 1007; + this[kCallback](err); +} diff --git a/backend/node_modules/ws/lib/receiver.js b/backend/node_modules/ws/lib/receiver.js new file mode 100644 index 0000000..54d9b4f --- /dev/null +++ b/backend/node_modules/ws/lib/receiver.js @@ -0,0 +1,706 @@ +'use strict'; + +const { Writable } = require('stream'); + +const PerMessageDeflate = require('./permessage-deflate'); +const { + BINARY_TYPES, + EMPTY_BUFFER, + kStatusCode, + kWebSocket +} = require('./constants'); +const { concat, toArrayBuffer, unmask } = require('./buffer-util'); +const { isValidStatusCode, isValidUTF8 } = require('./validation'); + +const FastBuffer = Buffer[Symbol.species]; + +const GET_INFO = 0; +const GET_PAYLOAD_LENGTH_16 = 1; +const GET_PAYLOAD_LENGTH_64 = 2; +const GET_MASK = 3; +const GET_DATA = 4; +const INFLATING = 5; +const DEFER_EVENT = 6; + +/** + * HyBi Receiver implementation. + * + * @extends Writable + */ +class Receiver extends Writable { + /** + * Creates a Receiver instance. + * + * @param {Object} [options] Options object + * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether + * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted + * multiple times in the same tick + * @param {String} [options.binaryType=nodebuffer] The type for binary data + * @param {Object} [options.extensions] An object containing the negotiated + * extensions + * @param {Boolean} [options.isServer=false] Specifies whether to operate in + * client or server mode + * @param {Number} [options.maxPayload=0] The maximum allowed message length + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + */ + constructor(options = {}) { + super(); + + this._allowSynchronousEvents = + options.allowSynchronousEvents !== undefined + ? options.allowSynchronousEvents + : true; + this._binaryType = options.binaryType || BINARY_TYPES[0]; + this._extensions = options.extensions || {}; + this._isServer = !!options.isServer; + this._maxPayload = options.maxPayload | 0; + this._skipUTF8Validation = !!options.skipUTF8Validation; + this[kWebSocket] = undefined; + + this._bufferedBytes = 0; + this._buffers = []; + + this._compressed = false; + this._payloadLength = 0; + this._mask = undefined; + this._fragmented = 0; + this._masked = false; + this._fin = false; + this._opcode = 0; + + this._totalPayloadLength = 0; + this._messageLength = 0; + this._fragments = []; + + this._errored = false; + this._loop = false; + this._state = GET_INFO; + } + + /** + * Implements `Writable.prototype._write()`. + * + * @param {Buffer} chunk The chunk of data to write + * @param {String} encoding The character encoding of `chunk` + * @param {Function} cb Callback + * @private + */ + _write(chunk, encoding, cb) { + if (this._opcode === 0x08 && this._state == GET_INFO) return cb(); + + this._bufferedBytes += chunk.length; + this._buffers.push(chunk); + this.startLoop(cb); + } + + /** + * Consumes `n` bytes from the buffered data. + * + * @param {Number} n The number of bytes to consume + * @return {Buffer} The consumed bytes + * @private + */ + consume(n) { + this._bufferedBytes -= n; + + if (n === this._buffers[0].length) return this._buffers.shift(); + + if (n < this._buffers[0].length) { + const buf = this._buffers[0]; + this._buffers[0] = new FastBuffer( + buf.buffer, + buf.byteOffset + n, + buf.length - n + ); + + return new FastBuffer(buf.buffer, buf.byteOffset, n); + } + + const dst = Buffer.allocUnsafe(n); + + do { + const buf = this._buffers[0]; + const offset = dst.length - n; + + if (n >= buf.length) { + dst.set(this._buffers.shift(), offset); + } else { + dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset); + this._buffers[0] = new FastBuffer( + buf.buffer, + buf.byteOffset + n, + buf.length - n + ); + } + + n -= buf.length; + } while (n > 0); + + return dst; + } + + /** + * Starts the parsing loop. + * + * @param {Function} cb Callback + * @private + */ + startLoop(cb) { + this._loop = true; + + do { + switch (this._state) { + case GET_INFO: + this.getInfo(cb); + break; + case GET_PAYLOAD_LENGTH_16: + this.getPayloadLength16(cb); + break; + case GET_PAYLOAD_LENGTH_64: + this.getPayloadLength64(cb); + break; + case GET_MASK: + this.getMask(); + break; + case GET_DATA: + this.getData(cb); + break; + case INFLATING: + case DEFER_EVENT: + this._loop = false; + return; + } + } while (this._loop); + + if (!this._errored) cb(); + } + + /** + * Reads the first two bytes of a frame. + * + * @param {Function} cb Callback + * @private + */ + getInfo(cb) { + if (this._bufferedBytes < 2) { + this._loop = false; + return; + } + + const buf = this.consume(2); + + if ((buf[0] & 0x30) !== 0x00) { + const error = this.createError( + RangeError, + 'RSV2 and RSV3 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_2_3' + ); + + cb(error); + return; + } + + const compressed = (buf[0] & 0x40) === 0x40; + + if (compressed && !this._extensions[PerMessageDeflate.extensionName]) { + const error = this.createError( + RangeError, + 'RSV1 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_1' + ); + + cb(error); + return; + } + + this._fin = (buf[0] & 0x80) === 0x80; + this._opcode = buf[0] & 0x0f; + this._payloadLength = buf[1] & 0x7f; + + if (this._opcode === 0x00) { + if (compressed) { + const error = this.createError( + RangeError, + 'RSV1 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_1' + ); + + cb(error); + return; + } + + if (!this._fragmented) { + const error = this.createError( + RangeError, + 'invalid opcode 0', + true, + 1002, + 'WS_ERR_INVALID_OPCODE' + ); + + cb(error); + return; + } + + this._opcode = this._fragmented; + } else if (this._opcode === 0x01 || this._opcode === 0x02) { + if (this._fragmented) { + const error = this.createError( + RangeError, + `invalid opcode ${this._opcode}`, + true, + 1002, + 'WS_ERR_INVALID_OPCODE' + ); + + cb(error); + return; + } + + this._compressed = compressed; + } else if (this._opcode > 0x07 && this._opcode < 0x0b) { + if (!this._fin) { + const error = this.createError( + RangeError, + 'FIN must be set', + true, + 1002, + 'WS_ERR_EXPECTED_FIN' + ); + + cb(error); + return; + } + + if (compressed) { + const error = this.createError( + RangeError, + 'RSV1 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_1' + ); + + cb(error); + return; + } + + if ( + this._payloadLength > 0x7d || + (this._opcode === 0x08 && this._payloadLength === 1) + ) { + const error = this.createError( + RangeError, + `invalid payload length ${this._payloadLength}`, + true, + 1002, + 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH' + ); + + cb(error); + return; + } + } else { + const error = this.createError( + RangeError, + `invalid opcode ${this._opcode}`, + true, + 1002, + 'WS_ERR_INVALID_OPCODE' + ); + + cb(error); + return; + } + + if (!this._fin && !this._fragmented) this._fragmented = this._opcode; + this._masked = (buf[1] & 0x80) === 0x80; + + if (this._isServer) { + if (!this._masked) { + const error = this.createError( + RangeError, + 'MASK must be set', + true, + 1002, + 'WS_ERR_EXPECTED_MASK' + ); + + cb(error); + return; + } + } else if (this._masked) { + const error = this.createError( + RangeError, + 'MASK must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_MASK' + ); + + cb(error); + return; + } + + if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16; + else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64; + else this.haveLength(cb); + } + + /** + * Gets extended payload length (7+16). + * + * @param {Function} cb Callback + * @private + */ + getPayloadLength16(cb) { + if (this._bufferedBytes < 2) { + this._loop = false; + return; + } + + this._payloadLength = this.consume(2).readUInt16BE(0); + this.haveLength(cb); + } + + /** + * Gets extended payload length (7+64). + * + * @param {Function} cb Callback + * @private + */ + getPayloadLength64(cb) { + if (this._bufferedBytes < 8) { + this._loop = false; + return; + } + + const buf = this.consume(8); + const num = buf.readUInt32BE(0); + + // + // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned + // if payload length is greater than this number. + // + if (num > Math.pow(2, 53 - 32) - 1) { + const error = this.createError( + RangeError, + 'Unsupported WebSocket frame: payload length > 2^53 - 1', + false, + 1009, + 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH' + ); + + cb(error); + return; + } + + this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4); + this.haveLength(cb); + } + + /** + * Payload length has been read. + * + * @param {Function} cb Callback + * @private + */ + haveLength(cb) { + if (this._payloadLength && this._opcode < 0x08) { + this._totalPayloadLength += this._payloadLength; + if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) { + const error = this.createError( + RangeError, + 'Max payload size exceeded', + false, + 1009, + 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH' + ); + + cb(error); + return; + } + } + + if (this._masked) this._state = GET_MASK; + else this._state = GET_DATA; + } + + /** + * Reads mask bytes. + * + * @private + */ + getMask() { + if (this._bufferedBytes < 4) { + this._loop = false; + return; + } + + this._mask = this.consume(4); + this._state = GET_DATA; + } + + /** + * Reads data bytes. + * + * @param {Function} cb Callback + * @private + */ + getData(cb) { + let data = EMPTY_BUFFER; + + if (this._payloadLength) { + if (this._bufferedBytes < this._payloadLength) { + this._loop = false; + return; + } + + data = this.consume(this._payloadLength); + + if ( + this._masked && + (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0 + ) { + unmask(data, this._mask); + } + } + + if (this._opcode > 0x07) { + this.controlMessage(data, cb); + return; + } + + if (this._compressed) { + this._state = INFLATING; + this.decompress(data, cb); + return; + } + + if (data.length) { + // + // This message is not compressed so its length is the sum of the payload + // length of all fragments. + // + this._messageLength = this._totalPayloadLength; + this._fragments.push(data); + } + + this.dataMessage(cb); + } + + /** + * Decompresses data. + * + * @param {Buffer} data Compressed data + * @param {Function} cb Callback + * @private + */ + decompress(data, cb) { + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + + perMessageDeflate.decompress(data, this._fin, (err, buf) => { + if (err) return cb(err); + + if (buf.length) { + this._messageLength += buf.length; + if (this._messageLength > this._maxPayload && this._maxPayload > 0) { + const error = this.createError( + RangeError, + 'Max payload size exceeded', + false, + 1009, + 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH' + ); + + cb(error); + return; + } + + this._fragments.push(buf); + } + + this.dataMessage(cb); + if (this._state === GET_INFO) this.startLoop(cb); + }); + } + + /** + * Handles a data message. + * + * @param {Function} cb Callback + * @private + */ + dataMessage(cb) { + if (!this._fin) { + this._state = GET_INFO; + return; + } + + const messageLength = this._messageLength; + const fragments = this._fragments; + + this._totalPayloadLength = 0; + this._messageLength = 0; + this._fragmented = 0; + this._fragments = []; + + if (this._opcode === 2) { + let data; + + if (this._binaryType === 'nodebuffer') { + data = concat(fragments, messageLength); + } else if (this._binaryType === 'arraybuffer') { + data = toArrayBuffer(concat(fragments, messageLength)); + } else if (this._binaryType === 'blob') { + data = new Blob(fragments); + } else { + data = fragments; + } + + if (this._allowSynchronousEvents) { + this.emit('message', data, true); + this._state = GET_INFO; + } else { + this._state = DEFER_EVENT; + setImmediate(() => { + this.emit('message', data, true); + this._state = GET_INFO; + this.startLoop(cb); + }); + } + } else { + const buf = concat(fragments, messageLength); + + if (!this._skipUTF8Validation && !isValidUTF8(buf)) { + const error = this.createError( + Error, + 'invalid UTF-8 sequence', + true, + 1007, + 'WS_ERR_INVALID_UTF8' + ); + + cb(error); + return; + } + + if (this._state === INFLATING || this._allowSynchronousEvents) { + this.emit('message', buf, false); + this._state = GET_INFO; + } else { + this._state = DEFER_EVENT; + setImmediate(() => { + this.emit('message', buf, false); + this._state = GET_INFO; + this.startLoop(cb); + }); + } + } + } + + /** + * Handles a control message. + * + * @param {Buffer} data Data to handle + * @return {(Error|RangeError|undefined)} A possible error + * @private + */ + controlMessage(data, cb) { + if (this._opcode === 0x08) { + if (data.length === 0) { + this._loop = false; + this.emit('conclude', 1005, EMPTY_BUFFER); + this.end(); + } else { + const code = data.readUInt16BE(0); + + if (!isValidStatusCode(code)) { + const error = this.createError( + RangeError, + `invalid status code ${code}`, + true, + 1002, + 'WS_ERR_INVALID_CLOSE_CODE' + ); + + cb(error); + return; + } + + const buf = new FastBuffer( + data.buffer, + data.byteOffset + 2, + data.length - 2 + ); + + if (!this._skipUTF8Validation && !isValidUTF8(buf)) { + const error = this.createError( + Error, + 'invalid UTF-8 sequence', + true, + 1007, + 'WS_ERR_INVALID_UTF8' + ); + + cb(error); + return; + } + + this._loop = false; + this.emit('conclude', code, buf); + this.end(); + } + + this._state = GET_INFO; + return; + } + + if (this._allowSynchronousEvents) { + this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data); + this._state = GET_INFO; + } else { + this._state = DEFER_EVENT; + setImmediate(() => { + this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data); + this._state = GET_INFO; + this.startLoop(cb); + }); + } + } + + /** + * Builds an error object. + * + * @param {function(new:Error|RangeError)} ErrorCtor The error constructor + * @param {String} message The error message + * @param {Boolean} prefix Specifies whether or not to add a default prefix to + * `message` + * @param {Number} statusCode The status code + * @param {String} errorCode The exposed error code + * @return {(Error|RangeError)} The error + * @private + */ + createError(ErrorCtor, message, prefix, statusCode, errorCode) { + this._loop = false; + this._errored = true; + + const err = new ErrorCtor( + prefix ? `Invalid WebSocket frame: ${message}` : message + ); + + Error.captureStackTrace(err, this.createError); + err.code = errorCode; + err[kStatusCode] = statusCode; + return err; + } +} + +module.exports = Receiver; diff --git a/backend/node_modules/ws/lib/sender.js b/backend/node_modules/ws/lib/sender.js new file mode 100644 index 0000000..a8b1da3 --- /dev/null +++ b/backend/node_modules/ws/lib/sender.js @@ -0,0 +1,602 @@ +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex" }] */ + +'use strict'; + +const { Duplex } = require('stream'); +const { randomFillSync } = require('crypto'); + +const PerMessageDeflate = require('./permessage-deflate'); +const { EMPTY_BUFFER, kWebSocket, NOOP } = require('./constants'); +const { isBlob, isValidStatusCode } = require('./validation'); +const { mask: applyMask, toBuffer } = require('./buffer-util'); + +const kByteLength = Symbol('kByteLength'); +const maskBuffer = Buffer.alloc(4); +const RANDOM_POOL_SIZE = 8 * 1024; +let randomPool; +let randomPoolPointer = RANDOM_POOL_SIZE; + +const DEFAULT = 0; +const DEFLATING = 1; +const GET_BLOB_DATA = 2; + +/** + * HyBi Sender implementation. + */ +class Sender { + /** + * Creates a Sender instance. + * + * @param {Duplex} socket The connection socket + * @param {Object} [extensions] An object containing the negotiated extensions + * @param {Function} [generateMask] The function used to generate the masking + * key + */ + constructor(socket, extensions, generateMask) { + this._extensions = extensions || {}; + + if (generateMask) { + this._generateMask = generateMask; + this._maskBuffer = Buffer.alloc(4); + } + + this._socket = socket; + + this._firstFragment = true; + this._compress = false; + + this._bufferedBytes = 0; + this._queue = []; + this._state = DEFAULT; + this.onerror = NOOP; + this[kWebSocket] = undefined; + } + + /** + * Frames a piece of data according to the HyBi WebSocket protocol. + * + * @param {(Buffer|String)} data The data to frame + * @param {Object} options Options object + * @param {Boolean} [options.fin=false] Specifies whether or not to set the + * FIN bit + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Buffer} [options.maskBuffer] The buffer used to store the masking + * key + * @param {Number} options.opcode The opcode + * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be + * modified + * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the + * RSV1 bit + * @return {(Buffer|String)[]} The framed data + * @public + */ + static frame(data, options) { + let mask; + let merge = false; + let offset = 2; + let skipMasking = false; + + if (options.mask) { + mask = options.maskBuffer || maskBuffer; + + if (options.generateMask) { + options.generateMask(mask); + } else { + if (randomPoolPointer === RANDOM_POOL_SIZE) { + /* istanbul ignore else */ + if (randomPool === undefined) { + // + // This is lazily initialized because server-sent frames must not + // be masked so it may never be used. + // + randomPool = Buffer.alloc(RANDOM_POOL_SIZE); + } + + randomFillSync(randomPool, 0, RANDOM_POOL_SIZE); + randomPoolPointer = 0; + } + + mask[0] = randomPool[randomPoolPointer++]; + mask[1] = randomPool[randomPoolPointer++]; + mask[2] = randomPool[randomPoolPointer++]; + mask[3] = randomPool[randomPoolPointer++]; + } + + skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0; + offset = 6; + } + + let dataLength; + + if (typeof data === 'string') { + if ( + (!options.mask || skipMasking) && + options[kByteLength] !== undefined + ) { + dataLength = options[kByteLength]; + } else { + data = Buffer.from(data); + dataLength = data.length; + } + } else { + dataLength = data.length; + merge = options.mask && options.readOnly && !skipMasking; + } + + let payloadLength = dataLength; + + if (dataLength >= 65536) { + offset += 8; + payloadLength = 127; + } else if (dataLength > 125) { + offset += 2; + payloadLength = 126; + } + + const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset); + + target[0] = options.fin ? options.opcode | 0x80 : options.opcode; + if (options.rsv1) target[0] |= 0x40; + + target[1] = payloadLength; + + if (payloadLength === 126) { + target.writeUInt16BE(dataLength, 2); + } else if (payloadLength === 127) { + target[2] = target[3] = 0; + target.writeUIntBE(dataLength, 4, 6); + } + + if (!options.mask) return [target, data]; + + target[1] |= 0x80; + target[offset - 4] = mask[0]; + target[offset - 3] = mask[1]; + target[offset - 2] = mask[2]; + target[offset - 1] = mask[3]; + + if (skipMasking) return [target, data]; + + if (merge) { + applyMask(data, mask, target, offset, dataLength); + return [target]; + } + + applyMask(data, mask, data, 0, dataLength); + return [target, data]; + } + + /** + * Sends a close message to the other peer. + * + * @param {Number} [code] The status code component of the body + * @param {(String|Buffer)} [data] The message component of the body + * @param {Boolean} [mask=false] Specifies whether or not to mask the message + * @param {Function} [cb] Callback + * @public + */ + close(code, data, mask, cb) { + let buf; + + if (code === undefined) { + buf = EMPTY_BUFFER; + } else if (typeof code !== 'number' || !isValidStatusCode(code)) { + throw new TypeError('First argument must be a valid error code number'); + } else if (data === undefined || !data.length) { + buf = Buffer.allocUnsafe(2); + buf.writeUInt16BE(code, 0); + } else { + const length = Buffer.byteLength(data); + + if (length > 123) { + throw new RangeError('The message must not be greater than 123 bytes'); + } + + buf = Buffer.allocUnsafe(2 + length); + buf.writeUInt16BE(code, 0); + + if (typeof data === 'string') { + buf.write(data, 2); + } else { + buf.set(data, 2); + } + } + + const options = { + [kByteLength]: buf.length, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 0x08, + readOnly: false, + rsv1: false + }; + + if (this._state !== DEFAULT) { + this.enqueue([this.dispatch, buf, false, options, cb]); + } else { + this.sendFrame(Sender.frame(buf, options), cb); + } + } + + /** + * Sends a ping message to the other peer. + * + * @param {*} data The message to send + * @param {Boolean} [mask=false] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback + * @public + */ + ping(data, mask, cb) { + let byteLength; + let readOnly; + + if (typeof data === 'string') { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else if (isBlob(data)) { + byteLength = data.size; + readOnly = false; + } else { + data = toBuffer(data); + byteLength = data.length; + readOnly = toBuffer.readOnly; + } + + if (byteLength > 125) { + throw new RangeError('The data size must not be greater than 125 bytes'); + } + + const options = { + [kByteLength]: byteLength, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 0x09, + readOnly, + rsv1: false + }; + + if (isBlob(data)) { + if (this._state !== DEFAULT) { + this.enqueue([this.getBlobData, data, false, options, cb]); + } else { + this.getBlobData(data, false, options, cb); + } + } else if (this._state !== DEFAULT) { + this.enqueue([this.dispatch, data, false, options, cb]); + } else { + this.sendFrame(Sender.frame(data, options), cb); + } + } + + /** + * Sends a pong message to the other peer. + * + * @param {*} data The message to send + * @param {Boolean} [mask=false] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback + * @public + */ + pong(data, mask, cb) { + let byteLength; + let readOnly; + + if (typeof data === 'string') { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else if (isBlob(data)) { + byteLength = data.size; + readOnly = false; + } else { + data = toBuffer(data); + byteLength = data.length; + readOnly = toBuffer.readOnly; + } + + if (byteLength > 125) { + throw new RangeError('The data size must not be greater than 125 bytes'); + } + + const options = { + [kByteLength]: byteLength, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 0x0a, + readOnly, + rsv1: false + }; + + if (isBlob(data)) { + if (this._state !== DEFAULT) { + this.enqueue([this.getBlobData, data, false, options, cb]); + } else { + this.getBlobData(data, false, options, cb); + } + } else if (this._state !== DEFAULT) { + this.enqueue([this.dispatch, data, false, options, cb]); + } else { + this.sendFrame(Sender.frame(data, options), cb); + } + } + + /** + * Sends a data message to the other peer. + * + * @param {*} data The message to send + * @param {Object} options Options object + * @param {Boolean} [options.binary=false] Specifies whether `data` is binary + * or text + * @param {Boolean} [options.compress=false] Specifies whether or not to + * compress `data` + * @param {Boolean} [options.fin=false] Specifies whether the fragment is the + * last one + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Function} [cb] Callback + * @public + */ + send(data, options, cb) { + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + let opcode = options.binary ? 2 : 1; + let rsv1 = options.compress; + + let byteLength; + let readOnly; + + if (typeof data === 'string') { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else if (isBlob(data)) { + byteLength = data.size; + readOnly = false; + } else { + data = toBuffer(data); + byteLength = data.length; + readOnly = toBuffer.readOnly; + } + + if (this._firstFragment) { + this._firstFragment = false; + if ( + rsv1 && + perMessageDeflate && + perMessageDeflate.params[ + perMessageDeflate._isServer + ? 'server_no_context_takeover' + : 'client_no_context_takeover' + ] + ) { + rsv1 = byteLength >= perMessageDeflate._threshold; + } + this._compress = rsv1; + } else { + rsv1 = false; + opcode = 0; + } + + if (options.fin) this._firstFragment = true; + + const opts = { + [kByteLength]: byteLength, + fin: options.fin, + generateMask: this._generateMask, + mask: options.mask, + maskBuffer: this._maskBuffer, + opcode, + readOnly, + rsv1 + }; + + if (isBlob(data)) { + if (this._state !== DEFAULT) { + this.enqueue([this.getBlobData, data, this._compress, opts, cb]); + } else { + this.getBlobData(data, this._compress, opts, cb); + } + } else if (this._state !== DEFAULT) { + this.enqueue([this.dispatch, data, this._compress, opts, cb]); + } else { + this.dispatch(data, this._compress, opts, cb); + } + } + + /** + * Gets the contents of a blob as binary data. + * + * @param {Blob} blob The blob + * @param {Boolean} [compress=false] Specifies whether or not to compress + * the data + * @param {Object} options Options object + * @param {Boolean} [options.fin=false] Specifies whether or not to set the + * FIN bit + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Buffer} [options.maskBuffer] The buffer used to store the masking + * key + * @param {Number} options.opcode The opcode + * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be + * modified + * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the + * RSV1 bit + * @param {Function} [cb] Callback + * @private + */ + getBlobData(blob, compress, options, cb) { + this._bufferedBytes += options[kByteLength]; + this._state = GET_BLOB_DATA; + + blob + .arrayBuffer() + .then((arrayBuffer) => { + if (this._socket.destroyed) { + const err = new Error( + 'The socket was closed while the blob was being read' + ); + + // + // `callCallbacks` is called in the next tick to ensure that errors + // that might be thrown in the callbacks behave like errors thrown + // outside the promise chain. + // + process.nextTick(callCallbacks, this, err, cb); + return; + } + + this._bufferedBytes -= options[kByteLength]; + const data = toBuffer(arrayBuffer); + + if (!compress) { + this._state = DEFAULT; + this.sendFrame(Sender.frame(data, options), cb); + this.dequeue(); + } else { + this.dispatch(data, compress, options, cb); + } + }) + .catch((err) => { + // + // `onError` is called in the next tick for the same reason that + // `callCallbacks` above is. + // + process.nextTick(onError, this, err, cb); + }); + } + + /** + * Dispatches a message. + * + * @param {(Buffer|String)} data The message to send + * @param {Boolean} [compress=false] Specifies whether or not to compress + * `data` + * @param {Object} options Options object + * @param {Boolean} [options.fin=false] Specifies whether or not to set the + * FIN bit + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Buffer} [options.maskBuffer] The buffer used to store the masking + * key + * @param {Number} options.opcode The opcode + * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be + * modified + * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the + * RSV1 bit + * @param {Function} [cb] Callback + * @private + */ + dispatch(data, compress, options, cb) { + if (!compress) { + this.sendFrame(Sender.frame(data, options), cb); + return; + } + + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + + this._bufferedBytes += options[kByteLength]; + this._state = DEFLATING; + perMessageDeflate.compress(data, options.fin, (_, buf) => { + if (this._socket.destroyed) { + const err = new Error( + 'The socket was closed while data was being compressed' + ); + + callCallbacks(this, err, cb); + return; + } + + this._bufferedBytes -= options[kByteLength]; + this._state = DEFAULT; + options.readOnly = false; + this.sendFrame(Sender.frame(buf, options), cb); + this.dequeue(); + }); + } + + /** + * Executes queued send operations. + * + * @private + */ + dequeue() { + while (this._state === DEFAULT && this._queue.length) { + const params = this._queue.shift(); + + this._bufferedBytes -= params[3][kByteLength]; + Reflect.apply(params[0], this, params.slice(1)); + } + } + + /** + * Enqueues a send operation. + * + * @param {Array} params Send operation parameters. + * @private + */ + enqueue(params) { + this._bufferedBytes += params[3][kByteLength]; + this._queue.push(params); + } + + /** + * Sends a frame. + * + * @param {(Buffer | String)[]} list The frame to send + * @param {Function} [cb] Callback + * @private + */ + sendFrame(list, cb) { + if (list.length === 2) { + this._socket.cork(); + this._socket.write(list[0]); + this._socket.write(list[1], cb); + this._socket.uncork(); + } else { + this._socket.write(list[0], cb); + } + } +} + +module.exports = Sender; + +/** + * Calls queued callbacks with an error. + * + * @param {Sender} sender The `Sender` instance + * @param {Error} err The error to call the callbacks with + * @param {Function} [cb] The first callback + * @private + */ +function callCallbacks(sender, err, cb) { + if (typeof cb === 'function') cb(err); + + for (let i = 0; i < sender._queue.length; i++) { + const params = sender._queue[i]; + const callback = params[params.length - 1]; + + if (typeof callback === 'function') callback(err); + } +} + +/** + * Handles a `Sender` error. + * + * @param {Sender} sender The `Sender` instance + * @param {Error} err The error + * @param {Function} [cb] The first pending callback + * @private + */ +function onError(sender, err, cb) { + callCallbacks(sender, err, cb); + sender.onerror(err); +} diff --git a/backend/node_modules/ws/lib/stream.js b/backend/node_modules/ws/lib/stream.js new file mode 100644 index 0000000..4c58c91 --- /dev/null +++ b/backend/node_modules/ws/lib/stream.js @@ -0,0 +1,161 @@ +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^WebSocket$" }] */ +'use strict'; + +const WebSocket = require('./websocket'); +const { Duplex } = require('stream'); + +/** + * Emits the `'close'` event on a stream. + * + * @param {Duplex} stream The stream. + * @private + */ +function emitClose(stream) { + stream.emit('close'); +} + +/** + * The listener of the `'end'` event. + * + * @private + */ +function duplexOnEnd() { + if (!this.destroyed && this._writableState.finished) { + this.destroy(); + } +} + +/** + * The listener of the `'error'` event. + * + * @param {Error} err The error + * @private + */ +function duplexOnError(err) { + this.removeListener('error', duplexOnError); + this.destroy(); + if (this.listenerCount('error') === 0) { + // Do not suppress the throwing behavior. + this.emit('error', err); + } +} + +/** + * Wraps a `WebSocket` in a duplex stream. + * + * @param {WebSocket} ws The `WebSocket` to wrap + * @param {Object} [options] The options for the `Duplex` constructor + * @return {Duplex} The duplex stream + * @public + */ +function createWebSocketStream(ws, options) { + let terminateOnDestroy = true; + + const duplex = new Duplex({ + ...options, + autoDestroy: false, + emitClose: false, + objectMode: false, + writableObjectMode: false + }); + + ws.on('message', function message(msg, isBinary) { + const data = + !isBinary && duplex._readableState.objectMode ? msg.toString() : msg; + + if (!duplex.push(data)) ws.pause(); + }); + + ws.once('error', function error(err) { + if (duplex.destroyed) return; + + // Prevent `ws.terminate()` from being called by `duplex._destroy()`. + // + // - If the `'error'` event is emitted before the `'open'` event, then + // `ws.terminate()` is a noop as no socket is assigned. + // - Otherwise, the error is re-emitted by the listener of the `'error'` + // event of the `Receiver` object. The listener already closes the + // connection by calling `ws.close()`. This allows a close frame to be + // sent to the other peer. If `ws.terminate()` is called right after this, + // then the close frame might not be sent. + terminateOnDestroy = false; + duplex.destroy(err); + }); + + ws.once('close', function close() { + if (duplex.destroyed) return; + + duplex.push(null); + }); + + duplex._destroy = function (err, callback) { + if (ws.readyState === ws.CLOSED) { + callback(err); + process.nextTick(emitClose, duplex); + return; + } + + let called = false; + + ws.once('error', function error(err) { + called = true; + callback(err); + }); + + ws.once('close', function close() { + if (!called) callback(err); + process.nextTick(emitClose, duplex); + }); + + if (terminateOnDestroy) ws.terminate(); + }; + + duplex._final = function (callback) { + if (ws.readyState === ws.CONNECTING) { + ws.once('open', function open() { + duplex._final(callback); + }); + return; + } + + // If the value of the `_socket` property is `null` it means that `ws` is a + // client websocket and the handshake failed. In fact, when this happens, a + // socket is never assigned to the websocket. Wait for the `'error'` event + // that will be emitted by the websocket. + if (ws._socket === null) return; + + if (ws._socket._writableState.finished) { + callback(); + if (duplex._readableState.endEmitted) duplex.destroy(); + } else { + ws._socket.once('finish', function finish() { + // `duplex` is not destroyed here because the `'end'` event will be + // emitted on `duplex` after this `'finish'` event. The EOF signaling + // `null` chunk is, in fact, pushed when the websocket emits `'close'`. + callback(); + }); + ws.close(); + } + }; + + duplex._read = function () { + if (ws.isPaused) ws.resume(); + }; + + duplex._write = function (chunk, encoding, callback) { + if (ws.readyState === ws.CONNECTING) { + ws.once('open', function open() { + duplex._write(chunk, encoding, callback); + }); + return; + } + + ws.send(chunk, callback); + }; + + duplex.on('end', duplexOnEnd); + duplex.on('error', duplexOnError); + return duplex; +} + +module.exports = createWebSocketStream; diff --git a/backend/node_modules/ws/lib/subprotocol.js b/backend/node_modules/ws/lib/subprotocol.js new file mode 100644 index 0000000..d4381e8 --- /dev/null +++ b/backend/node_modules/ws/lib/subprotocol.js @@ -0,0 +1,62 @@ +'use strict'; + +const { tokenChars } = require('./validation'); + +/** + * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names. + * + * @param {String} header The field value of the header + * @return {Set} The subprotocol names + * @public + */ +function parse(header) { + const protocols = new Set(); + let start = -1; + let end = -1; + let i = 0; + + for (i; i < header.length; i++) { + const code = header.charCodeAt(i); + + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if ( + i !== 0 && + (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */ + ) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x2c /* ',' */) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + + const protocol = header.slice(start, end); + + if (protocols.has(protocol)) { + throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); + } + + protocols.add(protocol); + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } + + if (start === -1 || end !== -1) { + throw new SyntaxError('Unexpected end of input'); + } + + const protocol = header.slice(start, i); + + if (protocols.has(protocol)) { + throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); + } + + protocols.add(protocol); + return protocols; +} + +module.exports = { parse }; diff --git a/backend/node_modules/ws/lib/validation.js b/backend/node_modules/ws/lib/validation.js new file mode 100644 index 0000000..4a2e68d --- /dev/null +++ b/backend/node_modules/ws/lib/validation.js @@ -0,0 +1,152 @@ +'use strict'; + +const { isUtf8 } = require('buffer'); + +const { hasBlob } = require('./constants'); + +// +// Allowed token characters: +// +// '!', '#', '$', '%', '&', ''', '*', '+', '-', +// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~' +// +// tokenChars[32] === 0 // ' ' +// tokenChars[33] === 1 // '!' +// tokenChars[34] === 0 // '"' +// ... +// +// prettier-ignore +const tokenChars = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31 + 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63 + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127 +]; + +/** + * Checks if a status code is allowed in a close frame. + * + * @param {Number} code The status code + * @return {Boolean} `true` if the status code is valid, else `false` + * @public + */ +function isValidStatusCode(code) { + return ( + (code >= 1000 && + code <= 1014 && + code !== 1004 && + code !== 1005 && + code !== 1006) || + (code >= 3000 && code <= 4999) + ); +} + +/** + * Checks if a given buffer contains only correct UTF-8. + * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by + * Markus Kuhn. + * + * @param {Buffer} buf The buffer to check + * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false` + * @public + */ +function _isValidUTF8(buf) { + const len = buf.length; + let i = 0; + + while (i < len) { + if ((buf[i] & 0x80) === 0) { + // 0xxxxxxx + i++; + } else if ((buf[i] & 0xe0) === 0xc0) { + // 110xxxxx 10xxxxxx + if ( + i + 1 === len || + (buf[i + 1] & 0xc0) !== 0x80 || + (buf[i] & 0xfe) === 0xc0 // Overlong + ) { + return false; + } + + i += 2; + } else if ((buf[i] & 0xf0) === 0xe0) { + // 1110xxxx 10xxxxxx 10xxxxxx + if ( + i + 2 >= len || + (buf[i + 1] & 0xc0) !== 0x80 || + (buf[i + 2] & 0xc0) !== 0x80 || + (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong + (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF) + ) { + return false; + } + + i += 3; + } else if ((buf[i] & 0xf8) === 0xf0) { + // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + if ( + i + 3 >= len || + (buf[i + 1] & 0xc0) !== 0x80 || + (buf[i + 2] & 0xc0) !== 0x80 || + (buf[i + 3] & 0xc0) !== 0x80 || + (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong + (buf[i] === 0xf4 && buf[i + 1] > 0x8f) || + buf[i] > 0xf4 // > U+10FFFF + ) { + return false; + } + + i += 4; + } else { + return false; + } + } + + return true; +} + +/** + * Determines whether a value is a `Blob`. + * + * @param {*} value The value to be tested + * @return {Boolean} `true` if `value` is a `Blob`, else `false` + * @private + */ +function isBlob(value) { + return ( + hasBlob && + typeof value === 'object' && + typeof value.arrayBuffer === 'function' && + typeof value.type === 'string' && + typeof value.stream === 'function' && + (value[Symbol.toStringTag] === 'Blob' || + value[Symbol.toStringTag] === 'File') + ); +} + +module.exports = { + isBlob, + isValidStatusCode, + isValidUTF8: _isValidUTF8, + tokenChars +}; + +if (isUtf8) { + module.exports.isValidUTF8 = function (buf) { + return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf); + }; +} /* istanbul ignore else */ else if (!process.env.WS_NO_UTF_8_VALIDATE) { + try { + const isValidUTF8 = require('utf-8-validate'); + + module.exports.isValidUTF8 = function (buf) { + return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf); + }; + } catch (e) { + // Continue regardless of the error. + } +} diff --git a/backend/node_modules/ws/lib/websocket-server.js b/backend/node_modules/ws/lib/websocket-server.js new file mode 100644 index 0000000..33e0985 --- /dev/null +++ b/backend/node_modules/ws/lib/websocket-server.js @@ -0,0 +1,550 @@ +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex$", "caughtErrors": "none" }] */ + +'use strict'; + +const EventEmitter = require('events'); +const http = require('http'); +const { Duplex } = require('stream'); +const { createHash } = require('crypto'); + +const extension = require('./extension'); +const PerMessageDeflate = require('./permessage-deflate'); +const subprotocol = require('./subprotocol'); +const WebSocket = require('./websocket'); +const { GUID, kWebSocket } = require('./constants'); + +const keyRegex = /^[+/0-9A-Za-z]{22}==$/; + +const RUNNING = 0; +const CLOSING = 1; +const CLOSED = 2; + +/** + * Class representing a WebSocket server. + * + * @extends EventEmitter + */ +class WebSocketServer extends EventEmitter { + /** + * Create a `WebSocketServer` instance. + * + * @param {Object} options Configuration options + * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether + * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted + * multiple times in the same tick + * @param {Boolean} [options.autoPong=true] Specifies whether or not to + * automatically send a pong in response to a ping + * @param {Number} [options.backlog=511] The maximum length of the queue of + * pending connections + * @param {Boolean} [options.clientTracking=true] Specifies whether or not to + * track clients + * @param {Function} [options.handleProtocols] A hook to handle protocols + * @param {String} [options.host] The hostname where to bind the server + * @param {Number} [options.maxPayload=104857600] The maximum allowed message + * size + * @param {Boolean} [options.noServer=false] Enable no server mode + * @param {String} [options.path] Accept only connections matching this path + * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable + * permessage-deflate + * @param {Number} [options.port] The port where to bind the server + * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S + * server to use + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + * @param {Function} [options.verifyClient] A hook to reject connections + * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket` + * class to use. It must be the `WebSocket` class or class that extends it + * @param {Function} [callback] A listener for the `listening` event + */ + constructor(options, callback) { + super(); + + options = { + allowSynchronousEvents: true, + autoPong: true, + maxPayload: 100 * 1024 * 1024, + skipUTF8Validation: false, + perMessageDeflate: false, + handleProtocols: null, + clientTracking: true, + verifyClient: null, + noServer: false, + backlog: null, // use default (511 as implemented in net.js) + server: null, + host: null, + path: null, + port: null, + WebSocket, + ...options + }; + + if ( + (options.port == null && !options.server && !options.noServer) || + (options.port != null && (options.server || options.noServer)) || + (options.server && options.noServer) + ) { + throw new TypeError( + 'One and only one of the "port", "server", or "noServer" options ' + + 'must be specified' + ); + } + + if (options.port != null) { + this._server = http.createServer((req, res) => { + const body = http.STATUS_CODES[426]; + + res.writeHead(426, { + 'Content-Length': body.length, + 'Content-Type': 'text/plain' + }); + res.end(body); + }); + this._server.listen( + options.port, + options.host, + options.backlog, + callback + ); + } else if (options.server) { + this._server = options.server; + } + + if (this._server) { + const emitConnection = this.emit.bind(this, 'connection'); + + this._removeListeners = addListeners(this._server, { + listening: this.emit.bind(this, 'listening'), + error: this.emit.bind(this, 'error'), + upgrade: (req, socket, head) => { + this.handleUpgrade(req, socket, head, emitConnection); + } + }); + } + + if (options.perMessageDeflate === true) options.perMessageDeflate = {}; + if (options.clientTracking) { + this.clients = new Set(); + this._shouldEmitClose = false; + } + + this.options = options; + this._state = RUNNING; + } + + /** + * Returns the bound address, the address family name, and port of the server + * as reported by the operating system if listening on an IP socket. + * If the server is listening on a pipe or UNIX domain socket, the name is + * returned as a string. + * + * @return {(Object|String|null)} The address of the server + * @public + */ + address() { + if (this.options.noServer) { + throw new Error('The server is operating in "noServer" mode'); + } + + if (!this._server) return null; + return this._server.address(); + } + + /** + * Stop the server from accepting new connections and emit the `'close'` event + * when all existing connections are closed. + * + * @param {Function} [cb] A one-time listener for the `'close'` event + * @public + */ + close(cb) { + if (this._state === CLOSED) { + if (cb) { + this.once('close', () => { + cb(new Error('The server is not running')); + }); + } + + process.nextTick(emitClose, this); + return; + } + + if (cb) this.once('close', cb); + + if (this._state === CLOSING) return; + this._state = CLOSING; + + if (this.options.noServer || this.options.server) { + if (this._server) { + this._removeListeners(); + this._removeListeners = this._server = null; + } + + if (this.clients) { + if (!this.clients.size) { + process.nextTick(emitClose, this); + } else { + this._shouldEmitClose = true; + } + } else { + process.nextTick(emitClose, this); + } + } else { + const server = this._server; + + this._removeListeners(); + this._removeListeners = this._server = null; + + // + // The HTTP/S server was created internally. Close it, and rely on its + // `'close'` event. + // + server.close(() => { + emitClose(this); + }); + } + } + + /** + * See if a given request should be handled by this server instance. + * + * @param {http.IncomingMessage} req Request object to inspect + * @return {Boolean} `true` if the request is valid, else `false` + * @public + */ + shouldHandle(req) { + if (this.options.path) { + const index = req.url.indexOf('?'); + const pathname = index !== -1 ? req.url.slice(0, index) : req.url; + + if (pathname !== this.options.path) return false; + } + + return true; + } + + /** + * Handle a HTTP Upgrade request. + * + * @param {http.IncomingMessage} req The request object + * @param {Duplex} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Function} cb Callback + * @public + */ + handleUpgrade(req, socket, head, cb) { + socket.on('error', socketOnError); + + const key = req.headers['sec-websocket-key']; + const upgrade = req.headers.upgrade; + const version = +req.headers['sec-websocket-version']; + + if (req.method !== 'GET') { + const message = 'Invalid HTTP method'; + abortHandshakeOrEmitwsClientError(this, req, socket, 405, message); + return; + } + + if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') { + const message = 'Invalid Upgrade header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + + if (key === undefined || !keyRegex.test(key)) { + const message = 'Missing or invalid Sec-WebSocket-Key header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + + if (version !== 13 && version !== 8) { + const message = 'Missing or invalid Sec-WebSocket-Version header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, { + 'Sec-WebSocket-Version': '13, 8' + }); + return; + } + + if (!this.shouldHandle(req)) { + abortHandshake(socket, 400); + return; + } + + const secWebSocketProtocol = req.headers['sec-websocket-protocol']; + let protocols = new Set(); + + if (secWebSocketProtocol !== undefined) { + try { + protocols = subprotocol.parse(secWebSocketProtocol); + } catch (err) { + const message = 'Invalid Sec-WebSocket-Protocol header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + } + + const secWebSocketExtensions = req.headers['sec-websocket-extensions']; + const extensions = {}; + + if ( + this.options.perMessageDeflate && + secWebSocketExtensions !== undefined + ) { + const perMessageDeflate = new PerMessageDeflate( + this.options.perMessageDeflate, + true, + this.options.maxPayload + ); + + try { + const offers = extension.parse(secWebSocketExtensions); + + if (offers[PerMessageDeflate.extensionName]) { + perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]); + extensions[PerMessageDeflate.extensionName] = perMessageDeflate; + } + } catch (err) { + const message = + 'Invalid or unacceptable Sec-WebSocket-Extensions header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + } + + // + // Optionally call external client verification handler. + // + if (this.options.verifyClient) { + const info = { + origin: + req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`], + secure: !!(req.socket.authorized || req.socket.encrypted), + req + }; + + if (this.options.verifyClient.length === 2) { + this.options.verifyClient(info, (verified, code, message, headers) => { + if (!verified) { + return abortHandshake(socket, code || 401, message, headers); + } + + this.completeUpgrade( + extensions, + key, + protocols, + req, + socket, + head, + cb + ); + }); + return; + } + + if (!this.options.verifyClient(info)) return abortHandshake(socket, 401); + } + + this.completeUpgrade(extensions, key, protocols, req, socket, head, cb); + } + + /** + * Upgrade the connection to WebSocket. + * + * @param {Object} extensions The accepted extensions + * @param {String} key The value of the `Sec-WebSocket-Key` header + * @param {Set} protocols The subprotocols + * @param {http.IncomingMessage} req The request object + * @param {Duplex} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Function} cb Callback + * @throws {Error} If called more than once with the same socket + * @private + */ + completeUpgrade(extensions, key, protocols, req, socket, head, cb) { + // + // Destroy the socket if the client has already sent a FIN packet. + // + if (!socket.readable || !socket.writable) return socket.destroy(); + + if (socket[kWebSocket]) { + throw new Error( + 'server.handleUpgrade() was called more than once with the same ' + + 'socket, possibly due to a misconfiguration' + ); + } + + if (this._state > RUNNING) return abortHandshake(socket, 503); + + const digest = createHash('sha1') + .update(key + GUID) + .digest('base64'); + + const headers = [ + 'HTTP/1.1 101 Switching Protocols', + 'Upgrade: websocket', + 'Connection: Upgrade', + `Sec-WebSocket-Accept: ${digest}` + ]; + + const ws = new this.options.WebSocket(null, undefined, this.options); + + if (protocols.size) { + // + // Optionally call external protocol selection handler. + // + const protocol = this.options.handleProtocols + ? this.options.handleProtocols(protocols, req) + : protocols.values().next().value; + + if (protocol) { + headers.push(`Sec-WebSocket-Protocol: ${protocol}`); + ws._protocol = protocol; + } + } + + if (extensions[PerMessageDeflate.extensionName]) { + const params = extensions[PerMessageDeflate.extensionName].params; + const value = extension.format({ + [PerMessageDeflate.extensionName]: [params] + }); + headers.push(`Sec-WebSocket-Extensions: ${value}`); + ws._extensions = extensions; + } + + // + // Allow external modification/inspection of handshake headers. + // + this.emit('headers', headers, req); + + socket.write(headers.concat('\r\n').join('\r\n')); + socket.removeListener('error', socketOnError); + + ws.setSocket(socket, head, { + allowSynchronousEvents: this.options.allowSynchronousEvents, + maxPayload: this.options.maxPayload, + skipUTF8Validation: this.options.skipUTF8Validation + }); + + if (this.clients) { + this.clients.add(ws); + ws.on('close', () => { + this.clients.delete(ws); + + if (this._shouldEmitClose && !this.clients.size) { + process.nextTick(emitClose, this); + } + }); + } + + cb(ws, req); + } +} + +module.exports = WebSocketServer; + +/** + * Add event listeners on an `EventEmitter` using a map of + * pairs. + * + * @param {EventEmitter} server The event emitter + * @param {Object.} map The listeners to add + * @return {Function} A function that will remove the added listeners when + * called + * @private + */ +function addListeners(server, map) { + for (const event of Object.keys(map)) server.on(event, map[event]); + + return function removeListeners() { + for (const event of Object.keys(map)) { + server.removeListener(event, map[event]); + } + }; +} + +/** + * Emit a `'close'` event on an `EventEmitter`. + * + * @param {EventEmitter} server The event emitter + * @private + */ +function emitClose(server) { + server._state = CLOSED; + server.emit('close'); +} + +/** + * Handle socket errors. + * + * @private + */ +function socketOnError() { + this.destroy(); +} + +/** + * Close the connection when preconditions are not fulfilled. + * + * @param {Duplex} socket The socket of the upgrade request + * @param {Number} code The HTTP response status code + * @param {String} [message] The HTTP response body + * @param {Object} [headers] Additional HTTP response headers + * @private + */ +function abortHandshake(socket, code, message, headers) { + // + // The socket is writable unless the user destroyed or ended it before calling + // `server.handleUpgrade()` or in the `verifyClient` function, which is a user + // error. Handling this does not make much sense as the worst that can happen + // is that some of the data written by the user might be discarded due to the + // call to `socket.end()` below, which triggers an `'error'` event that in + // turn causes the socket to be destroyed. + // + message = message || http.STATUS_CODES[code]; + headers = { + Connection: 'close', + 'Content-Type': 'text/html', + 'Content-Length': Buffer.byteLength(message), + ...headers + }; + + socket.once('finish', socket.destroy); + + socket.end( + `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` + + Object.keys(headers) + .map((h) => `${h}: ${headers[h]}`) + .join('\r\n') + + '\r\n\r\n' + + message + ); +} + +/** + * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least + * one listener for it, otherwise call `abortHandshake()`. + * + * @param {WebSocketServer} server The WebSocket server + * @param {http.IncomingMessage} req The request object + * @param {Duplex} socket The socket of the upgrade request + * @param {Number} code The HTTP response status code + * @param {String} message The HTTP response body + * @param {Object} [headers] The HTTP response headers + * @private + */ +function abortHandshakeOrEmitwsClientError( + server, + req, + socket, + code, + message, + headers +) { + if (server.listenerCount('wsClientError')) { + const err = new Error(message); + Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError); + + server.emit('wsClientError', err, socket, req); + } else { + abortHandshake(socket, code, message, headers); + } +} diff --git a/backend/node_modules/ws/lib/websocket.js b/backend/node_modules/ws/lib/websocket.js new file mode 100644 index 0000000..ad8764a --- /dev/null +++ b/backend/node_modules/ws/lib/websocket.js @@ -0,0 +1,1388 @@ +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex|Readable$", "caughtErrors": "none" }] */ + +'use strict'; + +const EventEmitter = require('events'); +const https = require('https'); +const http = require('http'); +const net = require('net'); +const tls = require('tls'); +const { randomBytes, createHash } = require('crypto'); +const { Duplex, Readable } = require('stream'); +const { URL } = require('url'); + +const PerMessageDeflate = require('./permessage-deflate'); +const Receiver = require('./receiver'); +const Sender = require('./sender'); +const { isBlob } = require('./validation'); + +const { + BINARY_TYPES, + EMPTY_BUFFER, + GUID, + kForOnEventAttribute, + kListener, + kStatusCode, + kWebSocket, + NOOP +} = require('./constants'); +const { + EventTarget: { addEventListener, removeEventListener } +} = require('./event-target'); +const { format, parse } = require('./extension'); +const { toBuffer } = require('./buffer-util'); + +const closeTimeout = 30 * 1000; +const kAborted = Symbol('kAborted'); +const protocolVersions = [8, 13]; +const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED']; +const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/; + +/** + * Class representing a WebSocket. + * + * @extends EventEmitter + */ +class WebSocket extends EventEmitter { + /** + * Create a new `WebSocket`. + * + * @param {(String|URL)} address The URL to which to connect + * @param {(String|String[])} [protocols] The subprotocols + * @param {Object} [options] Connection options + */ + constructor(address, protocols, options) { + super(); + + this._binaryType = BINARY_TYPES[0]; + this._closeCode = 1006; + this._closeFrameReceived = false; + this._closeFrameSent = false; + this._closeMessage = EMPTY_BUFFER; + this._closeTimer = null; + this._errorEmitted = false; + this._extensions = {}; + this._paused = false; + this._protocol = ''; + this._readyState = WebSocket.CONNECTING; + this._receiver = null; + this._sender = null; + this._socket = null; + + if (address !== null) { + this._bufferedAmount = 0; + this._isServer = false; + this._redirects = 0; + + if (protocols === undefined) { + protocols = []; + } else if (!Array.isArray(protocols)) { + if (typeof protocols === 'object' && protocols !== null) { + options = protocols; + protocols = []; + } else { + protocols = [protocols]; + } + } + + initAsClient(this, address, protocols, options); + } else { + this._autoPong = options.autoPong; + this._isServer = true; + } + } + + /** + * For historical reasons, the custom "nodebuffer" type is used by the default + * instead of "blob". + * + * @type {String} + */ + get binaryType() { + return this._binaryType; + } + + set binaryType(type) { + if (!BINARY_TYPES.includes(type)) return; + + this._binaryType = type; + + // + // Allow to change `binaryType` on the fly. + // + if (this._receiver) this._receiver._binaryType = type; + } + + /** + * @type {Number} + */ + get bufferedAmount() { + if (!this._socket) return this._bufferedAmount; + + return this._socket._writableState.length + this._sender._bufferedBytes; + } + + /** + * @type {String} + */ + get extensions() { + return Object.keys(this._extensions).join(); + } + + /** + * @type {Boolean} + */ + get isPaused() { + return this._paused; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onclose() { + return null; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onerror() { + return null; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onopen() { + return null; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onmessage() { + return null; + } + + /** + * @type {String} + */ + get protocol() { + return this._protocol; + } + + /** + * @type {Number} + */ + get readyState() { + return this._readyState; + } + + /** + * @type {String} + */ + get url() { + return this._url; + } + + /** + * Set up the socket and the internal resources. + * + * @param {Duplex} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Object} options Options object + * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether + * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted + * multiple times in the same tick + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Number} [options.maxPayload=0] The maximum allowed message size + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + * @private + */ + setSocket(socket, head, options) { + const receiver = new Receiver({ + allowSynchronousEvents: options.allowSynchronousEvents, + binaryType: this.binaryType, + extensions: this._extensions, + isServer: this._isServer, + maxPayload: options.maxPayload, + skipUTF8Validation: options.skipUTF8Validation + }); + + const sender = new Sender(socket, this._extensions, options.generateMask); + + this._receiver = receiver; + this._sender = sender; + this._socket = socket; + + receiver[kWebSocket] = this; + sender[kWebSocket] = this; + socket[kWebSocket] = this; + + receiver.on('conclude', receiverOnConclude); + receiver.on('drain', receiverOnDrain); + receiver.on('error', receiverOnError); + receiver.on('message', receiverOnMessage); + receiver.on('ping', receiverOnPing); + receiver.on('pong', receiverOnPong); + + sender.onerror = senderOnError; + + // + // These methods may not be available if `socket` is just a `Duplex`. + // + if (socket.setTimeout) socket.setTimeout(0); + if (socket.setNoDelay) socket.setNoDelay(); + + if (head.length > 0) socket.unshift(head); + + socket.on('close', socketOnClose); + socket.on('data', socketOnData); + socket.on('end', socketOnEnd); + socket.on('error', socketOnError); + + this._readyState = WebSocket.OPEN; + this.emit('open'); + } + + /** + * Emit the `'close'` event. + * + * @private + */ + emitClose() { + if (!this._socket) { + this._readyState = WebSocket.CLOSED; + this.emit('close', this._closeCode, this._closeMessage); + return; + } + + if (this._extensions[PerMessageDeflate.extensionName]) { + this._extensions[PerMessageDeflate.extensionName].cleanup(); + } + + this._receiver.removeAllListeners(); + this._readyState = WebSocket.CLOSED; + this.emit('close', this._closeCode, this._closeMessage); + } + + /** + * Start a closing handshake. + * + * +----------+ +-----------+ +----------+ + * - - -|ws.close()|-->|close frame|-->|ws.close()|- - - + * | +----------+ +-----------+ +----------+ | + * +----------+ +-----------+ | + * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING + * +----------+ +-----------+ | + * | | | +---+ | + * +------------------------+-->|fin| - - - - + * | +---+ | +---+ + * - - - - -|fin|<---------------------+ + * +---+ + * + * @param {Number} [code] Status code explaining why the connection is closing + * @param {(String|Buffer)} [data] The reason why the connection is + * closing + * @public + */ + close(code, data) { + if (this.readyState === WebSocket.CLOSED) return; + if (this.readyState === WebSocket.CONNECTING) { + const msg = 'WebSocket was closed before the connection was established'; + abortHandshake(this, this._req, msg); + return; + } + + if (this.readyState === WebSocket.CLOSING) { + if ( + this._closeFrameSent && + (this._closeFrameReceived || this._receiver._writableState.errorEmitted) + ) { + this._socket.end(); + } + + return; + } + + this._readyState = WebSocket.CLOSING; + this._sender.close(code, data, !this._isServer, (err) => { + // + // This error is handled by the `'error'` listener on the socket. We only + // want to know if the close frame has been sent here. + // + if (err) return; + + this._closeFrameSent = true; + + if ( + this._closeFrameReceived || + this._receiver._writableState.errorEmitted + ) { + this._socket.end(); + } + }); + + setCloseTimer(this); + } + + /** + * Pause the socket. + * + * @public + */ + pause() { + if ( + this.readyState === WebSocket.CONNECTING || + this.readyState === WebSocket.CLOSED + ) { + return; + } + + this._paused = true; + this._socket.pause(); + } + + /** + * Send a ping. + * + * @param {*} [data] The data to send + * @param {Boolean} [mask] Indicates whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when the ping is sent + * @public + */ + ping(data, mask, cb) { + if (this.readyState === WebSocket.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof data === 'function') { + cb = data; + data = mask = undefined; + } else if (typeof mask === 'function') { + cb = mask; + mask = undefined; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + if (mask === undefined) mask = !this._isServer; + this._sender.ping(data || EMPTY_BUFFER, mask, cb); + } + + /** + * Send a pong. + * + * @param {*} [data] The data to send + * @param {Boolean} [mask] Indicates whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when the pong is sent + * @public + */ + pong(data, mask, cb) { + if (this.readyState === WebSocket.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof data === 'function') { + cb = data; + data = mask = undefined; + } else if (typeof mask === 'function') { + cb = mask; + mask = undefined; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + if (mask === undefined) mask = !this._isServer; + this._sender.pong(data || EMPTY_BUFFER, mask, cb); + } + + /** + * Resume the socket. + * + * @public + */ + resume() { + if ( + this.readyState === WebSocket.CONNECTING || + this.readyState === WebSocket.CLOSED + ) { + return; + } + + this._paused = false; + if (!this._receiver._writableState.needDrain) this._socket.resume(); + } + + /** + * Send a data message. + * + * @param {*} data The message to send + * @param {Object} [options] Options object + * @param {Boolean} [options.binary] Specifies whether `data` is binary or + * text + * @param {Boolean} [options.compress] Specifies whether or not to compress + * `data` + * @param {Boolean} [options.fin=true] Specifies whether the fragment is the + * last one + * @param {Boolean} [options.mask] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when data is written out + * @public + */ + send(data, options, cb) { + if (this.readyState === WebSocket.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof options === 'function') { + cb = options; + options = {}; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + const opts = { + binary: typeof data !== 'string', + mask: !this._isServer, + compress: true, + fin: true, + ...options + }; + + if (!this._extensions[PerMessageDeflate.extensionName]) { + opts.compress = false; + } + + this._sender.send(data || EMPTY_BUFFER, opts, cb); + } + + /** + * Forcibly close the connection. + * + * @public + */ + terminate() { + if (this.readyState === WebSocket.CLOSED) return; + if (this.readyState === WebSocket.CONNECTING) { + const msg = 'WebSocket was closed before the connection was established'; + abortHandshake(this, this._req, msg); + return; + } + + if (this._socket) { + this._readyState = WebSocket.CLOSING; + this._socket.destroy(); + } + } +} + +/** + * @constant {Number} CONNECTING + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'CONNECTING', { + enumerable: true, + value: readyStates.indexOf('CONNECTING') +}); + +/** + * @constant {Number} CONNECTING + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'CONNECTING', { + enumerable: true, + value: readyStates.indexOf('CONNECTING') +}); + +/** + * @constant {Number} OPEN + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'OPEN', { + enumerable: true, + value: readyStates.indexOf('OPEN') +}); + +/** + * @constant {Number} OPEN + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'OPEN', { + enumerable: true, + value: readyStates.indexOf('OPEN') +}); + +/** + * @constant {Number} CLOSING + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'CLOSING', { + enumerable: true, + value: readyStates.indexOf('CLOSING') +}); + +/** + * @constant {Number} CLOSING + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'CLOSING', { + enumerable: true, + value: readyStates.indexOf('CLOSING') +}); + +/** + * @constant {Number} CLOSED + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'CLOSED', { + enumerable: true, + value: readyStates.indexOf('CLOSED') +}); + +/** + * @constant {Number} CLOSED + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'CLOSED', { + enumerable: true, + value: readyStates.indexOf('CLOSED') +}); + +[ + 'binaryType', + 'bufferedAmount', + 'extensions', + 'isPaused', + 'protocol', + 'readyState', + 'url' +].forEach((property) => { + Object.defineProperty(WebSocket.prototype, property, { enumerable: true }); +}); + +// +// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes. +// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface +// +['open', 'error', 'close', 'message'].forEach((method) => { + Object.defineProperty(WebSocket.prototype, `on${method}`, { + enumerable: true, + get() { + for (const listener of this.listeners(method)) { + if (listener[kForOnEventAttribute]) return listener[kListener]; + } + + return null; + }, + set(handler) { + for (const listener of this.listeners(method)) { + if (listener[kForOnEventAttribute]) { + this.removeListener(method, listener); + break; + } + } + + if (typeof handler !== 'function') return; + + this.addEventListener(method, handler, { + [kForOnEventAttribute]: true + }); + } + }); +}); + +WebSocket.prototype.addEventListener = addEventListener; +WebSocket.prototype.removeEventListener = removeEventListener; + +module.exports = WebSocket; + +/** + * Initialize a WebSocket client. + * + * @param {WebSocket} websocket The client to initialize + * @param {(String|URL)} address The URL to which to connect + * @param {Array} protocols The subprotocols + * @param {Object} [options] Connection options + * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether any + * of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple + * times in the same tick + * @param {Boolean} [options.autoPong=true] Specifies whether or not to + * automatically send a pong in response to a ping + * @param {Function} [options.finishRequest] A function which can be used to + * customize the headers of each http request before it is sent + * @param {Boolean} [options.followRedirects=false] Whether or not to follow + * redirects + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the + * handshake request + * @param {Number} [options.maxPayload=104857600] The maximum allowed message + * size + * @param {Number} [options.maxRedirects=10] The maximum number of redirects + * allowed + * @param {String} [options.origin] Value of the `Origin` or + * `Sec-WebSocket-Origin` header + * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable + * permessage-deflate + * @param {Number} [options.protocolVersion=13] Value of the + * `Sec-WebSocket-Version` header + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + * @private + */ +function initAsClient(websocket, address, protocols, options) { + const opts = { + allowSynchronousEvents: true, + autoPong: true, + protocolVersion: protocolVersions[1], + maxPayload: 100 * 1024 * 1024, + skipUTF8Validation: false, + perMessageDeflate: true, + followRedirects: false, + maxRedirects: 10, + ...options, + socketPath: undefined, + hostname: undefined, + protocol: undefined, + timeout: undefined, + method: 'GET', + host: undefined, + path: undefined, + port: undefined + }; + + websocket._autoPong = opts.autoPong; + + if (!protocolVersions.includes(opts.protocolVersion)) { + throw new RangeError( + `Unsupported protocol version: ${opts.protocolVersion} ` + + `(supported versions: ${protocolVersions.join(', ')})` + ); + } + + let parsedUrl; + + if (address instanceof URL) { + parsedUrl = address; + } else { + try { + parsedUrl = new URL(address); + } catch (e) { + throw new SyntaxError(`Invalid URL: ${address}`); + } + } + + if (parsedUrl.protocol === 'http:') { + parsedUrl.protocol = 'ws:'; + } else if (parsedUrl.protocol === 'https:') { + parsedUrl.protocol = 'wss:'; + } + + websocket._url = parsedUrl.href; + + const isSecure = parsedUrl.protocol === 'wss:'; + const isIpcUrl = parsedUrl.protocol === 'ws+unix:'; + let invalidUrlMessage; + + if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) { + invalidUrlMessage = + 'The URL\'s protocol must be one of "ws:", "wss:", ' + + '"http:", "https:", or "ws+unix:"'; + } else if (isIpcUrl && !parsedUrl.pathname) { + invalidUrlMessage = "The URL's pathname is empty"; + } else if (parsedUrl.hash) { + invalidUrlMessage = 'The URL contains a fragment identifier'; + } + + if (invalidUrlMessage) { + const err = new SyntaxError(invalidUrlMessage); + + if (websocket._redirects === 0) { + throw err; + } else { + emitErrorAndClose(websocket, err); + return; + } + } + + const defaultPort = isSecure ? 443 : 80; + const key = randomBytes(16).toString('base64'); + const request = isSecure ? https.request : http.request; + const protocolSet = new Set(); + let perMessageDeflate; + + opts.createConnection = + opts.createConnection || (isSecure ? tlsConnect : netConnect); + opts.defaultPort = opts.defaultPort || defaultPort; + opts.port = parsedUrl.port || defaultPort; + opts.host = parsedUrl.hostname.startsWith('[') + ? parsedUrl.hostname.slice(1, -1) + : parsedUrl.hostname; + opts.headers = { + ...opts.headers, + 'Sec-WebSocket-Version': opts.protocolVersion, + 'Sec-WebSocket-Key': key, + Connection: 'Upgrade', + Upgrade: 'websocket' + }; + opts.path = parsedUrl.pathname + parsedUrl.search; + opts.timeout = opts.handshakeTimeout; + + if (opts.perMessageDeflate) { + perMessageDeflate = new PerMessageDeflate( + opts.perMessageDeflate !== true ? opts.perMessageDeflate : {}, + false, + opts.maxPayload + ); + opts.headers['Sec-WebSocket-Extensions'] = format({ + [PerMessageDeflate.extensionName]: perMessageDeflate.offer() + }); + } + if (protocols.length) { + for (const protocol of protocols) { + if ( + typeof protocol !== 'string' || + !subprotocolRegex.test(protocol) || + protocolSet.has(protocol) + ) { + throw new SyntaxError( + 'An invalid or duplicated subprotocol was specified' + ); + } + + protocolSet.add(protocol); + } + + opts.headers['Sec-WebSocket-Protocol'] = protocols.join(','); + } + if (opts.origin) { + if (opts.protocolVersion < 13) { + opts.headers['Sec-WebSocket-Origin'] = opts.origin; + } else { + opts.headers.Origin = opts.origin; + } + } + if (parsedUrl.username || parsedUrl.password) { + opts.auth = `${parsedUrl.username}:${parsedUrl.password}`; + } + + if (isIpcUrl) { + const parts = opts.path.split(':'); + + opts.socketPath = parts[0]; + opts.path = parts[1]; + } + + let req; + + if (opts.followRedirects) { + if (websocket._redirects === 0) { + websocket._originalIpc = isIpcUrl; + websocket._originalSecure = isSecure; + websocket._originalHostOrSocketPath = isIpcUrl + ? opts.socketPath + : parsedUrl.host; + + const headers = options && options.headers; + + // + // Shallow copy the user provided options so that headers can be changed + // without mutating the original object. + // + options = { ...options, headers: {} }; + + if (headers) { + for (const [key, value] of Object.entries(headers)) { + options.headers[key.toLowerCase()] = value; + } + } + } else if (websocket.listenerCount('redirect') === 0) { + const isSameHost = isIpcUrl + ? websocket._originalIpc + ? opts.socketPath === websocket._originalHostOrSocketPath + : false + : websocket._originalIpc + ? false + : parsedUrl.host === websocket._originalHostOrSocketPath; + + if (!isSameHost || (websocket._originalSecure && !isSecure)) { + // + // Match curl 7.77.0 behavior and drop the following headers. These + // headers are also dropped when following a redirect to a subdomain. + // + delete opts.headers.authorization; + delete opts.headers.cookie; + + if (!isSameHost) delete opts.headers.host; + + opts.auth = undefined; + } + } + + // + // Match curl 7.77.0 behavior and make the first `Authorization` header win. + // If the `Authorization` header is set, then there is nothing to do as it + // will take precedence. + // + if (opts.auth && !options.headers.authorization) { + options.headers.authorization = + 'Basic ' + Buffer.from(opts.auth).toString('base64'); + } + + req = websocket._req = request(opts); + + if (websocket._redirects) { + // + // Unlike what is done for the `'upgrade'` event, no early exit is + // triggered here if the user calls `websocket.close()` or + // `websocket.terminate()` from a listener of the `'redirect'` event. This + // is because the user can also call `request.destroy()` with an error + // before calling `websocket.close()` or `websocket.terminate()` and this + // would result in an error being emitted on the `request` object with no + // `'error'` event listeners attached. + // + websocket.emit('redirect', websocket.url, req); + } + } else { + req = websocket._req = request(opts); + } + + if (opts.timeout) { + req.on('timeout', () => { + abortHandshake(websocket, req, 'Opening handshake has timed out'); + }); + } + + req.on('error', (err) => { + if (req === null || req[kAborted]) return; + + req = websocket._req = null; + emitErrorAndClose(websocket, err); + }); + + req.on('response', (res) => { + const location = res.headers.location; + const statusCode = res.statusCode; + + if ( + location && + opts.followRedirects && + statusCode >= 300 && + statusCode < 400 + ) { + if (++websocket._redirects > opts.maxRedirects) { + abortHandshake(websocket, req, 'Maximum redirects exceeded'); + return; + } + + req.abort(); + + let addr; + + try { + addr = new URL(location, address); + } catch (e) { + const err = new SyntaxError(`Invalid URL: ${location}`); + emitErrorAndClose(websocket, err); + return; + } + + initAsClient(websocket, addr, protocols, options); + } else if (!websocket.emit('unexpected-response', req, res)) { + abortHandshake( + websocket, + req, + `Unexpected server response: ${res.statusCode}` + ); + } + }); + + req.on('upgrade', (res, socket, head) => { + websocket.emit('upgrade', res); + + // + // The user may have closed the connection from a listener of the + // `'upgrade'` event. + // + if (websocket.readyState !== WebSocket.CONNECTING) return; + + req = websocket._req = null; + + const upgrade = res.headers.upgrade; + + if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') { + abortHandshake(websocket, socket, 'Invalid Upgrade header'); + return; + } + + const digest = createHash('sha1') + .update(key + GUID) + .digest('base64'); + + if (res.headers['sec-websocket-accept'] !== digest) { + abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header'); + return; + } + + const serverProt = res.headers['sec-websocket-protocol']; + let protError; + + if (serverProt !== undefined) { + if (!protocolSet.size) { + protError = 'Server sent a subprotocol but none was requested'; + } else if (!protocolSet.has(serverProt)) { + protError = 'Server sent an invalid subprotocol'; + } + } else if (protocolSet.size) { + protError = 'Server sent no subprotocol'; + } + + if (protError) { + abortHandshake(websocket, socket, protError); + return; + } + + if (serverProt) websocket._protocol = serverProt; + + const secWebSocketExtensions = res.headers['sec-websocket-extensions']; + + if (secWebSocketExtensions !== undefined) { + if (!perMessageDeflate) { + const message = + 'Server sent a Sec-WebSocket-Extensions header but no extension ' + + 'was requested'; + abortHandshake(websocket, socket, message); + return; + } + + let extensions; + + try { + extensions = parse(secWebSocketExtensions); + } catch (err) { + const message = 'Invalid Sec-WebSocket-Extensions header'; + abortHandshake(websocket, socket, message); + return; + } + + const extensionNames = Object.keys(extensions); + + if ( + extensionNames.length !== 1 || + extensionNames[0] !== PerMessageDeflate.extensionName + ) { + const message = 'Server indicated an extension that was not requested'; + abortHandshake(websocket, socket, message); + return; + } + + try { + perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]); + } catch (err) { + const message = 'Invalid Sec-WebSocket-Extensions header'; + abortHandshake(websocket, socket, message); + return; + } + + websocket._extensions[PerMessageDeflate.extensionName] = + perMessageDeflate; + } + + websocket.setSocket(socket, head, { + allowSynchronousEvents: opts.allowSynchronousEvents, + generateMask: opts.generateMask, + maxPayload: opts.maxPayload, + skipUTF8Validation: opts.skipUTF8Validation + }); + }); + + if (opts.finishRequest) { + opts.finishRequest(req, websocket); + } else { + req.end(); + } +} + +/** + * Emit the `'error'` and `'close'` events. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {Error} The error to emit + * @private + */ +function emitErrorAndClose(websocket, err) { + websocket._readyState = WebSocket.CLOSING; + // + // The following assignment is practically useless and is done only for + // consistency. + // + websocket._errorEmitted = true; + websocket.emit('error', err); + websocket.emitClose(); +} + +/** + * Create a `net.Socket` and initiate a connection. + * + * @param {Object} options Connection options + * @return {net.Socket} The newly created socket used to start the connection + * @private + */ +function netConnect(options) { + options.path = options.socketPath; + return net.connect(options); +} + +/** + * Create a `tls.TLSSocket` and initiate a connection. + * + * @param {Object} options Connection options + * @return {tls.TLSSocket} The newly created socket used to start the connection + * @private + */ +function tlsConnect(options) { + options.path = undefined; + + if (!options.servername && options.servername !== '') { + options.servername = net.isIP(options.host) ? '' : options.host; + } + + return tls.connect(options); +} + +/** + * Abort the handshake and emit an error. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to + * abort or the socket to destroy + * @param {String} message The error message + * @private + */ +function abortHandshake(websocket, stream, message) { + websocket._readyState = WebSocket.CLOSING; + + const err = new Error(message); + Error.captureStackTrace(err, abortHandshake); + + if (stream.setHeader) { + stream[kAborted] = true; + stream.abort(); + + if (stream.socket && !stream.socket.destroyed) { + // + // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if + // called after the request completed. See + // https://github.com/websockets/ws/issues/1869. + // + stream.socket.destroy(); + } + + process.nextTick(emitErrorAndClose, websocket, err); + } else { + stream.destroy(err); + stream.once('error', websocket.emit.bind(websocket, 'error')); + stream.once('close', websocket.emitClose.bind(websocket)); + } +} + +/** + * Handle cases where the `ping()`, `pong()`, or `send()` methods are called + * when the `readyState` attribute is `CLOSING` or `CLOSED`. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {*} [data] The data to send + * @param {Function} [cb] Callback + * @private + */ +function sendAfterClose(websocket, data, cb) { + if (data) { + const length = isBlob(data) ? data.size : toBuffer(data).length; + + // + // The `_bufferedAmount` property is used only when the peer is a client and + // the opening handshake fails. Under these circumstances, in fact, the + // `setSocket()` method is not called, so the `_socket` and `_sender` + // properties are set to `null`. + // + if (websocket._socket) websocket._sender._bufferedBytes += length; + else websocket._bufferedAmount += length; + } + + if (cb) { + const err = new Error( + `WebSocket is not open: readyState ${websocket.readyState} ` + + `(${readyStates[websocket.readyState]})` + ); + process.nextTick(cb, err); + } +} + +/** + * The listener of the `Receiver` `'conclude'` event. + * + * @param {Number} code The status code + * @param {Buffer} reason The reason for closing + * @private + */ +function receiverOnConclude(code, reason) { + const websocket = this[kWebSocket]; + + websocket._closeFrameReceived = true; + websocket._closeMessage = reason; + websocket._closeCode = code; + + if (websocket._socket[kWebSocket] === undefined) return; + + websocket._socket.removeListener('data', socketOnData); + process.nextTick(resume, websocket._socket); + + if (code === 1005) websocket.close(); + else websocket.close(code, reason); +} + +/** + * The listener of the `Receiver` `'drain'` event. + * + * @private + */ +function receiverOnDrain() { + const websocket = this[kWebSocket]; + + if (!websocket.isPaused) websocket._socket.resume(); +} + +/** + * The listener of the `Receiver` `'error'` event. + * + * @param {(RangeError|Error)} err The emitted error + * @private + */ +function receiverOnError(err) { + const websocket = this[kWebSocket]; + + if (websocket._socket[kWebSocket] !== undefined) { + websocket._socket.removeListener('data', socketOnData); + + // + // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See + // https://github.com/websockets/ws/issues/1940. + // + process.nextTick(resume, websocket._socket); + + websocket.close(err[kStatusCode]); + } + + if (!websocket._errorEmitted) { + websocket._errorEmitted = true; + websocket.emit('error', err); + } +} + +/** + * The listener of the `Receiver` `'finish'` event. + * + * @private + */ +function receiverOnFinish() { + this[kWebSocket].emitClose(); +} + +/** + * The listener of the `Receiver` `'message'` event. + * + * @param {Buffer|ArrayBuffer|Buffer[])} data The message + * @param {Boolean} isBinary Specifies whether the message is binary or not + * @private + */ +function receiverOnMessage(data, isBinary) { + this[kWebSocket].emit('message', data, isBinary); +} + +/** + * The listener of the `Receiver` `'ping'` event. + * + * @param {Buffer} data The data included in the ping frame + * @private + */ +function receiverOnPing(data) { + const websocket = this[kWebSocket]; + + if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP); + websocket.emit('ping', data); +} + +/** + * The listener of the `Receiver` `'pong'` event. + * + * @param {Buffer} data The data included in the pong frame + * @private + */ +function receiverOnPong(data) { + this[kWebSocket].emit('pong', data); +} + +/** + * Resume a readable stream + * + * @param {Readable} stream The readable stream + * @private + */ +function resume(stream) { + stream.resume(); +} + +/** + * The `Sender` error event handler. + * + * @param {Error} The error + * @private + */ +function senderOnError(err) { + const websocket = this[kWebSocket]; + + if (websocket.readyState === WebSocket.CLOSED) return; + if (websocket.readyState === WebSocket.OPEN) { + websocket._readyState = WebSocket.CLOSING; + setCloseTimer(websocket); + } + + // + // `socket.end()` is used instead of `socket.destroy()` to allow the other + // peer to finish sending queued data. There is no need to set a timer here + // because `CLOSING` means that it is already set or not needed. + // + this._socket.end(); + + if (!websocket._errorEmitted) { + websocket._errorEmitted = true; + websocket.emit('error', err); + } +} + +/** + * Set a timer to destroy the underlying raw socket of a WebSocket. + * + * @param {WebSocket} websocket The WebSocket instance + * @private + */ +function setCloseTimer(websocket) { + websocket._closeTimer = setTimeout( + websocket._socket.destroy.bind(websocket._socket), + closeTimeout + ); +} + +/** + * The listener of the socket `'close'` event. + * + * @private + */ +function socketOnClose() { + const websocket = this[kWebSocket]; + + this.removeListener('close', socketOnClose); + this.removeListener('data', socketOnData); + this.removeListener('end', socketOnEnd); + + websocket._readyState = WebSocket.CLOSING; + + let chunk; + + // + // The close frame might not have been received or the `'end'` event emitted, + // for example, if the socket was destroyed due to an error. Ensure that the + // `receiver` stream is closed after writing any remaining buffered data to + // it. If the readable side of the socket is in flowing mode then there is no + // buffered data as everything has been already written and `readable.read()` + // will return `null`. If instead, the socket is paused, any possible buffered + // data will be read as a single chunk. + // + if ( + !this._readableState.endEmitted && + !websocket._closeFrameReceived && + !websocket._receiver._writableState.errorEmitted && + (chunk = websocket._socket.read()) !== null + ) { + websocket._receiver.write(chunk); + } + + websocket._receiver.end(); + + this[kWebSocket] = undefined; + + clearTimeout(websocket._closeTimer); + + if ( + websocket._receiver._writableState.finished || + websocket._receiver._writableState.errorEmitted + ) { + websocket.emitClose(); + } else { + websocket._receiver.on('error', receiverOnFinish); + websocket._receiver.on('finish', receiverOnFinish); + } +} + +/** + * The listener of the socket `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function socketOnData(chunk) { + if (!this[kWebSocket]._receiver.write(chunk)) { + this.pause(); + } +} + +/** + * The listener of the socket `'end'` event. + * + * @private + */ +function socketOnEnd() { + const websocket = this[kWebSocket]; + + websocket._readyState = WebSocket.CLOSING; + websocket._receiver.end(); + this.end(); +} + +/** + * The listener of the socket `'error'` event. + * + * @private + */ +function socketOnError() { + const websocket = this[kWebSocket]; + + this.removeListener('error', socketOnError); + this.on('error', NOOP); + + if (websocket) { + websocket._readyState = WebSocket.CLOSING; + this.destroy(); + } +} diff --git a/backend/node_modules/ws/package.json b/backend/node_modules/ws/package.json new file mode 100644 index 0000000..2004b1c --- /dev/null +++ b/backend/node_modules/ws/package.json @@ -0,0 +1,69 @@ +{ + "name": "ws", + "version": "8.18.3", + "description": "Simple to use, blazing fast and thoroughly tested websocket client and server for Node.js", + "keywords": [ + "HyBi", + "Push", + "RFC-6455", + "WebSocket", + "WebSockets", + "real-time" + ], + "homepage": "https://github.com/websockets/ws", + "bugs": "https://github.com/websockets/ws/issues", + "repository": { + "type": "git", + "url": "git+https://github.com/websockets/ws.git" + }, + "author": "Einar Otto Stangvik (http://2x.io)", + "license": "MIT", + "main": "index.js", + "exports": { + ".": { + "browser": "./browser.js", + "import": "./wrapper.mjs", + "require": "./index.js" + }, + "./package.json": "./package.json" + }, + "browser": "browser.js", + "engines": { + "node": ">=10.0.0" + }, + "files": [ + "browser.js", + "index.js", + "lib/*.js", + "wrapper.mjs" + ], + "scripts": { + "test": "nyc --reporter=lcov --reporter=text mocha --throw-deprecation test/*.test.js", + "integration": "mocha --throw-deprecation test/*.integration.js", + "lint": "eslint . && prettier --check --ignore-path .gitignore \"**/*.{json,md,yaml,yml}\"" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + }, + "devDependencies": { + "benchmark": "^2.1.4", + "bufferutil": "^4.0.1", + "eslint": "^9.0.0", + "eslint-config-prettier": "^10.0.1", + "eslint-plugin-prettier": "^5.0.0", + "globals": "^16.0.0", + "mocha": "^8.4.0", + "nyc": "^15.0.0", + "prettier": "^3.0.0", + "utf-8-validate": "^6.0.0" + } +} diff --git a/backend/node_modules/ws/wrapper.mjs b/backend/node_modules/ws/wrapper.mjs new file mode 100644 index 0000000..7245ad1 --- /dev/null +++ b/backend/node_modules/ws/wrapper.mjs @@ -0,0 +1,8 @@ +import createWebSocketStream from './lib/stream.js'; +import Receiver from './lib/receiver.js'; +import Sender from './lib/sender.js'; +import WebSocket from './lib/websocket.js'; +import WebSocketServer from './lib/websocket-server.js'; + +export { createWebSocketStream, Receiver, Sender, WebSocket, WebSocketServer }; +export default WebSocket; diff --git a/backend/package-lock.json b/backend/package-lock.json new file mode 100644 index 0000000..6affc9a --- /dev/null +++ b/backend/package-lock.json @@ -0,0 +1,1012 @@ +{ + "name": "backend", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "backend", + "version": "1.0.0", + "license": "ISC", + "dependencies": { + "@supabase/supabase-js": "^2.87.1", + "cors": "^2.8.5", + "dotenv": "^17.2.3", + "express": "^5.2.1", + "nodemailer": "^7.0.11" + } + }, + "node_modules/@supabase/auth-js": { + "version": "2.87.1", + "resolved": "https://registry.npmjs.org/@supabase/auth-js/-/auth-js-2.87.1.tgz", + "integrity": "sha512-6RDeOf5TVoaXFtEstN188ykp3pXLZaU9qoAWfx8dc50FFAAqt+kcFJ96V0IvSmcpb4mDAWcpTJ7BegmVDn/WIw==", + "license": "MIT", + "dependencies": { + "tslib": "2.8.1" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@supabase/functions-js": { + "version": "2.87.1", + "resolved": "https://registry.npmjs.org/@supabase/functions-js/-/functions-js-2.87.1.tgz", + "integrity": "sha512-rWmYo4gRD0XAjMhYDlz7IH67bp4TIQ1UE4VqwIQtl1gGPwtLDq6wcRnu7jLKlXx0Gtrknw/eoiHYG9//XrCTzQ==", + "license": "MIT", + "dependencies": { + "tslib": "2.8.1" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@supabase/postgrest-js": { + "version": "2.87.1", + "resolved": "https://registry.npmjs.org/@supabase/postgrest-js/-/postgrest-js-2.87.1.tgz", + "integrity": "sha512-Yzu5eL3iGmZW0C/8x+vEojAOou63FI9oVw8HI8YOq63+5yM8g8aGh7Y1E2vbXFb7+gHGsPqLnaC6dPhrYt7qBA==", + "license": "MIT", + "dependencies": { + "tslib": "2.8.1" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@supabase/realtime-js": { + "version": "2.87.1", + "resolved": "https://registry.npmjs.org/@supabase/realtime-js/-/realtime-js-2.87.1.tgz", + "integrity": "sha512-XvLtEznxmYZXA7LYuy5zbSXpSYjDLJq2wQeRh3MzON2OR4U8Kq+RtPz2E2Wi8HEzvBfsc+nNu1TG8LQ9+3DRkA==", + "license": "MIT", + "dependencies": { + "@types/phoenix": "^1.6.6", + "@types/ws": "^8.18.1", + "tslib": "2.8.1", + "ws": "^8.18.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@supabase/storage-js": { + "version": "2.87.1", + "resolved": "https://registry.npmjs.org/@supabase/storage-js/-/storage-js-2.87.1.tgz", + "integrity": "sha512-0Uc8tNV4yzkNNmp1inpXru0RB4a7ECq05G2S6BDvSpMxTxJrDVJ4vVDwyhqB8ZZ+O9+8prHaQYoByQeuDnwpFQ==", + "license": "MIT", + "dependencies": { + "iceberg-js": "^0.8.1", + "tslib": "2.8.1" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@supabase/supabase-js": { + "version": "2.87.1", + "resolved": "https://registry.npmjs.org/@supabase/supabase-js/-/supabase-js-2.87.1.tgz", + "integrity": "sha512-tVgqZqnHZVum584KuUKSQZgcy6ZkhVd6gG8QWg2QfIXH9HmXdamauxdVsLXwaNPJxEdOyfAfwIyi5XUsiVYWtg==", + "license": "MIT", + "dependencies": { + "@supabase/auth-js": "2.87.1", + "@supabase/functions-js": "2.87.1", + "@supabase/postgrest-js": "2.87.1", + "@supabase/realtime-js": "2.87.1", + "@supabase/storage-js": "2.87.1" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@types/node": { + "version": "25.0.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-25.0.0.tgz", + "integrity": "sha512-rl78HwuZlaDIUSeUKkmogkhebA+8K1Hy7tddZuJ3D0xV8pZSfsYGTsliGUol1JPzu9EKnTxPC4L1fiWouStRew==", + "license": "MIT", + "dependencies": { + "undici-types": "~7.16.0" + } + }, + "node_modules/@types/phoenix": { + "version": "1.6.7", + "resolved": "https://registry.npmjs.org/@types/phoenix/-/phoenix-1.6.7.tgz", + "integrity": "sha512-oN9ive//QSBkf19rfDv45M7eZPi0eEXylht2OLEXicu5b4KoQ1OzXIw+xDSGWxSxe1JmepRR/ZH283vsu518/Q==", + "license": "MIT" + }, + "node_modules/@types/ws": { + "version": "8.18.1", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz", + "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/body-parser": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.1.tgz", + "integrity": "sha512-nfDwkulwiZYQIGwxdy0RUmowMhKcFVcYXUU7m4QlKYim1rUtg83xm2yjZ40QjDuc291AJjjeSc9b++AWHSgSHw==", + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^1.0.5", + "debug": "^4.4.3", + "http-errors": "^2.0.0", + "iconv-lite": "^0.7.0", + "on-finished": "^2.4.1", + "qs": "^6.14.0", + "raw-body": "^3.0.1", + "type-is": "^2.0.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/content-disposition": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.1.tgz", + "integrity": "sha512-oIXISMynqSqm241k6kcQ5UwttDILMK4BiurCfGEREw6+X9jkkpEe5T9FZaApyLGGOnFuyMWZpdolTXMtvEJ08Q==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/cors": { + "version": "2.8.5", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", + "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/dotenv": { + "version": "17.2.3", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.2.3.tgz", + "integrity": "sha512-JVUnt+DUIzu87TABbhPmNfVdBDt18BLOWjMUFJMSi/Qqg7NTYtabbvSNJGOJ7afbRuv9D/lngizHtP7QyLQ+9w==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz", + "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==", + "license": "MIT", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.2.1", + "content-disposition": "^1.0.0", + "content-type": "^1.0.5", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "depd": "^2.0.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.7", + "qs": "^6.14.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.0.1", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/finalhandler": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", + "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/iceberg-js": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/iceberg-js/-/iceberg-js-0.8.1.tgz", + "integrity": "sha512-1dhVQZXhcHje7798IVM+xoo/1ZdVfzOMIc8/rgVSijRK38EDqOJoGula9N/8ZI5RD8QTxNQtK/Gozpr+qUqRRA==", + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/iconv-lite": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.1.tgz", + "integrity": "sha512-2Tth85cXwGFHfvRgZWszZSvdo+0Xsqmw8k8ZwxScfcBneNUraK+dxRxRm24nszx80Y0TVio8kKLt5sLE7ZCLlw==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "license": "MIT" + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz", + "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", + "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/nodemailer": { + "version": "7.0.11", + "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-7.0.11.tgz", + "integrity": "sha512-gnXhNRE0FNhD7wPSCGhdNh46Hs6nm+uTyg+Kq0cZukNQiYdnCsoQjodNP9BQVG9XrcK/v6/MgpAPBUFyzh9pvw==", + "license": "MIT-0", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.3.0.tgz", + "integrity": "sha512-7jdwVIRtsP8MYpdXSwOS0YdD0Du+qOoF/AEPIt88PcCFrZCzx41oxku1jD88hZBwbNUIEfpqvuhjFaMAqMTWnA==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/qs": { + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.0.tgz", + "integrity": "sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", + "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/router": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/send": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.0.tgz", + "integrity": "sha512-uaW0WwXKpL9blXE2o0bRhoL2EGXIrZxQ2ZQ4mgcfoBxdFmQold+qWsD2jLrfZ0trjKL6vOw0j//eAwcALFjKSw==", + "license": "MIT", + "dependencies": { + "debug": "^4.3.5", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "mime-types": "^3.0.1", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/serve-static": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.0.tgz", + "integrity": "sha512-61g9pCh0Vnh7IutZjtLGGpTA355+OPn2TyDv/6ivP2h/AdAVX9azsoxmg2/M6nZeQZNYBEwIcsne1mJd9oQItQ==", + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", + "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD" + }, + "node_modules/type-is": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.1.tgz", + "integrity": "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==", + "license": "MIT", + "dependencies": { + "content-type": "^1.0.5", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/undici-types": { + "version": "7.16.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz", + "integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==", + "license": "MIT" + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + }, + "node_modules/ws": { + "version": "8.18.3", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz", + "integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + } + } +} diff --git a/backend/package.json b/backend/package.json new file mode 100644 index 0000000..093853f --- /dev/null +++ b/backend/package.json @@ -0,0 +1,20 @@ +{ + "name": "backend", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "", + "license": "ISC", + "type": "commonjs", + "dependencies": { + "@supabase/supabase-js": "^2.87.1", + "cors": "^2.8.5", + "dotenv": "^17.2.3", + "express": "^5.2.1", + "nodemailer": "^7.0.11" + } +} diff --git a/backend/routes/teamRoutes.js b/backend/routes/teamRoutes.js new file mode 100644 index 0000000..e9b07e5 --- /dev/null +++ b/backend/routes/teamRoutes.js @@ -0,0 +1,102 @@ +const express = require("express"); +const router = express.Router(); +const supabase = require("../supabaseClient"); +const { sendConfirmationEmail } = require("../email"); + +console.log("teamRoutes.js loaded"); + +router.get("/test", (req, res) => { + res.send("Team routes are working!"); +}); + +const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; +const phoneRegex = /^\d{10}$/; + +function validatePerson(p) { + if (!p.name) throw "Name is required"; + if (!emailRegex.test(p.email)) throw "Invalid email"; + if (!phoneRegex.test(p.phone)) throw "Phone must be 10 digits"; + if (!p.college) throw "College is required"; + if (!p.year) throw "Year is required"; +} + +router.post("/register", async (req, res) => { + console.log("POST /register hit"); + console.log("Request body:", req.body); + + try { + const { teamName, teamSize, leader, members } = req.body; + + /* ---- BASIC CHECKS ---- */ + if (!teamName) throw "Team name required"; + if (teamSize !== 4) throw "Team size must be 4"; + if (!leader) throw "Leader data missing"; + if (!Array.isArray(members) || members.length !== 3) + throw "Exactly 3 members required"; + + validatePerson(leader); + members.forEach(validatePerson); + + const emails = [ + leader.email, + ...members.map((m) => m.email), + ]; + if (new Set(emails).size !== emails.length) + throw "Duplicate emails not allowed"; + + const { data: teamData, error: teamError } = await supabase + .from("teams_3") + .insert([ + { + team_name: teamName, + team_size: teamSize, + }, + ]) + .select() + .single(); + + if (teamError) throw teamError.message; + + const teamId = teamData.id; + + const { error: leaderError } = await supabase + .from("participants") + .insert([ + { + team_id: teamId, + role: "leader", + ...leader, + }, + ]); + + if (leaderError) throw leaderError.message; + + const membersWithTeam = members.map((m) => ({ + team_id: teamId, + role: "member", + ...m, + })); + + const { error: membersError } = await supabase + .from("participants") + .insert(membersWithTeam); + + if (membersError) throw membersError.message; + + await sendConfirmationEmail(leader.email, teamName); + + return res.status(201).json({ + success: true, + message: "Team registered successfully", + }); + + } catch (err) { + console.error("Register error:", err); + return res.status(400).json({ + success: false, + message: err, + }); + } +}); + +module.exports = router; diff --git a/backend/server.js b/backend/server.js new file mode 100644 index 0000000..194fa12 --- /dev/null +++ b/backend/server.js @@ -0,0 +1,26 @@ +import express from "express"; +import cors from "cors"; +import dotenv from "dotenv"; +import teamRoutes from "./routes/teamRoutes.js"; + +dotenv.config(); + +const app = express(); + +app.use(cors({ + origin: "*", + methods: ["GET", "POST"] +})); + +app.use(express.json()); + +app.use("/api/team", teamRoutes); + +app.get("/", (req, res) => { + res.send("Backend running"); +}); + +const PORT = process.env.PORT || 5050; +app.listen(PORT, () => { + console.log(`Backend running on port ${PORT}`); +}); diff --git a/backend/supabaseClient.js b/backend/supabaseClient.js new file mode 100644 index 0000000..b2e9373 --- /dev/null +++ b/backend/supabaseClient.js @@ -0,0 +1,9 @@ +const { createClient } = require("@supabase/supabase-js"); +require("dotenv").config(); + +const supabase = createClient( + process.env.SUPABASE_URL, + process.env.SUPABASE_SERVICE_ROLE_KEY +); + +module.exports = supabase; diff --git a/backend/templates/email.html b/backend/templates/email.html new file mode 100644 index 0000000..86102f8 --- /dev/null +++ b/backend/templates/email.html @@ -0,0 +1,260 @@ + + + + + + Registration Confirmation + + + +
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+

Registration Confirmed!

+

You have successfully registered for GIT-A-THON 2025.

+
+
+
+

Team Info

+
+
+ + + + + +
+ Team Name + {{teamName}} + + Team Size + {{teamSize}} +
+
+
+
+
+
+

Team Leader

+
+
+ + + + + + + + + + + + + +
+ Name + {{leaderName}} + + Email + {{leaderEmail}} +
+ Phone + {{leaderPhone}} + + College + {{leaderCollege}} +
+ Year + {{leaderYear}} + + GitHub + {{leaderGithub}} +
+
+
+
+
+
+

Member 2

+
+
+ + + + + + + + + + + + + +
+ Name + {{member2Name}} + + Email + {{member2Email}} +
+ Phone + {{member2Phone}} + + College + {{member2College}} +
+ Year + {{member2Year}} + + GitHub + {{member2Github}} +
+
+
+
+
+
+

Member 3

+
+
+ + + + + + + + + + + + + +
+ Name + {{member3Name}} + + Email + {{member3Email}} +
+ Phone + {{member3Phone}} + + College + {{member3College}} +
+ Year + {{member3Year}} + + GitHub + {{member3Github}} +
+
+
+
+
+
+

Member 4

+
+
+ + + + + + + + + + + + + +
+ Name + {{member4Name}} + + Email + {{member4Email}} +
+ Phone + {{member4Phone}} + + College + {{member4College}} +
+ Year + {{member4Year}} + + GitHub + {{member4Github}} +
+
+
+
+ + + + \ No newline at end of file diff --git a/components/Register.jsx b/components/Register.jsx index 512ec66..bebc2da 100644 --- a/components/Register.jsx +++ b/components/Register.jsx @@ -2,6 +2,7 @@ import { useState } from "react"; import { motion, AnimatePresence } from "framer-motion"; +const API_URL = "https://git-a-thon-backend.onrender.com/api/team/register"; export default function Register() { const [step, setStep] = useState(0); @@ -120,12 +121,48 @@ export default function Register() { } }; - const handleSubmit = (e) => { - e.preventDefault(); - console.log("Form Submitted", formData); + const handleSubmit = async (e) => { + e.preventDefault(); + + const payload = { + teamName: formData.teamName, + teamLeaderName: formData.leader.name, + email: formData.leader.email, + phoneNumber: formData.leader.phone, + college: formData.leader.college, + githubProfile: formData.leader.github, + teamSize: formData.teamSize, + problemPreference: formData.problemStatement || "Not selected", + members: formData.members, + }; + + try { + console.log(" Sending payload:", payload); + + const res = await fetch(API_URL, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify(payload), + }); + + const data = await res.json(); + + console.log("📥 Backend response:", data); + + if (!res.ok) { + setError(data.message || "Registration failed"); + return; + } + setDirection(1); setIsSubmitted(true); - }; + } catch (err) { + console.error(" Request failed:", err); + setError("Failed to connect to server. Please try again."); + } +}; const handleReset = () => { setStep(0); diff --git a/verce.json b/verce.json new file mode 100644 index 0000000..25bcd84 --- /dev/null +++ b/verce.json @@ -0,0 +1,14 @@ +{ + "version": 2, + "functions": { + "api/index.js": { + "runtime": "nodejs18.x" + } + }, + "routes": [ + { + "src": "/api/(.*)", + "dest": "/api/index.js" + } + ] +}